Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions apps/server/scripts/replay-project-memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,20 @@ const messages = [
text: "/compact the tenant cache",
created_by: "user",
},
{
message_id: "command-notice",
project_id: "replay-project",
thread_id: "asking-thread",
payload_json: JSON.stringify({
text: "Change cache keys to include tenant IDs.",
createdBy: "agent",
notification: {
source: { kind: "background_command" },
outcome: "completed",
summary: "npm test completed",
},
}),
},
];

it.effect("replays invented facts through recall and names the gate", () =>
Expand All @@ -82,31 +96,34 @@ it.effect("replays invented facts through recall and names the gate", () =>
assert.equal(match?.characters, "Change cache keys to include tenant IDs.".length);
assert.isAbove(match?.candidatesMs ?? -1, -1);
assert.equal(typeof match?.candidatesMs, "number");
assert.equal(byId.get("greeting")?.gate, "not_substantive");
assert.equal(byId.get("greeting")?.candidatesMs, null);
assert.equal(byId.get("greeting")?.gate, "no_match");
assert.equal(typeof byId.get("greeting")?.candidatesMs, "number");
assert.deepEqual(byId.get("greeting")?.deliveredFactIds, []);
assert.equal(byId.get("unrelated")?.gate, "no_match");
assert.deepEqual(byId.get("unrelated")?.deliveredFactIds, []);
assert.equal(byId.get("slash")?.gate, "slash");
assert.equal(byId.get("command-notice")?.gate, "progress_notice");
assert.equal(byId.get("command-notice")?.candidatesMs, null);
assert.deepEqual(byId.get("command-notice")?.deliveredFactIds, []);
assert.equal(summary.byGate.delivered, 1);
assert.equal(summary.byGate.not_substantive, 1);
assert.equal(summary.byGate.no_match, 1);
assert.equal(summary.byGate.no_match, 2);
assert.equal(summary.byGate.slash, 1);
assert.equal(summary.byGate.progress_notice, 1);
assert.equal(summary.byCreatedBy.user?.messages, 3);
assert.equal(summary.byCreatedBy.agent?.messages, 1);
assert.equal(summary.lookupLatencyMs.n, 2);
assert.equal(summary.byCreatedBy.agent?.messages, 2);
assert.equal(summary.lookupLatencyMs.n, 3);
assert.equal(summary.factsLoaded, 1);
const written = (
JSON.parse(yield* fs.readFileString(path.join(out, "summary.json"))) as {
messages: number;
}
).messages;
assert.equal(written, 4);
assert.equal(written, 5);
const lines = (yield* fs.readFileString(path.join(out, "results.ndjson")))
.trim()
.split("\n")
.map((line) => JSON.parse(line) as ReplayRow);
assert.equal(lines.length, 4);
assert.equal(lines.length, 5);
yield* fs.writeFileString(factsPath, "[]");
const failure = yield* replayProjectMemory({
facts: factsPath,
Expand Down
51 changes: 44 additions & 7 deletions apps/server/scripts/replay-project-memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
EnvironmentId,
EventId,
MessageId,
OrchestrationV2Notification,
ProjectFactId,
ProjectId,
ProviderInstanceId,
Expand All @@ -18,6 +19,7 @@ import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodeURL from "node:url";
import * as DateTime from "effect/DateTime";
import * as Schema from "effect/Schema";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
Expand All @@ -38,7 +40,7 @@ const RECALL_TIMEOUT = "1 second";
const GATES = [
"hand_picked",
"slash",
"not_substantive",
"progress_notice",
"allowance",
"kernel_unavailable",
"no_match",
Expand All @@ -59,6 +61,7 @@ export interface ReplayOptions {
readonly project?: string;
readonly factCount?: number;
readonly limit?: number;
readonly candidateLimit?: number;
}

interface NormalizedFact {
Expand All @@ -78,19 +81,24 @@ interface NormalizedMessage {
readonly threadId: string;
readonly createdBy: string;
readonly text: string;
readonly notification?: OrchestrationV2Notification;
readonly noticeKind: string | null;
}

export interface ReplayRow {
readonly messageId: string;
readonly projectId: string;
readonly threadId: string;
readonly createdBy: string;
readonly noticeKind: string | null;
readonly characters: number;
readonly gate: string;
readonly deliveredFactIds: ReadonlyArray<string>;
readonly top: ReadonlyArray<{ readonly factId: string }>;
readonly wallMs: number;
readonly candidatesMs: number | null;
readonly scoringMs: number | null;
readonly statsMs: number | null;
readonly resolveMs: number | null;
readonly seenMs: number | null;
}
Expand Down Expand Up @@ -176,18 +184,20 @@ export const parseReplayArgs = (argv: ReadonlyArray<string>): ReplayOptions => {
const out = read("--out");
if (!factsPath || !messagesPath || !out)
throw new Error(
"Usage: replay-project-memory.ts --facts <facts.json> --messages <msgs.json> --out <dir> [--project <id>] [--fact-count <n>] [--limit <n>]",
"Usage: replay-project-memory.ts --facts <facts.json> --messages <msgs.json> --out <dir> [--project <id>] [--fact-count <n>] [--limit <n>] [--candidate-limit <n>]",
);
const project = read("--project");
const factCount = positiveInteger("--fact-count", read("--fact-count"));
const limit = positiveInteger("--limit", read("--limit"));
const candidateLimit = positiveInteger("--candidate-limit", read("--candidate-limit"));
return {
facts: factsPath,
messages: messagesPath,
out,
...(project ? { project } : {}),
...(factCount === undefined ? {} : { factCount }),
...(limit === undefined ? {} : { limit }),
...(candidateLimit === undefined ? {} : { candidateLimit }),
};
};

Expand Down Expand Up @@ -235,6 +245,8 @@ const normalizeFact = (value: unknown): NormalizedFact => {
};
};

const decodeNotification = Schema.decodeUnknownSync(OrchestrationV2Notification);

const messageText = (row: Record<string, unknown>): { text: string; createdBy: string } => {
if (typeof row.text === "string") {
const createdBy =
Expand All @@ -261,12 +273,26 @@ const normalizeMessage = (value: unknown): NormalizedMessage => {
if (typeof row.project_id !== "string" || typeof row.thread_id !== "string")
throw new Error(`message ${row.message_id} is missing project_id or thread_id`);
const { text, createdBy } = messageText(row);
const payload =
typeof row.payload_json === "string" ? JSON.parse(row.payload_json) : row.payload_json;
const body = typeof payload === "object" && payload !== null ? payload : row;
const raw = (body as Record<string, unknown>).notification;
let notification: NormalizedMessage["notification"];
if (raw !== undefined) {
try {
notification = decodeNotification(raw);
} catch {
notification = undefined;
}
}
return {
messageId: row.message_id,
projectId: row.project_id,
threadId: row.thread_id,
createdBy,
text,
...(notification === undefined ? {} : { notification }),
noticeKind: notification?.source.kind ?? null,
};
};

Expand Down Expand Up @@ -398,6 +424,7 @@ export const summarizeReplay = (
stageMs: {
candidates: stage((row) => row.candidatesMs),
scoring: stage((row) => row.scoringMs),
stats: stage((row) => row.statsMs),
resolve: stage((row) => row.resolveMs),
seen: stage((row) => row.seenMs),
},
Expand Down Expand Up @@ -529,8 +556,8 @@ const recallGate = (outcome: ProjectKnowledge.RecallOutcome): (typeof GATES)[num
return "slash";
case "hand_attached":
return "hand_picked";
case "not_substantive":
return "not_substantive";
case "progress_notice":
return "progress_notice";
case "no_budget":
return "allowance";
case "no_match":
Expand Down Expand Up @@ -632,7 +659,10 @@ const loadFacts = Effect.fn("replay.loadFacts")(function* (
return facts.length;
});

const measureMessage = Effect.fn("replay.measureMessage")(function* (message: NormalizedMessage) {
const measureMessage = Effect.fn("replay.measureMessage")(function* (
message: NormalizedMessage,
candidateLimit: number | undefined,
) {
const knowledge = yield* ProjectKnowledge.ProjectKnowledge;
spans.length = 0;
const started = performance.now();
Expand All @@ -642,6 +672,8 @@ const measureMessage = Effect.fn("replay.measureMessage")(function* (message: No
threadId: ThreadId.make(message.threadId),
requestId: CommandId.make(`memory-recall:${message.messageId}`),
query: message.text,
...(message.notification === undefined ? {} : { notification: message.notification }),
...(candidateLimit === undefined ? {} : { candidateLimit }),
composer: { text: message.text, records: [] },
knowledgeAllowance: KNOWLEDGE_ALLOWANCE,
})
Expand All @@ -652,15 +684,19 @@ const measureMessage = Effect.fn("replay.measureMessage")(function* (message: No
projectId: message.projectId,
threadId: message.threadId,
createdBy: message.createdBy,
noticeKind: message.noticeKind,
characters: message.text.length,
gate: recallGate(outcome),
deliveredFactIds: deliveredFactIds(outcome),
top: outcome._tag === "Omitted" ? [] : (outcome.top ?? []),
wallMs,
candidatesMs:
stageMs("ProjectKnowledgeStore.recallCandidates") ??
stageMs("ProjectKnowledgeStore.candidates"),
scoringMs: stageMs("HolographicMemory.scoreCandidates"),
resolveMs: stageMs("ProjectKnowledge.resolveMatches"),
statsMs: stageMs("ProjectKnowledgeStore.termStats"),
resolveMs:
stageMs("ProjectKnowledge.resolveForTurn") ?? stageMs("ProjectKnowledge.resolveMatches"),
seenMs: stageMs("ProjectKnowledgeStore.seenFactIds"),
};
return row;
Expand Down Expand Up @@ -699,7 +735,8 @@ export const replayProjectMemory = Effect.fn("replay.projectMemory")(function* (
.pipe(Effect.provideService(Tracer.Tracer, tracer));
}
const rows: ReplayRow[] = [];
for (const message of corpus.messages) rows.push(yield* measureMessage(message));
for (const message of corpus.messages)
rows.push(yield* measureMessage(message, options.candidateLimit));
return { loaded, rows };
}).pipe(Effect.provide(knowledgeLayer(dbPath)));
const summary = summarizeReplay(produced.rows, {
Expand Down
55 changes: 55 additions & 0 deletions apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4656,6 +4656,61 @@ effectIt.effect("declares no replayed runs to the summary lookup on a provider s
expect(lookups).toEqual([undefined]);
}),
);
effectIt.effect.each([false, true])(
"manual resume recalls with the original unsent message metadata (%s)",
(notified) =>
Effect.gen(function* () {
const recall = vi.fn<ProjectKnowledge.ProjectKnowledge["Service"]["recall"]>(() =>
Effect.succeed({ _tag: "Skipped", reason: "no_match" }),
);
const harness = makeLocalCommandHarness({
text: "",
manualContinuation: true,
sideChat: { contextRun: "delivered", unsentResume: true },
recallKnowledge: recall,
});
const projection = harness.projection();
harness.setProjection({
...projection,
messages: projection.messages.map((m) =>
m.id === "message-native-account-command"
? {
...m,
notification: {
source: { kind: "system" as const },
outcome: "updated" as const,
summary: "Resumed thread",
},
}
: {
...m,
...(notified
? {
notification: {
source: { kind: "monitor" as const },
outcome: "updated" as const,
summary: "Checks changed",
},
}
: {}),
},
),
});
yield* harness.start;
expect(recall).toHaveBeenCalledOnce();
const input = recall.mock.calls[0]![0];
const original = projection.messages.find(
(m) => m.id !== "message-native-account-command" && m.text === input.query,
);
expect(original).toBeDefined();
expect(input.notification).toEqual(
notified
? { source: { kind: "monitor" }, outcome: "updated", summary: "Checks changed" }
: undefined,
);
expect(input.turn?.messageId).toEqual(original!.id);
}),
);

effectIt.effect("copies the delivered summary receipt onto the handoff activity item", () =>
Effect.gen(function* () {
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/orchestration-v2/ProviderTurnStartService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1951,10 +1951,13 @@ export const layer: Layer.Layer<
threadId: projection.thread.id,
requestId: CommandId.make(`memory-recall:${attempt.id}`),
query: providerMessage.text,
...(providerMessage.notification === undefined
? {}
: { notification: providerMessage.notification }),
composer: pstackComposer,
knowledgeAllowance: budget.knowledgeAllowance,
turn: {
messageId: message.id,
messageId: providerMessage.id,
attemptId: attempt.id,
providerInstanceId: run.providerInstanceId,
providerThreadId: runningProviderThread.id,
Expand Down
7 changes: 5 additions & 2 deletions apps/server/src/peer/PeerLinkRequests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,12 +415,15 @@ const recordPendingCard = (a: Laptop, key: string) =>

/**
* Every row of every table in the laptop's database, as text, to scan for
* anything leaked: events, projections, receipts and outbox alike.
* anything leaked: events, projections, receipts and outbox alike. Virtual
* tables store nothing themselves: FTS rows live in shadow tables, and some
* (fts3tokenize) cannot be scanned at all.
*/
const storedText = (a: Laptop) =>
Effect.gen(function* () {
const tables = yield* a.sql<{ name: string }>`
SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
SELECT name FROM pragma_table_list
WHERE schema = 'main' AND type IN ('table', 'shadow') AND name NOT LIKE 'sqlite_%'
`;
const rows = yield* Effect.forEach(tables, ({ name }) =>
a.sql.unsafe<Record<string, unknown>>(`SELECT * FROM "${name}"`),
Expand Down
Loading
Loading