diff --git a/apps/server/scripts/replay-project-memory.test.ts b/apps/server/scripts/replay-project-memory.test.ts index b0a7cc1ff26ae..71ebd9aa1bb52 100644 --- a/apps/server/scripts/replay-project-memory.test.ts +++ b/apps/server/scripts/replay-project-memory.test.ts @@ -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", () => @@ -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, diff --git a/apps/server/scripts/replay-project-memory.ts b/apps/server/scripts/replay-project-memory.ts index 007e217acd95b..75835081761eb 100644 --- a/apps/server/scripts/replay-project-memory.ts +++ b/apps/server/scripts/replay-project-memory.ts @@ -5,6 +5,7 @@ import { EnvironmentId, EventId, MessageId, + OrchestrationV2Notification, ProjectFactId, ProjectId, ProviderInstanceId, @@ -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"; @@ -38,7 +40,7 @@ const RECALL_TIMEOUT = "1 second"; const GATES = [ "hand_picked", "slash", - "not_substantive", + "progress_notice", "allowance", "kernel_unavailable", "no_match", @@ -59,6 +61,7 @@ export interface ReplayOptions { readonly project?: string; readonly factCount?: number; readonly limit?: number; + readonly candidateLimit?: number; } interface NormalizedFact { @@ -78,6 +81,8 @@ interface NormalizedMessage { readonly threadId: string; readonly createdBy: string; readonly text: string; + readonly notification?: OrchestrationV2Notification; + readonly noticeKind: string | null; } export interface ReplayRow { @@ -85,12 +90,15 @@ export interface ReplayRow { readonly projectId: string; readonly threadId: string; readonly createdBy: string; + readonly noticeKind: string | null; readonly characters: number; readonly gate: string; readonly deliveredFactIds: ReadonlyArray; + 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; } @@ -176,11 +184,12 @@ export const parseReplayArgs = (argv: ReadonlyArray): ReplayOptions => { const out = read("--out"); if (!factsPath || !messagesPath || !out) throw new Error( - "Usage: replay-project-memory.ts --facts --messages --out [--project ] [--fact-count ] [--limit ]", + "Usage: replay-project-memory.ts --facts --messages --out [--project ] [--fact-count ] [--limit ] [--candidate-limit ]", ); 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, @@ -188,6 +197,7 @@ export const parseReplayArgs = (argv: ReadonlyArray): ReplayOptions => { ...(project ? { project } : {}), ...(factCount === undefined ? {} : { factCount }), ...(limit === undefined ? {} : { limit }), + ...(candidateLimit === undefined ? {} : { candidateLimit }), }; }; @@ -235,6 +245,8 @@ const normalizeFact = (value: unknown): NormalizedFact => { }; }; +const decodeNotification = Schema.decodeUnknownSync(OrchestrationV2Notification); + const messageText = (row: Record): { text: string; createdBy: string } => { if (typeof row.text === "string") { const createdBy = @@ -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).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, }; }; @@ -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), }, @@ -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": @@ -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(); @@ -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, }) @@ -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; @@ -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, { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index c2cb3b520ddc7..8e0f84d16f54e 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -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(() => + 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* () { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 5bfe3c2bd0e47..500c4f0db87a3 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -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, diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index f15f348ac8864..c7ef6aaf713df 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -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>(`SELECT * FROM "${name}"`), diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index d00a052408658..9be81f3c23472 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -1364,3 +1364,59 @@ it.effect("registers every migration file", () => ); }).pipe(Effect.provide(NodeServices.layer)), ); + +it.effect( + "backfills project recall frequencies and maintains current facts through lifecycle changes", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 112 }); + const insert = (id: string, project: string) => sql` + INSERT INTO project_knowledge_facts + (id, project_id, status, revision, content, entities_json, tags_json, kind, trust, + retrieval_count, created_at, updated_at, forgotten_at, sources_json, origin_json) + VALUES (${id}, ${project}, 'saved', 1, 'πύλη cobalt cobalt', '["cobalt"]', '["lantern"]', + 'note', 0.6, 0, '2026-11-16', '2026-11-16', NULL, '[]', '{"kind":"user"}')`; + yield* insert("first", "project"); + yield* insert("foreign", "other"); + yield* runMigrations(); + const counts = sql`SELECT term, doc FROM project_knowledge_recall_terms WHERE project_id = 'project' ORDER BY term`; + assert.deepEqual(yield* counts, [ + { term: "cobalt", doc: 1 }, + { term: "lantern", doc: 1 }, + { term: "πύλη", doc: 1 }, + ]); + yield* insert("second", "project"); + yield* sql`UPDATE project_knowledge_facts SET content='cobalt kestrel', entities_json='[]', tags_json='[]' WHERE id='first'`; + assert.deepEqual(yield* counts, [ + { term: "cobalt", doc: 2 }, + { term: "kestrel", doc: 1 }, + { term: "lantern", doc: 1 }, + { term: "πύλη", doc: 1 }, + ]); + yield* sql`UPDATE project_knowledge_facts SET superseded_by_id='first' WHERE id='second'`; + assert.deepEqual(yield* counts, [ + { term: "cobalt", doc: 1 }, + { term: "kestrel", doc: 1 }, + ]); + yield* sql`UPDATE project_knowledge_facts SET superseded_by_id=NULL WHERE id='second'`; + yield* sql`UPDATE project_knowledge_facts SET status='forgotten',content=NULL,entities_json='[]',tags_json='[]',sources_json='[]',forgotten_at='2026-11-17' WHERE id='first'`; + assert.deepEqual(yield* counts, [ + { term: "cobalt", doc: 1 }, + { term: "lantern", doc: 1 }, + { term: "πύλη", doc: 1 }, + ]); + yield* sql`UPDATE project_knowledge_facts SET project_id='other' WHERE id='second'`; + assert.deepEqual(yield* counts, []); + yield* sql`DELETE FROM project_knowledge_facts WHERE id='second'`; + assert.deepEqual( + yield* sql`SELECT term,doc FROM project_knowledge_recall_terms WHERE project_id='other' ORDER BY term`, + [ + { term: "cobalt", doc: 1 }, + { term: "lantern", doc: 1 }, + { term: "πύλη", doc: 1 }, + ], + ); + assert.deepEqual(yield* runMigrations(), []); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 308f2d6d7478b..ff726c15283d8 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -124,6 +124,7 @@ import Migration0110 from "./Migrations/110_ProviderTurnAttemptIndex.ts"; import Migration0111 from "./Migrations/111_TurnItemMessageOrdinalIndex.ts"; import Migration0112 from "./Migrations/112_TurnItemInlineWorkOutput.ts"; import Migration0113 from "./Migrations/113_RepairSubagentGroups.ts"; +import Migration0114 from "./Migrations/114_ProjectKnowledgeRecallIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -240,6 +241,7 @@ const migrationEntries = [ [111, "TurnItemMessageOrdinalIndex", Migration0111], [112, "TurnItemInlineWorkOutput", Migration0112], [113, "RepairSubagentGroups", Migration0113], + [114, "ProjectKnowledgeRecallIndex", Migration0114], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/114_ProjectKnowledgeRecallIndex.ts b/apps/server/src/persistence/Migrations/114_ProjectKnowledgeRecallIndex.ts new file mode 100644 index 0000000000000..a4849964a61eb --- /dev/null +++ b/apps/server/src/persistence/Migrations/114_ProjectKnowledgeRecallIndex.ts @@ -0,0 +1,61 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE VIRTUAL TABLE project_knowledge_fts_vocab USING fts5vocab(project_knowledge_fts, 'row')`; + yield* sql`CREATE VIRTUAL TABLE project_knowledge_tokenizer USING fts3tokenize(unicode61)`; + yield* sql`CREATE TABLE project_knowledge_recall_terms (project_id TEXT NOT NULL, term TEXT NOT NULL, doc INTEGER NOT NULL, PRIMARY KEY (project_id, term)) WITHOUT ROWID`; + yield* sql`CREATE INDEX project_knowledge_recall_current ON project_knowledge_facts(project_id) WHERE status = 'saved' AND superseded_by_id IS NULL`; + yield* sql`INSERT INTO project_knowledge_recall_terms + SELECT f.project_id, t.token, count(DISTINCT f.rowid) + FROM project_knowledge_facts f CROSS JOIN project_knowledge_tokenizer t + WHERE f.status = 'saved' AND f.superseded_by_id IS NULL + AND t.input = f.content || ' ' || f.entities_json || ' ' || f.tags_json + GROUP BY f.project_id, t.token`; + yield* sql` + CREATE TRIGGER project_knowledge_recall_insert AFTER INSERT ON project_knowledge_facts + WHEN new.status = 'saved' AND new.superseded_by_id IS NULL + BEGIN + INSERT INTO project_knowledge_recall_terms (project_id, term, doc) + SELECT new.project_id, token, 1 FROM project_knowledge_tokenizer + WHERE input = new.content || ' ' || new.entities_json || ' ' || new.tags_json + GROUP BY token + ON CONFLICT (project_id, term) DO UPDATE SET doc = doc + 1; + END + `; + yield* sql` + CREATE TRIGGER project_knowledge_recall_delete AFTER DELETE ON project_knowledge_facts + WHEN old.status = 'saved' AND old.superseded_by_id IS NULL + BEGIN + UPDATE project_knowledge_recall_terms SET doc = doc - 1 + WHERE project_id = old.project_id AND term IN ( + SELECT token FROM project_knowledge_tokenizer + WHERE input = old.content || ' ' || old.entities_json || ' ' || old.tags_json + ); + DELETE FROM project_knowledge_recall_terms WHERE project_id = old.project_id AND doc = 0; + END + `; + yield* sql` + CREATE TRIGGER project_knowledge_recall_update_old BEFORE UPDATE OF content, entities_json, tags_json, project_id, status, superseded_by_id ON project_knowledge_facts + WHEN old.status = 'saved' AND old.superseded_by_id IS NULL + BEGIN + UPDATE project_knowledge_recall_terms SET doc = doc - 1 + WHERE project_id = old.project_id AND term IN ( + SELECT token FROM project_knowledge_tokenizer + WHERE input = old.content || ' ' || old.entities_json || ' ' || old.tags_json + ); + DELETE FROM project_knowledge_recall_terms WHERE project_id = old.project_id AND doc = 0; + END + `; + yield* sql` + CREATE TRIGGER project_knowledge_recall_update_new AFTER UPDATE OF content, entities_json, tags_json, project_id, status, superseded_by_id ON project_knowledge_facts + WHEN new.status = 'saved' AND new.superseded_by_id IS NULL + BEGIN + INSERT INTO project_knowledge_recall_terms (project_id, term, doc) + SELECT new.project_id, token, 1 FROM project_knowledge_tokenizer + WHERE input = new.content || ' ' || new.entities_json || ' ' || new.tags_json + GROUP BY token + ON CONFLICT (project_id, term) DO UPDATE SET doc = doc + 1; + END + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index c20fc6509518d..7017dff03064d 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -93,6 +93,7 @@ describe("V2 preview upgrade", () => { [111, "TurnItemMessageOrdinalIndex"], [112, "TurnItemInlineWorkOutput"], [113, "RepairSubagentGroups"], + [114, "ProjectKnowledgeRecallIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -229,6 +230,7 @@ describe("V2 preview upgrade", () => { [111, "TurnItemMessageOrdinalIndex"], [112, "TurnItemInlineWorkOutput"], [113, "RepairSubagentGroups"], + [114, "ProjectKnowledgeRecallIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts index c35844cc358ba..b17b833330e73 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -2286,6 +2286,89 @@ it.effect("recall keeps the most trusted fact when more than the bound match equ }).pipe(Effect.provide(layerTest)), ); +it.effect("recall does not score with the holographic kernel", () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const projectId = ProjectId.make("recall-no-kernel"); + yield* createProject(projectId); + yield* knowledge.mutate(createFact(projectId), { kind: "user" }); + const query = "Change cache keys to include tenant IDs."; + const outcome = yield* knowledge.recall({ + projectId, + threadId: ThreadId.make("recall-no-kernel"), + requestId: CommandId.make("recall-no-kernel"), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }); + assert.deepEqual(attachedFactIds(outcome), [ProjectFactId.make("fact-one")]); + }).pipe( + Effect.provide( + knowledgeTestLayer( + Layer.succeed(HolographicMemory.HolographicMemory, { + scoreCandidates: () => Effect.die("recall must not call HolographicMemory"), + }), + ), + ), + ), +); + +it.effect("recall preserves trust order for equally covered eligible near-duplicates", () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const sql = yield* SqlClient.SqlClient; + const projectId = ProjectId.make("recall-near-duplicates"); + yield* createProject(projectId); + const duplicate = "Ship the ledger labs toggle for billing."; + for (let index = 0; index < 40; index += 1) { + const id = `dup-${index.toString().padStart(2, "0")}`; + yield* knowledge.mutate( + { + ...createFact(projectId, id), + content: duplicate, + entities: [], + tags: [], + }, + { kind: "user" }, + ); + } + yield* knowledge.mutate( + { + ...createFact(projectId, "current"), + content: "The ledger labs toggle gates billing.", + entities: ["ledger labs"], + tags: [], + }, + { kind: "user" }, + ); + for (let index = 0; index < 200; index += 1) + yield* knowledge.mutate( + { + ...createFact(projectId, `pad-${index}`), + content: `Unrelated padding subject ${index} about alphabets and gardens.`, + entities: [], + tags: [], + }, + { kind: "user" }, + ); + yield* sql`UPDATE project_knowledge_facts SET trust = 0.9 WHERE project_id = ${projectId} AND id LIKE 'dup-%'`; + yield* sql`UPDATE project_knowledge_facts SET trust = 0.51 WHERE project_id = ${projectId} AND id = 'current'`; + const query = "Ship the ledger labs toggle for billing."; + const outcome = yield* knowledge.recall({ + projectId, + threadId: ThreadId.make("recall-near-duplicates"), + requestId: CommandId.make("recall-near-duplicates"), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }); + assert.deepEqual(attachedFactIds(outcome), [ + ProjectFactId.make("dup-00"), + ProjectFactId.make("dup-01"), + ]); + }).pipe(Effect.provide(layerTest)), +); + it.effect( "recall attaches an older fact when closer matches were shown or came from this thread", () => @@ -2312,6 +2395,7 @@ it.effect( ...createFact(projectId, factId), commandId: CommandId.make(`create:${factId}`), content: longer, + entities: [], }, { kind: "user" }, ); @@ -2323,11 +2407,14 @@ it.effect( const shownProject = ProjectId.make("recall-older-shown"); const shownThread = ThreadId.make("recall-older-shown"); const shownTarget = yield* saveOlderTarget(shownProject); - const shownIds = Array.from({ length: 45 }, (_, index) => + const shownIds = Array.from({ length: 130 }, (_, index) => ProjectFactId.make(`shown-${index.toString().padStart(2, "0")}`), ); for (const factId of shownIds) - yield* knowledge.mutate(createFact(shownProject, factId), { kind: "user" }); + yield* knowledge.mutate( + { ...createFact(shownProject, factId), entities: [] }, + { kind: "user" }, + ); yield* knowledge.recordViews(shownProject, shownThread, shownIds); assert.deepEqual( attachedFactIds(yield* recallTarget(shownProject, shownThread, "recall-older-shown")), @@ -2347,10 +2434,11 @@ it.effect( messageId: MessageId.make("recall-older-cited-message"), }); if (source.state !== "available") return yield* Effect.die("source unavailable"); - for (let index = 0; index < 45; index++) + for (let index = 0; index < 130; index++) yield* knowledge.mutate( { ...createFact(citedProject, `cited-${index.toString().padStart(2, "0")}`), + entities: [], sources: [source.source], }, { kind: "user" }, @@ -2368,10 +2456,11 @@ it.effect( threadId: originThread, providerInstanceId, }; - for (let index = 0; index < 45; index++) + for (let index = 0; index < 130; index++) yield* knowledge.mutate( { ...createFact(originProject, `origin-${index.toString().padStart(2, "0")}`), + entities: [], sources: [], }, origin, @@ -3377,12 +3466,10 @@ it.effect( ); it.effect("does not consider a newer fact that shares no term with the recall query", () => { - const considered: string[] = []; const scoring = Layer.succeed(HolographicMemory.HolographicMemory, { scoreCandidates: (input) => - Effect.sync(() => { - considered.push(...input.candidates.map((candidate) => candidate.id)); - return input.candidates.map((candidate) => ({ + Effect.sync(() => + input.candidates.map((candidate) => ({ id: candidate.id, rawCosine: 1, holographic: 1, @@ -3393,8 +3480,8 @@ it.effect("does not consider a newer fact that shares no term with the recall qu tokenOverlap: 1, fts: 1, coverage: 1, - })); - }), + })), + ), }); return Effect.gen(function* () { const knowledge = yield* ProjectKnowledge.ProjectKnowledge; @@ -3413,7 +3500,7 @@ it.effect("does not consider a newer fact that shares no term with the recall qu { kind: "user" }, ); const query = "Change cache keys to include tenant IDs."; - yield* knowledge.recall({ + const outcome = yield* knowledge.recall({ projectId, threadId: ThreadId.make("recall-bounded"), requestId: CommandId.make("recall-bounded"), @@ -3421,6 +3508,8 @@ it.effect("does not consider a newer fact that shares no term with the recall qu composer: { text: query, records: [] }, knowledgeAllowance: 48000, }); + const considered = + outcome._tag === "Omitted" ? [] : (outcome.top ?? []).map((item) => item.factId); assert.include(considered, "matching"); assert.notInclude(considered, "newer-unrelated"); const searched = yield* knowledge.search({ @@ -3568,3 +3657,271 @@ it.effect( ); }).pipe(Effect.provide(knowledgeTestLayer(HolographicMemory.layer, true))), ); + +const isolatedFact = ( + projectId: ProjectId, + id: string, + content: string, +): ProjectKnowledgeMutation => ({ + ...createFact(projectId, id), + content, + entities: [], + tags: [], +}); +const recallIdsFor = ( + knowledge: ProjectKnowledge.ProjectKnowledge["Service"], + projectId: ProjectId, + query: string, + request: string, +) => + knowledge + .recall({ + projectId, + threadId: ThreadId.make(request), + requestId: CommandId.make(request), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }) + .pipe(Effect.map(attachedFactIds)); +it.effect("recall in one project depends on facts saved in other projects", () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const seed = (projectId: ProjectId) => + Effect.gen(function* () { + yield* createProject(projectId); + yield* knowledge.mutate( + isolatedFact( + projectId, + `${projectId}-target`, + "React component props must be memoized before passing callbacks to list rows.", + ), + { kind: "user" }, + ); + for (let i = 0; i < 20; i++) + yield* knowledge.mutate( + isolatedFact( + projectId, + `${projectId}-pad-${i}`, + `Deploy note ${i}: rotate gardens alphabet.`, + ), + { kind: "user" }, + ); + }); + const query = + "Why does the list row rerender? Check whether React component props callbacks are memoized."; + const alone = ProjectId.make("op-alone"); + yield* seed(alone); + const before = yield* recallIdsFor(knowledge, alone, query, "alone-before"); + // Another project on the same server saves many React notes. + const other = ProjectId.make("op-other-web-app"); + yield* createProject(other); + for (let i = 0; i < 400; i++) + yield* knowledge.mutate( + isolatedFact( + other, + `other-${i}`, + `React component ${i} props callbacks list rows memoized rerender check ${i}.`, + ), + { kind: "user" }, + ); + const after = yield* recallIdsFor(knowledge, alone, query, "alone-after"); + assert.deepEqual(before, [ProjectFactId.make("op-alone-target")]); + assert.deepEqual(after, before); + const tiedProject = ProjectId.make("isolated-ties"); + yield* createProject(tiedProject); + const contents = ["cobalt kestrel lantern", "orchard harbor willow", "violet copper quartz"]; + for (const [index, content] of contents.entries()) + yield* knowledge.mutate(isolatedFact(tiedProject, `tie-${index}`, content), { kind: "user" }); + const tiedQuery = contents.join(" "); + const tiedBefore = yield* recallIdsFor(knowledge, tiedProject, tiedQuery, "ties-before"); + assert.equal(tiedBefore.length, 2); + const tiedOther = ProjectId.make("isolated-ties-other"); + yield* createProject(tiedOther); + for (let i = 0; i < 100; i++) + yield* knowledge.mutate(isolatedFact(tiedOther, `foreign-tie-${i}`, contents[0]!), { + kind: "user", + }); + const tiedAfter = yield* recallIdsFor(knowledge, tiedProject, tiedQuery, "ties-after"); + assert.deepEqual(tiedAfter, tiedBefore); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("superseded history changes recall of identical active facts", () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const target = "The quokka telemetry exporter batches spans before flushing to the collector."; + const query = + "Why does the quokka telemetry exporter batch spans before flushing to the collector?"; + const fresh = ProjectId.make("op-fresh"); + yield* createProject(fresh); + yield* knowledge.mutate(isolatedFact(fresh, "fresh-target", target), { kind: "user" }); + for (let i = 0; i < 40; i++) + yield* knowledge.mutate( + isolatedFact(fresh, `fresh-pad-${i}`, `Garden note ${i} about alphabets.`), + { + kind: "user", + }, + ); + const freshOut = yield* recallIdsFor(knowledge, fresh, query, "fresh"); + assert.deepEqual(freshOut, [ProjectFactId.make("fresh-target")]); + // Wipe so the two runs see the same corpus apart from history. + const sql = yield* SqlClient.SqlClient; + yield* sql`DELETE FROM project_knowledge_facts WHERE project_id = ${fresh}`; + + const hist = ProjectId.make("op-history"); + yield* createProject(hist); + let current = yield* knowledge.mutate(isolatedFact(hist, "v0", target), { kind: "user" }); + for (let i = 1; i <= 6; i++) + current = yield* knowledge.mutate( + { + action: "supersede", + commandId: CommandId.make(`supersede:${i}`), + projectId: hist, + factId: current.id, + expectedRevision: current.revision, + replacementFactId: ProjectFactId.make(`v${i}`), + content: `${target} (rev ${i})`, + entities: [], + tags: [], + kind: "decision", + sources: [{ kind: "user" }], + }, + { kind: "user" }, + ); + for (let i = 0; i < 40; i++) + yield* knowledge.mutate( + isolatedFact(hist, `hist-pad-${i}`, `Garden note ${i} about alphabets.`), + { + kind: "user", + }, + ); + const histOut = yield* recallIdsFor(knowledge, hist, query, "history"); + + assert.deepEqual(histOut, ["v6"]); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("lost-source fact outranks a valid one", () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const projectId = ProjectId.make("lost-recall"); + yield* createProject(projectId); + const threadId = ThreadId.make("src-thread"); + const messageId = MessageId.make("src-message"); + yield* projections.apply(thread(threadId, projectId)); + yield* projections.apply(message(threadId, messageId, "assistant", "ledger decision")); + const source = yield* knowledge.readSource({ projectId, threadId, messageId }); + if (source.state !== "available") return yield* Effect.die("source unavailable"); + const content = "The ledger labs toggle gates billing changes for invoices."; + yield* knowledge.mutate( + { + ...createFact(projectId, "lost"), + content, + entities: ["ledger labs"], + tags: [], + sources: [source.source], + }, + { kind: "user" }, + ); + yield* knowledge.mutate( + { ...createFact(projectId, "valid"), content, entities: ["ledger labs"], tags: [] }, + { kind: "user" }, + ); + for (let i = 0; i < 40; i += 1) + yield* knowledge.mutate( + { + ...createFact(projectId, `pad-${i}`), + content: `Unrelated padding subject ${i} about alphabets and gardens.`, + entities: [], + tags: [], + }, + { kind: "user" }, + ); + yield* sql`UPDATE project_knowledge_facts SET trust = 0.9 WHERE id = 'lost'`; + yield* sql`UPDATE project_knowledge_facts SET trust = 0.6 WHERE id = 'valid'`; + const run = (id: string) => + knowledge.recall({ + projectId, + threadId: ThreadId.make("t-" + id), + requestId: CommandId.make("r-" + id), + query: content, + composer: { text: content, records: [] }, + knowledgeAllowance: 48000, + }); + const before = yield* run("before"); + assert.deepEqual(attachedFactIds(before), [ + ProjectFactId.make("lost"), + ProjectFactId.make("valid"), + ]); + const archivedThread = yield* projections.getThreadRecords(threadId, []); + yield* projections.apply({ + id: EventId.make("arch"), + threadId, + type: "thread.archived", + occurredAt: at(5), + payload: { ...archivedThread.thread, archivedAt: at(5) }, + }); + const after = yield* run("after"); + assert.deepEqual(attachedFactIds(after), [ProjectFactId.make("valid")]); + }).pipe(Effect.provide(layerTest)), +); + +it.effect( + "recall uses exact terms before the candidate bound and forwards watch notifications", + () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const projectId = ProjectId.make("exact-recall"); + yield* createProject(projectId); + const query = "cobalt lantern kestrel"; + yield* knowledge.mutate( + isolatedFact(projectId, "exact", `${query} ${"garden ".repeat(500)}`), + { kind: "user" }, + ); + for (let i = 0; i < 130; i++) + yield* knowledge.mutate( + isolatedFact(projectId, `prefix-${i}`, "cobalts lanterns kestrels"), + { kind: "user" }, + ); + const input = { + projectId, + threadId: ThreadId.make("exact-reader"), + requestId: CommandId.make("exact-read"), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }; + assert.deepEqual(attachedFactIds(yield* knowledge.recall(input)), [ + ProjectFactId.make("exact"), + ]); + assert.deepEqual( + attachedFactIds( + yield* knowledge.recall({ + ...input, + notification: { + source: { kind: "monitor" }, + outcome: "completed", + summary: "Checks finished", + }, + }), + ), + [], + ); + assert.deepEqual( + attachedFactIds( + yield* knowledge.recall({ + ...input, + notification: { + source: { kind: "command" }, + outcome: "completed", + summary: "Command finished", + }, + }), + ), + [], + ); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.ts b/apps/server/src/project/knowledge/ProjectKnowledge.ts index eed4ff931c97a..9863701d89d23 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.ts @@ -1,9 +1,7 @@ import { ActiveProjectFact, - boundProjectMemoryRecallQuery, - isSubstantiveProjectMemoryQuery, - selectProjectMemoryRecallMatches, type AssistedLearningRun, + type OrchestrationV2Notification, type CommandId, ComposerContextId, type ComposerContextRecord, @@ -66,6 +64,15 @@ import { } from "./persistence.ts"; import * as HolographicMemory from "./HolographicMemory.ts"; import { projectMemorySearchTokens } from "./holographicScoring.ts"; +import { + rankRecallCandidates, + recallTerms, + recallTrigger, + RECALL_CANDIDATE_LIMIT, + RECALL_MAX_FACTS, + RECALL_MESSAGE_CHARS, + type TermStats, +} from "./recallRelevance.ts"; import { conflictHints } from "./knowledgeConflicts.ts"; import { DeliveryScrubRunner } from "./deliveryScrubSchedule.ts"; @@ -75,10 +82,15 @@ type RecallComposer = { }; export type RecallOutcome = - | { readonly _tag: "Attached"; readonly composer: RecallComposer } + | { + readonly _tag: "Attached"; + readonly composer: RecallComposer; + readonly top?: ReadonlyArray<{ readonly factId: string }>; + } | { readonly _tag: "Skipped"; - readonly reason: "slash" | "hand_attached" | "not_substantive" | "no_budget" | "no_match"; + readonly reason: "slash" | "hand_attached" | "progress_notice" | "no_budget" | "no_match"; + readonly top?: ReadonlyArray<{ readonly factId: string }>; } | { readonly _tag: "Omitted"; readonly reason: "timed_out" | "failed" }; const RECALL_CONTEXT_ID = ComposerContextId.make("recall"); @@ -100,12 +112,6 @@ type KnowledgeFormat = "attached" | "recalled"; const recalledPreamble = (projectId: ProjectId) => `Saved facts from project ${projectId}, for reference. Rate any you rely on with t3_knowledge_mutate feedback: helpful, or unhelpful if it misled you.`; -/** Whether a thread's own messages or agent produced this fact, so its agent already has it. */ -const cameFromThread = (fact: Pick, threadId: ThreadId) => - ((fact.origin.kind === "agent-thread" || fact.origin.kind === "assisted") && - fact.origin.threadId === threadId) || - fact.sources.some((source) => source.kind === "message" && source.threadId === threadId); - export class ProjectKnowledge extends Context.Service< ProjectKnowledge, { @@ -158,6 +164,8 @@ export class ProjectKnowledge extends Context.Service< readonly threadId: ThreadId; readonly requestId: CommandId; readonly query: string; + readonly notification?: OrchestrationV2Notification; + readonly candidateLimit?: number; readonly composer: RecallComposer; /** The turn's remaining knowledge budget, in bytes. */ readonly knowledgeAllowance: number; @@ -917,369 +925,302 @@ const make = Effect.gen(function* () { ...(resolved.items ? { items: resolved.items } : {}), }; }); - const searchFacts = Effect.fn("ProjectKnowledge.search")( - // Recall keeps its best two matches after removing facts the thread has already seen. - function* ( - request: ProjectKnowledgeSearchInput, - recallOptions?: { - readonly skip: (fact: ProjectFact) => boolean; - readonly threadId: ThreadId; - readonly excludeFactIds: ReadonlyArray; - }, - ): Effect.fn.Return { - const skip = recallOptions?.skip; - const { - factCursor: _recallFactCursor, - cursor: _recallMessageCursor, - ...recallRequest - } = request; - const input = - recallOptions !== undefined - ? { - ...recallRequest, - query: boundProjectMemoryRecallQuery(request.query), - limit: 8, - } - : request; - yield* requireProject(input.projectId); - if (recallOptions !== undefined && !isSubstantiveProjectMemoryQuery(input.query)) - return { - messages: { matches: [] }, - facts: { - state: "available" as const, - matches: [], - coverage: "complete" as const, - nextCursor: null, - }, - }; - const messages = - recallOptions !== undefined - ? { matches: [] } - : yield* threads - .search({ - ...input, - ...(input.messageLimit === undefined ? {} : { limit: input.messageLimit }), - }) - .pipe(Effect.mapError(storageError(input.projectId))); - const entities = [ - ...new Set((input.entities ?? []).map((entity) => entity.toLowerCase())), - ].sort(); - const minTrust = input.minTrust ?? 0.3; - const queryDigest = yield* encodeQuery({ + const searchFacts = Effect.fn("ProjectKnowledge.search")(function* ( + input: ProjectKnowledgeSearchInput, + ): Effect.fn.Return { + yield* requireProject(input.projectId); + const messages = yield* threads + .search({ + ...input, + ...(input.messageLimit === undefined ? {} : { limit: input.messageLimit }), + }) + .pipe(Effect.mapError(storageError(input.projectId))); + const entities = [ + ...new Set((input.entities ?? []).map((entity) => entity.toLowerCase())), + ].sort(); + const minTrust = input.minTrust ?? 0.3; + const queryDigest = yield* encodeQuery({ + projectId: input.projectId, + query: input.query, + entities, + entityMatch: input.entityMatch ?? "any", + includeArchived: input.includeArchived ?? false, + minTrust, + ...(input.includeSuperseded ? { includeSuperseded: true } : {}), + }).pipe(Effect.flatMap(digest), Effect.mapError(storageError(input.projectId))); + const { cursor: _messageCursor, ...factInput } = input; + const requestDigest = yield* encodeSearch(factInput).pipe( + Effect.flatMap(digest), + Effect.mapError(storageError(input.projectId)), + ); + const searchedAt = yield* DateTime.now; + const receiptsNotBefore = DateTime.formatIso( + DateTime.subtract(searchedAt, { milliseconds: SEARCH_RECEIPT_TTL_MILLIS }), + ); + const prior = yield* store + .receipt(input.requestId, receiptsNotBefore) + .pipe(Effect.mapError(storageError(input.projectId))); + if ( + prior !== null && + (prior.projectId !== input.projectId || + prior.factId !== null || + prior.digest !== requestDigest || + prior.search === null) + ) { + return yield* new ProjectKnowledgeError({ + reason: "command_reused", projectId: input.projectId, - query: input.query, - entities, - entityMatch: input.entityMatch ?? "any", - includeArchived: input.includeArchived ?? false, - minTrust, - ...(input.includeSuperseded ? { includeSuperseded: true } : {}), - }).pipe(Effect.flatMap(digest), Effect.mapError(storageError(input.projectId))); - const { cursor: _messageCursor, ...factInput } = input; - const requestDigest = yield* encodeSearch(factInput).pipe( - Effect.flatMap(digest), - Effect.mapError(storageError(input.projectId)), - ); - const searchedAt = yield* DateTime.now; - const receiptsNotBefore = DateTime.formatIso( - DateTime.subtract(searchedAt, { milliseconds: SEARCH_RECEIPT_TTL_MILLIS }), - ); - const prior = yield* store - .receipt(input.requestId, receiptsNotBefore) + }); + } + const rootRequestId = + prior?.search?.rootRequestId ?? input.factCursor?.requestId ?? input.requestId; + const rootReceipt = + rootRequestId === input.requestId + ? prior + : yield* store + .receipt(rootRequestId, receiptsNotBefore) + .pipe(Effect.mapError(storageError(input.projectId))); + if ( + (input.factCursor !== undefined || prior !== null) && + (rootReceipt === null || + rootReceipt.projectId !== input.projectId || + rootReceipt.search?.ranking == null || + rootReceipt.search.queryDigest !== queryDigest || + (input.factCursor?.offset ?? 0) > rootReceipt.search.ranking.matches.length) + ) { + return yield* new ProjectKnowledgeError({ + reason: "invalid_cursor", + projectId: input.projectId, + }); + } + let ranking = rootReceipt?.search?.ranking ?? null; + if (ranking === null) { + const candidates = yield* store + .candidates( + input.projectId, + projectMemorySearchTokens(input.query), + entities, + minTrust, + input.includeSuperseded ?? false, + ) .pipe(Effect.mapError(storageError(input.projectId))); - if ( - prior !== null && - (prior.projectId !== input.projectId || - prior.factId !== null || - prior.digest !== requestDigest || - prior.search === null) - ) { - return yield* new ProjectKnowledgeError({ - reason: "command_reused", - projectId: input.projectId, - }); - } - const rootRequestId = - prior?.search?.rootRequestId ?? input.factCursor?.requestId ?? input.requestId; - const rootReceipt = - rootRequestId === input.requestId - ? prior - : yield* store - .receipt(rootRequestId, receiptsNotBefore) - .pipe(Effect.mapError(storageError(input.projectId))); - if ( - (input.factCursor !== undefined || prior !== null) && - (rootReceipt === null || - rootReceipt.projectId !== input.projectId || - rootReceipt.search?.ranking == null || - rootReceipt.search.queryDigest !== queryDigest || - (input.factCursor?.offset ?? 0) > rootReceipt.search.ranking.matches.length) - ) { - return yield* new ProjectKnowledgeError({ - reason: "invalid_cursor", - projectId: input.projectId, - }); - } - let ranking = rootReceipt?.search?.ranking ?? null; - if (ranking === null) { - const candidates = yield* ( - recallOptions === undefined - ? store.candidates( - input.projectId, - projectMemorySearchTokens(input.query), - entities, - minTrust, - input.includeSuperseded ?? false, - ) - : store.recallCandidates( - input.projectId, - projectMemorySearchTokens(input.query), - minTrust, - recallOptions.threadId, - recallOptions.excludeFactIds, - ) - ).pipe(Effect.mapError(storageError(input.projectId))); - const eligible = candidates.facts.filter( - (fact): fact is typeof ActiveProjectFact.Type => - fact.status !== "forgotten" && - fact.content !== null && - skip?.(fact) !== true && - (entities.length === 0 || - (input.entityMatch === "all" - ? entities.every((entity) => - fact.entities.some((value) => value.toLowerCase() === entity), - ) - : entities.some((entity) => - fact.entities.some((value) => value.toLowerCase() === entity), - ))), + const eligible = candidates.facts.filter( + (fact): fact is typeof ActiveProjectFact.Type => + fact.status !== "forgotten" && + fact.content !== null && + (entities.length === 0 || + (input.entityMatch === "all" + ? entities.every((entity) => + fact.entities.some((value) => value.toLowerCase() === entity), + ) + : entities.some((entity) => + fact.entities.some((value) => value.toLowerCase() === entity), + ))), + ); + const now = DateTime.toEpochMillis(yield* DateTime.now); + const scored = yield* holographic + .scoreCandidates({ + query: input.query, + now, + candidates: eligible.map((fact) => ({ + id: fact.id, + content: fact.content, + entities: fact.entities, + tags: fact.tags, + trust: fact.trust, + updatedAt: Date.parse(fact.updatedAt), + retrievalCount: fact.retrievalCount, + ...(candidates.ranks.has(fact.id) ? { ftsRank: candidates.ranks.get(fact.id)! } : {}), + })), + }) + .pipe( + Effect.map((scores) => ({ state: "available" as const, scores })), + Effect.catchTags({ + HolographicMemoryError: (cause) => + cause.reason === "unavailable" + ? Effect.succeed({ state: "unavailable" as const }) + : Effect.fail( + new ProjectKnowledgeError({ + reason: "scoring", + projectId: input.projectId, + cause, + }), + ), + }), ); - const now = DateTime.toEpochMillis(yield* DateTime.now); - const scored = yield* holographic - .scoreCandidates({ - query: input.query, - now, - candidates: eligible.map((fact) => ({ - id: fact.id, - content: fact.content, - entities: fact.entities, - tags: fact.tags, + if (scored.state === "unavailable") + return { messages, facts: { state: "unavailable", reason: "kernel_unavailable" } }; + const snapshots = new Map(eligible.map((fact) => [fact.id, fact])); + const matches = scored.scores.flatMap((score) => { + const fact = snapshots.get(ProjectFactId.make(score.id)); + if (!fact) return []; + return [ + { + factId: fact.id, + revision: fact.revision, + updatedAt: fact.updatedAt, + scoreMillionths: score.scoreMillionths, + score: { + holographic: score.holographic, + lexical: score.fts, + tokenOverlap: score.tokenOverlap, + temporalDecay: score.decay, + reinforcement: score.reinforcement, trust: fact.trust, - updatedAt: Date.parse(fact.updatedAt), - retrievalCount: fact.retrievalCount, - ...(candidates.ranks.has(fact.id) ? { ftsRank: candidates.ranks.get(fact.id)! } : {}), - })), - }) - .pipe( - Effect.map((scores) => ({ state: "available" as const, scores })), - Effect.catchTags({ - HolographicMemoryError: (cause) => - cause.reason === "unavailable" - ? Effect.succeed({ state: "unavailable" as const }) - : Effect.fail( - new ProjectKnowledgeError({ - reason: "scoring", - projectId: input.projectId, - cause, - }), - ), - }), - ); - if (scored.state === "unavailable") - return { messages, facts: { state: "unavailable", reason: "kernel_unavailable" } }; - const snapshots = new Map(eligible.map((fact) => [fact.id, fact])); - const matches = scored.scores.flatMap((score) => { - const fact = snapshots.get(ProjectFactId.make(score.id)); - if (!fact) return []; - return [ - { - factId: fact.id, - revision: fact.revision, - updatedAt: fact.updatedAt, - scoreMillionths: score.scoreMillionths, - score: { - holographic: score.holographic, - lexical: score.fts, - tokenOverlap: score.tokenOverlap, - temporalDecay: score.decay, - reinforcement: score.reinforcement, - trust: fact.trust, - combined: score.score, - }, + combined: score.score, }, - ]; + }, + ]; + }); + matches.sort( + (left, right) => + right.scoreMillionths - left.scoreMillionths || + (left.updatedAt < right.updatedAt ? 1 : left.updatedAt > right.updatedAt ? -1 : 0) || + (left.factId < right.factId ? -1 : left.factId > right.factId ? 1 : 0), + ); + ranking = { + matches: matches.map(({ factId, revision, score }) => ({ factId, revision, score })), + coverage: candidates.partial ? "partial" : "complete", + }; + } + const initialRanking = ranking; + const limit = input.limit ?? 20; + const recallable = ( + fact: ProjectFact | undefined, + revision: number, + ): fact is typeof ActiveProjectFact.Type => + fact !== undefined && + fact.revision === revision && + fact.status !== "forgotten" && + fact.content !== null && + (fact.supersededBy == null || input.includeSuperseded === true); + // Walks ranked positions in order and checks citations a batch at a time, so a page reads + // sources for about as many facts as it returns instead of for the whole ranking. + const resolveMatches = Effect.fn("ProjectKnowledge.resolveMatches")(function* ( + searchReceipt: SearchReceipt | null, + ) { + const ranked = searchReceipt?.ranking ?? initialRanking; + const positions = + searchReceipt?.positions ?? + ranked.matches.map((_, position) => position).slice(input.factCursor?.offset ?? 0); + // A fresh page looks one past the limit to know whether a continuation exists. + const take = searchReceipt === null ? limit + 1 : positions.length; + const resolved: Array<{ + readonly fact: typeof ActiveProjectFact.Type; + readonly score: typeof KnowledgeScore.Type; + readonly position: number; + }> = []; + let next = 0; + while (resolved.length < take && next < positions.length) { + const batch = positions.slice(next, next + Math.max(take - resolved.length, RESOLVE_BATCH)); + next += batch.length; + const current = new Map( + (yield* store.findMany( + input.projectId, + batch.map((position) => ranked.matches[position]!.factId), + )).map((fact) => [fact.id, fact]), + ); + const candidates = batch.flatMap((position) => { + const match = ranked.matches[position]!; + const fact = current.get(match.factId); + return recallable(fact, match.revision) ? [{ fact, score: match.score, position }] : []; }); - matches.sort( - (left, right) => - right.scoreMillionths - left.scoreMillionths || - (left.updatedAt < right.updatedAt ? 1 : left.updatedAt > right.updatedAt ? -1 : 0) || - (left.factId < right.factId ? -1 : left.factId > right.factId ? 1 : 0), + const lost = new Set( + (yield* unavailableSources( + input.projectId, + candidates.map((candidate) => candidate.fact), + input.includeArchived ?? false, + )).map((item) => item.factId), ); - ranking = { - matches: matches.map(({ factId, revision, score }) => ({ factId, revision, score })), - coverage: candidates.partial ? "partial" : "complete", - }; + for (const candidate of candidates) + if (!lost.has(candidate.fact.id) && resolved.length < take) resolved.push(candidate); } - const initialRanking = ranking; - const limit = input.limit ?? 20; - const recallable = ( - fact: ProjectFact | undefined, - revision: number, - ): fact is typeof ActiveProjectFact.Type => - fact !== undefined && - fact.revision === revision && - fact.status !== "forgotten" && - fact.content !== null && - (fact.supersededBy == null || input.includeSuperseded === true); - // Walks ranked positions in order and checks citations a batch at a time, so a page reads - // sources for about as many facts as it returns instead of for the whole ranking. - const resolveMatches = Effect.fn("ProjectKnowledge.resolveMatches")(function* ( - searchReceipt: SearchReceipt | null, - ) { - const ranked = searchReceipt?.ranking ?? initialRanking; - const positions = - searchReceipt?.positions ?? - ranked.matches.map((_, position) => position).slice(input.factCursor?.offset ?? 0); - // A fresh page looks one past the limit to know whether a continuation exists. - const take = searchReceipt === null ? limit + 1 : positions.length; - const resolved: Array<{ - readonly fact: typeof ActiveProjectFact.Type; - readonly score: typeof KnowledgeScore.Type; - readonly position: number; - }> = []; - let next = 0; - while (resolved.length < take && next < positions.length) { - const batch = positions.slice( - next, - next + Math.max(take - resolved.length, RESOLVE_BATCH), - ); - next += batch.length; + return { ranked, resolved }; + }); + // Citation checks are reads; they run before the write transaction, which only re-reads + // the rows of the facts it returns. + const early = yield* resolveMatches(prior?.search ?? null).pipe( + Effect.mapError(storageError(input.projectId)), + ); + return yield* sql + .withTransaction( + Effect.gen(function* () { + yield* requireProject(input.projectId); + const receipt = yield* store.receipt(input.requestId, receiptsNotBefore); + if ( + receipt !== null && + (receipt.projectId !== input.projectId || + receipt.factId !== null || + receipt.digest !== requestDigest) + ) { + return yield* new ProjectKnowledgeError({ + reason: "command_reused", + projectId: input.projectId, + }); + } + const searchReceipt = receipt?.search ?? null; + // A duplicate request can commit its receipt after the early read; follow it. + const { ranked, resolved } = + (searchReceipt === null) === (prior?.search == null) + ? early + : yield* resolveMatches(searchReceipt); + const page = searchReceipt === null ? resolved.slice(0, limit) : resolved; const current = new Map( (yield* store.findMany( input.projectId, - batch.map((position) => ranked.matches[position]!.factId), + page.map((match) => match.fact.id), )).map((fact) => [fact.id, fact]), ); - const candidates = batch.flatMap((position) => { - const match = ranked.matches[position]!; - const fact = current.get(match.factId); - return recallable(fact, match.revision) && skip?.(fact) !== true - ? [{ fact, score: match.score, position }] - : []; + const selected = page.flatMap((match) => { + const fact = current.get(match.fact.id); + return recallable(fact, match.fact.revision) ? [{ ...match, fact }] : []; }); - const lost = new Set( - (yield* unavailableSources( + const last = page.at(-1); + const nextOffset = + searchReceipt === null + ? resolved.length > page.length && last !== undefined + ? last.position + 1 + : null + : searchReceipt.nextOffset; + const reinforce = receipt === null && input.recordRetrieval !== false; + if (reinforce) + yield* store.recordRetrieval( input.projectId, - candidates.map((candidate) => candidate.fact), - input.includeArchived ?? false, - )).map((item) => item.factId), - ); - for (const candidate of candidates) - if (!lost.has(candidate.fact.id) && resolved.length < take) resolved.push(candidate); - } - return { ranked, resolved }; - }); - // Citation checks are reads; they run before the write transaction, which only re-reads - // the rows of the facts it returns. - const early = yield* resolveMatches(prior?.search ?? null).pipe( - Effect.mapError(storageError(input.projectId)), - ); - if (recallOptions !== undefined) - return { - messages, - facts: { - state: "available" as const, - matches: selectProjectMemoryRecallMatches({ - messages: { matches: [] }, - facts: { - state: "available", - matches: early.resolved.map(({ fact, score }) => ({ fact, score })), - coverage: early.ranked.coverage, - nextCursor: null, - }, - }), - coverage: early.ranked.coverage, - nextCursor: null, - }, - }; - return yield* sql - .withTransaction( - Effect.gen(function* () { - yield* requireProject(input.projectId); - const receipt = yield* store.receipt(input.requestId, receiptsNotBefore); - if ( - receipt !== null && - (receipt.projectId !== input.projectId || - receipt.factId !== null || - receipt.digest !== requestDigest) - ) { - return yield* new ProjectKnowledgeError({ - reason: "command_reused", - projectId: input.projectId, - }); - } - const searchReceipt = receipt?.search ?? null; - // A duplicate request can commit its receipt after the early read; follow it. - const { ranked, resolved } = - (searchReceipt === null) === (prior?.search == null) - ? early - : yield* resolveMatches(searchReceipt); - const page = searchReceipt === null ? resolved.slice(0, limit) : resolved; - const current = new Map( - (yield* store.findMany( - input.projectId, - page.map((match) => match.fact.id), - )).map((fact) => [fact.id, fact]), + selected.map((match) => match.fact.id), ); - const selected = page.flatMap((match) => { - const fact = current.get(match.fact.id); - return recallable(fact, match.fact.revision) ? [{ ...match, fact }] : []; - }); - const last = page.at(-1); - const nextOffset = - searchReceipt === null - ? resolved.length > page.length && last !== undefined - ? last.position + 1 - : null - : searchReceipt.nextOffset; - const reinforce = receipt === null && input.recordRetrieval !== false; - if (reinforce) - yield* store.recordRetrieval( - input.projectId, - selected.map((match) => match.fact.id), - ); - if (receipt === null) { - yield* store.recordSearch( - input.requestId, - input.projectId, - requestDigest, - { - rootRequestId, - queryDigest, - ranking: input.factCursor === undefined ? ranked : null, - positions: selected.map((match) => match.position), - nextOffset, - }, - DateTime.formatIso(searchedAt), - receiptsNotBefore, - ); - } - return { - messages, - facts: { - state: "available" as const, - matches: selected.map(({ fact, score }) => ({ - fact: reinforce ? { ...fact, retrievalCount: fact.retrievalCount + 1 } : fact, - score, - })), - coverage: ranked.coverage, - nextCursor: - nextOffset === null ? null : { requestId: rootRequestId, offset: nextOffset }, + if (receipt === null) { + yield* store.recordSearch( + input.requestId, + input.projectId, + requestDigest, + { + rootRequestId, + queryDigest, + ranking: input.factCursor === undefined ? ranked : null, + positions: selected.map((match) => match.position), + nextOffset, }, - }; - }), - ) - .pipe(Effect.mapError(storageError(input.projectId))); - }, - ); + DateTime.formatIso(searchedAt), + receiptsNotBefore, + ); + } + return { + messages, + facts: { + state: "available" as const, + matches: selected.map(({ fact, score }) => ({ + fact: reinforce ? { ...fact, retrievalCount: fact.retrievalCount + 1 } : fact, + score, + })), + coverage: ranked.coverage, + nextCursor: + nextOffset === null ? null : { requestId: rootRequestId, offset: nextOffset }, + }, + }; + }), + ) + .pipe(Effect.mapError(storageError(input.projectId))); + }); const search: ProjectKnowledge["Service"]["search"] = (input, viewer) => searchFacts(input).pipe( Effect.tap((result) => @@ -1313,10 +1254,11 @@ const make = Effect.gen(function* () { }).pipe(Effect.andThen(note({ _tag: "Omitted", reason }))); if (input.composer.records.some((record) => record.kind === "project-knowledge")) return yield* note({ _tag: "Skipped", reason: "hand_attached" }); - if (input.query.trimStart().startsWith("/")) - return yield* note({ _tag: "Skipped", reason: "slash" }); - if (!isSubstantiveProjectMemoryQuery(input.query)) - return yield* note({ _tag: "Skipped", reason: "not_substantive" }); + const trigger = recallTrigger({ + text: input.query, + ...(input.notification === undefined ? {} : { notification: input.notification }), + }); + if (!trigger.recall) return yield* note({ _tag: "Skipped", reason: trigger.reason }); const factBytes = Math.min( RECALL_MAX_BYTES, Math.floor(input.knowledgeAllowance) - RECALL_ENVELOPE_BYTES, @@ -1324,29 +1266,57 @@ const make = Effect.gen(function* () { if (factBytes < RECALL_MIN_BYTES) return yield* note({ _tag: "Skipped", reason: "no_budget" }); const lookup = Effect.gen(function* () { + const text = input.query.slice(0, RECALL_MESSAGE_CHARS); + const messageTokens = yield* store + .tokenize([text]) + .pipe(Effect.mapError(storageError(input.projectId))); + const terms = [...recallTerms(text, (value) => messageTokens.get(value)!)]; const seen = yield* store .seenFactIds(input.projectId, input.threadId, input.turn) .pipe(Effect.mapError(storageError(input.projectId))); - const result = yield* searchFacts( - { - projectId: input.projectId, - requestId: input.requestId, - query: input.query, - recordRetrieval: false, - minTrust: 0.5, - }, - { - skip: (fact) => seen.has(fact.id) || cameFromThread(fact, input.threadId), - threadId: input.threadId, - excludeFactIds: [...seen], - }, + const candidates = yield* store + .recallCandidates( + input.projectId, + terms, + 0.5, + input.threadId, + [...seen], + input.candidateLimit ?? RECALL_CANDIDATE_LIMIT, + ) + .pipe(Effect.mapError(storageError(input.projectId))); + const active = candidates.facts.flatMap((fact) => + fact.status === "forgotten" || fact.content === null ? [] : [fact], ); - if (result.facts.state !== "available") return yield* omit("failed"); - const selections = result.facts.matches.map(({ fact }) => ({ - kind: "fact" as const, - factId: fact.id, - revision: fact.revision, - })); + const tokens = yield* store + .tokenize(active.map((fact) => [fact.content, ...fact.entities].join(" "))) + .pipe(Effect.mapError(storageError(input.projectId))); + const tokenize = (value: string): ReadonlyArray => + tokens.get(value) ?? messageTokens.get(value) ?? []; + const allTerms = new Set(terms); + for (const fact of active) + for (const term of recallTerms([fact.content, ...fact.entities].join(" "), tokenize)) + allTerms.add(term); + const counted = yield* store + .termStats([...allTerms], input.projectId) + .pipe(Effect.mapError(storageError(input.projectId))); + const stats: TermStats = { + corpusSize: counted.corpusSize, + docs: (term) => counted.docs.get(term) ?? 0, + tokenize, + }; + const ranked = rankRecallCandidates(text, active, stats, input.notification); + const top = ranked.slice(0, 5).map((match) => ({ factId: match.fact.id })); + const selections = []; + for (const match of ranked) { + if (!match.passes) continue; + if (!(yield* sourcesAvailable(match.fact, false))) continue; + selections.push({ + kind: "fact" as const, + factId: match.fact.id, + revision: match.fact.revision, + }); + if (selections.length === RECALL_MAX_FACTS) break; + } const environmentId = yield* environment.getEnvironmentId; // Drop the weakest match until the rest resolve within the turn's knowledge budget. for (let count = selections.length; count > 0; count--) { @@ -1369,13 +1339,14 @@ const make = Effect.gen(function* () { if (Option.isSome(resolved)) return { _tag: "Attached" as const, + top, composer: { text: `${input.composer.text}\n\n${formatComposerContextReference(record)}`, records: [...input.composer.records, record], }, }; } - return { _tag: "Skipped" as const, reason: "no_match" as const }; + return { _tag: "Skipped" as const, reason: "no_match" as const, top }; }).pipe(NodeSqliteClient.readOnly); return yield* lookup.pipe( Effect.timeoutOption(RECALL_TIMEOUT), diff --git a/apps/server/src/project/knowledge/persistence.ts b/apps/server/src/project/knowledge/persistence.ts index 6374cdc0f9d60..2936eaad3c770 100644 --- a/apps/server/src/project/knowledge/persistence.ts +++ b/apps/server/src/project/knowledge/persistence.ts @@ -68,6 +68,14 @@ const FactRow = Schema.Struct({ const encodeOrigin = Schema.encodeSync(Schema.fromJsonString(KnowledgeOrigin)); const encodeFactIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(ProjectFactId))); const encodeLabels = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); +const decodeTokenRows = Schema.decodeUnknownEffect( + Schema.Array( + Schema.Struct({ + text: Schema.String, + tokens: Schema.fromJsonString(Schema.Array(Schema.String)), + }), + ), +); const encodeSources = Schema.encodeSync(Schema.fromJsonString(Schema.Array(KnowledgeFactSource))); const decodeRows = Schema.decodeUnknownEffect(Schema.Array(FactRow)); const decodeProjectFacts = Schema.decodeUnknownEffect(Schema.Array(ProjectFact)); @@ -156,9 +164,12 @@ const withoutForgotten = ( ); }; -const ftsMatch = (terms: ReadonlyArray) => +const ftsMatch = (terms: ReadonlyArray, exact = false) => terms - .map((term) => `"${term.replaceAll('"', '""')}"${Buffer.byteLength(term) >= 4 ? "*" : ""}`) + .map((term) => { + const quoted = `"${term.replaceAll('"', '""')}"`; + return exact || Buffer.byteLength(term) < 4 ? quoted : `${quoted}*`; + }) .join(" OR "); export const makeStore = Effect.gen(function* () { @@ -309,22 +320,52 @@ export const makeStore = Effect.gen(function* () { partial: ids.length > 1000, }; }); + const tokenize = Effect.fn("ProjectKnowledgeStore.tokenize")(function* ( + texts: ReadonlyArray, + ) { + const rows = yield* sql<{ readonly text: string; readonly tokens: string }>` + SELECT j.value AS text, + (SELECT json_group_array(token) FROM project_knowledge_tokenizer WHERE input = j.value) AS tokens + FROM json_each(${encodeLabels([...new Set(texts)])}) j`; + const tokens = new Map>(); + for (const row of yield* decodeTokenRows(rows)) tokens.set(row.text, row.tokens); + return tokens; + }); + const termStats = Effect.fn("ProjectKnowledgeStore.termStats")(function* ( + terms: ReadonlyArray, + projectId: ProjectId, + ) { + const [count] = yield* sql<{ + readonly n: number; + }>`SELECT count(*) AS n FROM project_knowledge_facts WHERE project_id=${projectId} AND status='saved' AND superseded_by_id IS NULL`; + const rows = + terms.length === 0 + ? [] + : yield* sql<{ + readonly term: string; + readonly doc: number; + }>`SELECT term, doc FROM project_knowledge_recall_terms WHERE project_id=${projectId} AND ${sql.in("term", terms)}`; + return { + corpusSize: Number(count?.n ?? 0), + docs: new Map(rows.map((r) => [r.term, Number(r.doc)])), + }; + }); const recallCandidates = Effect.fn("ProjectKnowledgeStore.recallCandidates")(function* ( projectId: ProjectId, terms: ReadonlyArray, minTrust: number, threadId: ThreadId, excludeFactIds: ReadonlyArray, + limit: number, ) { - const ftsQuery = ftsMatch(terms); - if (ftsQuery === "") - return { facts: [], ranks: new Map(), partial: false }; + const ftsQuery = ftsMatch(terms, true); + if (ftsQuery === "") return { facts: [], partial: false }; const unseen = excludeFactIds.length === 0 ? sql`1 = 1` : sql`f.id NOT IN (SELECT value FROM json_each(${encodeFactIds(excludeFactIds)}))`; - const rows = yield* sql<{ readonly id: ProjectFactId; readonly rank: number }>` - SELECT f.id, bm25(project_knowledge_fts) AS rank + const rows = yield* sql<{ readonly id: ProjectFactId }>` + SELECT f.id FROM project_knowledge_fts JOIN project_knowledge_facts f ON f.rowid = project_knowledge_fts.rowid WHERE project_knowledge_fts MATCH ${ftsQuery} AND f.project_id = ${projectId} AND f.status = 'saved' AND f.trust >= ${minTrust} AND f.superseded_by_id IS NULL @@ -338,13 +379,17 @@ export const makeStore = Effect.gen(function* () { WHERE json_extract(source.value, '$.kind') = 'message' AND json_extract(source.value, '$.threadId') = ${threadId} ) - ORDER BY rank ASC, f.trust DESC, f.updated_at DESC, f.id ASC LIMIT 40`; + ORDER BY f.trust DESC, f.updated_at DESC, f.id ASC LIMIT ${limit}`; + const loaded = yield* findMany( + projectId, + rows.map((row) => row.id), + ); + const byId = new Map(loaded.map((fact) => [fact.id, fact])); return { - facts: yield* findMany( - projectId, - rows.map((row) => row.id), - ), - ranks: new Map(rows.map((row) => [row.id, row.rank])), + facts: rows.flatMap((row) => { + const fact = byId.get(row.id); + return fact === undefined ? [] : [fact]; + }), partial: false, }; }); @@ -812,6 +857,8 @@ export const makeStore = Effect.gen(function* () { record, recordSearch, candidates, + tokenize, + termStats, recallCandidates, similar, findDuplicateContent, diff --git a/apps/server/src/project/knowledge/recallRelevance.test.ts b/apps/server/src/project/knowledge/recallRelevance.test.ts new file mode 100644 index 0000000000000..4baf90d2f1fa0 --- /dev/null +++ b/apps/server/src/project/knowledge/recallRelevance.test.ts @@ -0,0 +1,407 @@ +import * as NodeSqlite from "node:sqlite"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import type { OrchestrationV2NotificationSource } from "@t3tools/contracts"; + +import { renderSeatTurnPrompt } from "../../orchestration-v2/GroupPrompt.ts"; +import { runMigrations } from "../../persistence/Migrations.ts"; +import { + recallForMessage, + recallTokens, + recallTrigger, + rankRecallCandidates, + type RecallFactText, + type RecallMessage, + type TermStats, +} from "./recallRelevance.ts"; + +const CORPUS = 718; +const docsFor = (rare: ReadonlyArray, common: ReadonlyArray) => { + const docs = new Map(); + for (const term of rare) docs.set(term, 1); + for (const term of common) docs.set(term, 200); + return docs; +}; + +const stats: TermStats = { + corpusSize: CORPUS, + docs: (term) => + docsFor( + ["ledger", "labs", "toggle", "gates", "billing", "changes", "enable", "ship", "acme"], + [ + "continue", + "remaining", + "work", + "keep", + "current", + "structure", + "place", + "same", + "checkout", + ], + ).get(term) ?? 0, +}; + +const ledger: RecallFactText = { + id: "ledger-labs", + content: "The ledger labs toggle gates billing changes.", + entities: ["ledger labs"], +}; + +const remaining: RecallFactText = { + id: "remaining-work", + content: "Continue the remaining work in the same checkout.", + entities: ["checkout"], +}; + +const receipts: RecallFactText = { + id: "receipt-archive", + content: + "Archive receipts preserve invoice timestamps during nightly exports and reconciliation.", + entities: ["receipt archive"], +}; + +const facts = [ledger, remaining, receipts]; + +const filler = "Continue the remaining work and keep the current structure in place. "; +const boilerplate = filler.repeat(Math.ceil(240 / filler.length)).slice(0, 240); +const delegateBrief = `${boilerplate}Enable the ledger labs toggle before billing changes.`; + +const idsFor = (message: RecallMessage) => + recallForMessage(message, facts, stats).map((fact) => fact.id); + +it("recalls a fact the message actually names, and stays quiet otherwise", () => { + assert.isAbove(boilerplate.length, 200); + assert.isBelow(delegateBrief.length, 8_192); + const buried = `${"padding ".repeat(2_000)}Enable the ledger labs toggle`; + assert.isAbove(buried.indexOf("Enable"), 8_192); + const seat = renderSeatTurnPrompt({ + delta: [ + { + label: "Ada", + model: null, + text: "Enable the ledger labs toggle before billing changes.", + }, + ], + reaction: false, + }); + const cases: ReadonlyArray<{ + readonly name: string; + readonly message: RecallMessage; + readonly ids: ReadonlyArray; + }> = [ + { + name: "delegate brief names the fact after the boilerplate", + message: { text: delegateBrief }, + ids: ["ledger-labs", "remaining-work"], + }, + { + name: "a narrow fact covers too little of a broad message", + message: { + text: `${Array.from({ length: 300 }, (_, index) => `orchard${index}`).join(" ")} Enable the ledger labs toggle before billing changes.`, + }, + ids: [], + }, + { + name: "a short request fully covers a common fact", + message: { text: "continue with remaining work" }, + ids: ["remaining-work"], + }, + { + name: "can you also do the work here", + message: { text: "can you also do the work here" }, + ids: [], + }, + { + name: "background command notice", + message: { + text: "Background command finished (exit code 0) after the ledger labs toggle.", + notification: { source: { kind: "command" } }, + }, + ids: [], + }, + { + name: "subagent completion notice", + message: { + text: "Subagent finished the ledger labs toggle.", + notification: { source: { kind: "subagent" } }, + }, + ids: [], + }, + { + name: "pull request watch has only seven matching terms", + message: { + text: "Checks failed: archive receipts preserve invoice timestamps during exports.", + notification: { source: { kind: "monitor" } }, + }, + ids: [], + }, + { + name: "pull request watch has eight matching terms", + message: { + text: "Checks failed: archive receipts preserve invoice timestamps during nightly exports.", + notification: { source: { kind: "monitor" } }, + }, + ids: ["receipt-archive"], + }, + { + name: "a person names the fact", + message: { text: "Enable the ledger labs toggle" }, + ids: ["ledger-labs"], + }, + { + name: "a seat prompt names the fact and has no notification", + message: { text: seat }, + ids: ["ledger-labs"], + }, + { + name: "a slash command", + message: { text: "/enable the ledger labs toggle" }, + ids: [], + }, + { + name: "the fact is named only past the character bound", + message: { text: buried }, + ids: [], + }, + ]; + assert.deepEqual( + recallForMessage({ text: "continue with remaining work" }, facts, { + ...stats, + corpusSize: 2000, + }).map((fact) => fact.id), + ["remaining-work"], + ); + assert.deepEqual( + cases.map((entry) => [entry.name, idsFor(entry.message)]), + cases.map((entry) => [entry.name, entry.ids]), + ); +}); + +it("classifies every notification kind, and only a pull request watch stays eligible", () => { + const expectSkip: { [Kind in OrchestrationV2NotificationSource["kind"]]: boolean } = { + command: true, + subagent: true, + background_task: true, + system: true, + group: true, + delegated_task: true, + monitor: false, + }; + for (const kind of Object.keys(expectSkip) as Array) { + const trigger = recallTrigger({ + text: "Enable the ledger labs toggle", + notification: { source: { kind } }, + }); + assert.equal(trigger.recall, !expectSkip[kind]); + } +}); + +it.effect("splits terms the way the FTS vocabulary does", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations(); + const content = "The naïve billing-ledger Café_Menu 2026 ok"; + const entities = JSON.stringify(["Café Menu"]); + yield* sql` + INSERT INTO project_knowledge_facts ( + id, project_id, status, revision, content, entities_json, tags_json, kind, trust, + retrieval_count, created_at, updated_at, forgotten_at, sources_json, origin_json + ) VALUES ( + 'fact-tokens', 'project-tokens', 'saved', 1, ${content}, ${entities}, '[]', 'note', 0.5, + 0, '2026-11-16T00:00:00.000Z', '2026-11-16T00:00:00.000Z', NULL, '[]', '{"kind":"user"}' + ) + `; + const rows = yield* sql<{ readonly term: string }>` + SELECT term FROM project_knowledge_fts_vocab ORDER BY term + `; + const indexed = new Set(rows.map((row) => row.term)); + assert.deepEqual([...recallTokens(`${content} Café Menu`)].sort(), [...indexed].sort()); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); + +it("uses unicode61 tokens across scripts and identifier punctuation", () => { + const db = new NodeSqlite.DatabaseSync(":memory:"); + try { + db.exec( + "CREATE VIRTUAL TABLE sample USING fts5(content); CREATE VIRTUAL TABLE vocab USING fts5vocab(sample, 'row')", + ); + const samples = [ + "café naïve résumé Ærøskøbing straße İstanbul Cấu hình kết nối cơ sở dữ liệu", + "πύλη πληρωμών απορρίπτει συναλλαγές Σ σ ς Ελληνικά", + "Привет мир тестирование", + "캐시 키에는 테넌트 한국어텍스트", + "ガバナンス ばなな キャッシュキー", + "数据库连接池配置 東京タワー", + "การย้ายฐานข้อมูล ภายใน ธุรกรรม", + "हिन्दी भाषा परीक्षण", + "filesystem FULLWIDTH ①②③ x²y³ ㎒", + "emoji🚀rocket deploy✅done", + "snake_case-name dotted.name path/to/file.ts CamelCase HTTPServer2", + "a\u0301 e\u0302\u0301 क\u093f क\u094dष", + ]; + for (const text of samples) { + db.exec("DELETE FROM sample"); + db.prepare("INSERT INTO sample(content) VALUES (?)").run(text); + const indexed = db + .prepare("SELECT term FROM vocab ORDER BY term") + .all() + .map((row) => row.term); + assert.deepEqual([...recallTokens(text)].sort(), indexed, text); + } + } finally { + db.close(); + } +}); + +it("enforces coverage, overlap and relevance order", () => { + const shared = "cobalt kestrel lantern"; + const padding = + "orchard harbor willow badger meadow pebble granite thistle otter falcon river maple"; + const fact = (id: string, content: string, entities: string[] = []): RecallFactText => ({ + id, + content, + entities, + }); + const cases = [ + { + name: "long unspaced Han token", + text: "数据库连接池配置", + facts: [fact("han", "数据库连接池配置")], + docs: 1, + ids: ["han"], + }, + { + name: "short Han token", + text: "数据库", + facts: [fact("short-han", "数据库")], + docs: 1, + ids: [], + }, + { + name: "stopwords", + text: "can you please", + facts: [fact("stopwords", "can you please")], + docs: 1, + ids: [], + }, + { + name: "short identifiers", + text: "go db ui", + facts: [fact("short-terms", "go db ui")], + docs: 1, + ids: [], + }, + { + name: "two matched terms", + text: "cobalt kestrel", + facts: [fact("two", shared)], + docs: 1, + ids: [], + }, + { + name: "coverage below thirty percent on both sides", + text: `${shared} ${padding}`, + facts: [ + fact( + "low", + `${shared} violet copper quartz blossom crimson spruce coral eucalyptus fern almond cedar silver`, + ), + ], + docs: 1, + ids: [], + }, + { + name: "entity terms match alongside content", + text: shared, + facts: [fact("entity", "Formatting preferences apply locally.", [shared])], + docs: 1, + ids: ["entity"], + }, + { + name: "query coverage carries a narrow request", + text: shared, + facts: [fact("broad", `${shared} ${padding}`)], + docs: 1, + ids: ["broad"], + }, + { + name: "fact coverage carries a broad brief", + text: `${shared} ${padding}`, + facts: [fact("narrow", shared)], + docs: 1, + ids: ["narrow"], + }, + { + name: "leading whitespace before slash", + text: ` \n\t/${shared}`, + facts: [fact("slash", shared)], + docs: 1, + ids: [], + }, + { + name: "empty indexed content", + text: shared, + facts: [fact("empty", "!!!")], + docs: 1, + ids: [], + }, + { + name: "relevance orders the two attachments", + text: `${shared} orchard harbor willow badger meadow pebble granite`, + facts: [ + fact("weak", `${shared} violet copper quartz blossom crimson spruce coral`), + fact("middle", `${shared} orchard harbor violet copper quartz blossom crimson`), + fact("strong", `${shared} orchard harbor willow badger meadow violet copper`), + ], + docs: 1, + ids: ["strong", "middle"], + }, + ]; + for (const row of cases) { + const attached = recallForMessage({ text: row.text }, row.facts, { + corpusSize: CORPUS, + docs: () => row.docs, + }); + assert.deepEqual( + attached.map((f) => f.id), + row.ids, + row.name, + ); + } + assert.deepEqual( + recallForMessage( + { text: "数据库连接池配置", notification: { source: { kind: "monitor" } } }, + [fact("han", "数据库连接池配置")], + stats, + ), + [], + ); + assert.deepEqual( + rankRecallCandidates("!!!", [fact("empty", "!!!")], stats).filter((m) => m.passes), + [], + ); +}); + +it("weights distinctive terms", () => { + const shared = "cobalt kestrel lantern"; + const query = `${shared} violet copper quartz meadow harbor zircon`; + const ranked = rankRecallCandidates( + query, + [ + { id: "common", content: `${shared} crimson spruce coral birch cypress`, entities: [] }, + { id: "distinctive", content: "violet copper quartz willow fern almond", entities: [] }, + ], + { + corpusSize: 64, + docs: (term) => + "cobalt kestrel lantern willow fern almond".split(" ").includes(term) ? 50 : 1, + }, + ); + assert.deepEqual( + ranked.filter((m) => m.passes).map((m) => m.fact.id), + ["distinctive"], + ); +}); diff --git a/apps/server/src/project/knowledge/recallRelevance.ts b/apps/server/src/project/knowledge/recallRelevance.ts new file mode 100644 index 0000000000000..eaa546c06dbf2 --- /dev/null +++ b/apps/server/src/project/knowledge/recallRelevance.ts @@ -0,0 +1,169 @@ +import * as NodeSqlite from "node:sqlite"; +import type { OrchestrationV2NotificationSource } from "@t3tools/contracts"; + +/** How much of a message recall reads. A delegate brief's task starts after the boilerplate. */ +export const RECALL_MESSAGE_CHARS = 8_192; +export const RECALL_MAX_FACTS = 2; +const RECALL_MIN_MATCHED_TERMS = 3; +const RECALL_MONITOR_MIN_MATCHED_TERMS = 8; +const RECALL_MIN_COVERAGE = 0.3; +const RECALL_MIN_MESSAGE_COVERAGE = 0.028; +// 40 hid a current fact behind near-duplicates. 100 and 200 delivered the same facts here, and 200 slowed the tail. +export const RECALL_CANDIDATE_LIMIT = 100; + +const RECALL_STOPWORDS = new Set( + `the and for this that with please help can you could would want need hello there thanks +are was were is be to of in on it as at by an or not from into when should must use keep only any all its their +than then also but if so do does did done has have had will just make sure each every other more most some such +these those them they we our us your dont before after without within while where which who what +how why same new via per out up down off over under again once here now still yet very cannot never +always may might shall one two three first second last next using used uses`.split(/\s+/), +); + +/** The part of a user message that decides recall. Progress is the notification, not who created it. */ +export interface RecallMessage { + readonly text: string; + readonly notification?: { + readonly source: { readonly kind: OrchestrationV2NotificationSource["kind"] }; + }; +} + +export type RecallTrigger = + | { readonly recall: true } + | { readonly recall: false; readonly reason: "slash" | "progress_notice" }; + +/** A saved fact as the gate reads it. Trust, sources, and thread identity are decided earlier. */ +export interface RecallFactText { + readonly id: string; + readonly content: string; + readonly entities: ReadonlyArray; +} + +/** Project-local document frequencies of current saved facts. */ +export interface TermStats { + readonly tokenize?: (text: string) => Iterable; + readonly corpusSize: number; + readonly docs: (term: string) => number; +} + +export interface RecallMatch { + readonly fact: Fact; + readonly relevance: number; + readonly passes: boolean; +} + +/** Standalone adapter; recall batches the same tokenizer on its read-only connection. */ +const tokenizeRecallText = (text: string): ReadonlyArray => { + const db = new NodeSqlite.DatabaseSync(":memory:"); + try { + db.exec("CREATE VIRTUAL TABLE tokens USING fts3tokenize(unicode61)"); + return db + .prepare("SELECT token FROM tokens WHERE input = ?") + .all(text) + .map((row) => String(row.token)); + } finally { + db.close(); + } +}; + +export const recallTokens = (text: string): ReadonlySet => + new Set(tokenizeRecallText(text)); + +export const recallTerms = ( + text: string, + tokenize: (text: string) => Iterable = tokenizeRecallText, +): ReadonlySet => + new Set([...tokenize(text)].filter((token) => token.length >= 3 && !RECALL_STOPWORDS.has(token))); + +/** Work already under way. A pull-request watch stays eligible and the gate decides. */ +const isProgressNotice = (kind: OrchestrationV2NotificationSource["kind"]): boolean => { + switch (kind) { + case "command": + case "subagent": + case "background_task": + case "system": + case "group": + case "delegated_task": + return true; + case "monitor": + return false; + default: { + const unexpected: never = kind; + return unexpected; + } + } +}; + +export const recallTrigger = (message: RecallMessage): RecallTrigger => { + const kind = message.notification?.source.kind; + if (kind !== undefined && isProgressNotice(kind)) + return { recall: false, reason: "progress_notice" }; + if (message.text.trimStart().startsWith("/")) return { recall: false, reason: "slash" }; + return { recall: true }; +}; + +const idf = (docs: number, corpusSize: number) => Math.log(1 + corpusSize / (1 + docs)); + +export const rankRecallCandidates = ( + message: string, + facts: ReadonlyArray, + stats: TermStats, + notification?: RecallMessage["notification"], +): ReadonlyArray> => { + const minimumMatchedTerms = + notification?.source.kind === "monitor" + ? RECALL_MONITOR_MIN_MATCHED_TERMS + : RECALL_MIN_MATCHED_TERMS; + const text = message.slice(0, RECALL_MESSAGE_CHARS); + const tokenize = stats.tokenize ?? tokenizeRecallText; + const queryTerms = recallTerms(text, tokenize); + const queryMass = [...queryTerms].reduce( + (sum, term) => sum + idf(stats.docs(term), stats.corpusSize), + 0, + ); + const ranked = facts.flatMap((fact) => { + const terms = recallTerms([fact.content, ...fact.entities].join(" "), tokenize); + const matched = [...queryTerms].filter((term) => terms.has(term)); + const hit = matched.reduce((sum, term) => sum + idf(stats.docs(term), stats.corpusSize), 0); + const factMass = [...terms].reduce( + (sum, term) => sum + idf(stats.docs(term), stats.corpusSize), + 0, + ); + const queryCoverage = queryMass === 0 ? 0 : hit / queryMass; + const factCoverage = factMass === 0 ? 0 : hit / factMass; + const relevance = Math.max(queryCoverage, factCoverage); + const passes = + (matched.length >= minimumMatchedTerms || + (minimumMatchedTerms === RECALL_MIN_MATCHED_TERMS && + matched.some( + (term) => + /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(term) && + term.length >= 6, + ))) && + relevance >= RECALL_MIN_COVERAGE && + queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE; + return [{ fact, relevance, passes }]; + }); + // Equal coverage preserves project-local trust and recency order. + ranked.sort((left, right) => right.relevance - left.relevance); + return ranked; +}; + +const selectRecallMatches = ( + message: RecallMessage, + facts: ReadonlyArray, + stats: TermStats, +): ReadonlyArray> => + rankRecallCandidates(message.text, facts, stats, message.notification) + .filter((match) => match.passes) + .slice(0, RECALL_MAX_FACTS); + +/** Facts recall would attach for this message. Notices and slash commands attach none. */ +export const recallForMessage = ( + message: RecallMessage, + facts: ReadonlyArray, + stats: TermStats, +): ReadonlyArray => { + if (!recallTrigger(message).recall) return []; + return selectRecallMatches(message, facts, stats).map((match) => match.fact); +}; diff --git a/packages/contracts/src/projectKnowledge.test.ts b/packages/contracts/src/projectKnowledge.test.ts index d89aba6ac7aa1..f124fd571695d 100644 --- a/packages/contracts/src/projectKnowledge.test.ts +++ b/packages/contracts/src/projectKnowledge.test.ts @@ -3,15 +3,12 @@ import * as Schema from "effect/Schema"; import { ProjectKnowledgeDelivery, - ProjectKnowledgeSearchResult, - selectProjectMemoryRecallMatches, ProjectKnowledgeListInput, ProjectKnowledgeListResult, ProjectKnowledgeMutation, ProjectKnowledgeStatus, } from "./projectKnowledge.ts"; -const decodeSearchResult = Schema.decodeUnknownSync(ProjectKnowledgeSearchResult); const decodeDelivery = Schema.decodeUnknownSync(ProjectKnowledgeDelivery); const decodeList = Schema.decodeUnknownSync(ProjectKnowledgeListResult); @@ -140,46 +137,3 @@ it.each(["over_budget", "source_unavailable", "stale_revision", "not_permitted", expect(decodeDelivery({ ...oldDelivery, omissions }).omissions).toEqual(omissions); }, ); - -describe("project memory recall matches", () => { - it("keeps only strong cited matches and bounds optional context", () => { - const score = { - holographic: 1, - lexical: 1, - tokenOverlap: 0.4, - temporalDecay: 1, - reinforcement: 1, - trust: 0.8, - combined: 1, - }; - const result = decodeSearchResult({ - messages: { matches: [] }, - facts: { - state: "available", - coverage: "complete", - nextCursor: null, - matches: [ - { fact: { ...fact({ kind: "user" }), id: "uncited" }, score }, - { - fact: { ...fact({ kind: "user" }), id: "weak", sources: [{ kind: "user" }] }, - score: { ...score, lexical: 0, tokenOverlap: 0.01 }, - }, - ...["first", "second", "third"].map((id) => ({ - fact: { ...fact({ kind: "user" }), id, sources: [{ kind: "user" }] }, - score, - })), - ], - }, - }); - expect(selectProjectMemoryRecallMatches(result).map((item) => item.fact.id)).toEqual([ - "first", - "second", - ]); - expect( - selectProjectMemoryRecallMatches({ - ...result, - facts: { state: "unavailable", reason: "kernel_unavailable" }, - }), - ).toEqual([]); - }); -}); diff --git a/packages/contracts/src/projectKnowledge.ts b/packages/contracts/src/projectKnowledge.ts index 325f4e2b356e3..2de5b40aa0e35 100644 --- a/packages/contracts/src/projectKnowledge.ts +++ b/packages/contracts/src/projectKnowledge.ts @@ -18,7 +18,6 @@ import { ProviderInstanceId } from "./providerInstance.ts"; import { OrchestrationSearchThreadsInput, OrchestrationSearchThreadsResult, - THREAD_SEARCH_QUERY_MAX_LENGTH, } from "./threadSearch.ts"; export const ProjectFactId = TrimmedNonEmptyString.pipe(Schema.brand("ProjectFactId")); @@ -497,71 +496,6 @@ const ProjectKnowledgeSearchResultSchema = Schema.Struct({ ]), }); export type ProjectKnowledgeSearchResult = typeof ProjectKnowledgeSearchResultSchema.Type; -export interface ProjectMemoryRecallMatch { - readonly fact: ProjectFact; - readonly score: typeof KnowledgeScore.Type; -} - -export function boundProjectMemoryRecallQuery(query: string): string { - return query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH); -} - -const memoryQueryFiller = new Set([ - "the", - "and", - "for", - "this", - "that", - "with", - "please", - "help", - "can", - "you", - "could", - "would", - "want", - "need", - "hello", - "there", - "thanks", -]); -const memoryQueryTerms = (query: string) => [ - ...new Set( - ( - boundProjectMemoryRecallQuery(query) - .toLowerCase() - .match(/[\p{L}\p{N}_/:.]+/gu) ?? [] - ).filter((term) => term.length >= 3 && !memoryQueryFiller.has(term)), - ), -]; - -export function isSubstantiveProjectMemoryQuery(query: string): boolean { - const terms = memoryQueryTerms(query); - return ( - terms.length >= 3 || - terms.some( - (term) => - /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(term) && term.length >= 6, - ) - ); -} - -export function selectProjectMemoryRecallMatches( - result: ProjectKnowledgeSearchResult, -): ReadonlyArray { - if (result.facts.state !== "available") return []; - return result.facts.matches - .filter( - ({ fact, score }) => - fact.status === "saved" && - fact.supersededBy == null && - fact.sources.length > 0 && - score.trust >= 0.5 && - score.combined > 0 && - (score.tokenOverlap >= 0.15 || (score.lexical >= 0.65 && score.tokenOverlap >= 0.05)), - ) - .slice(0, 2); -} export const ProjectKnowledgeSearchResult: Schema.Codec< ProjectKnowledgeSearchResult,