From 2009155b12ffcebc0639802fb9b32648435d312b Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 12:24:05 -0800 Subject: [PATCH 01/10] fix(server): project memory recall matches the whole message and skips progress notices Recall was reading the first 200 characters and a token ratio that rewarded short vague messages, and it attached facts to notices about work already running. It now reads up to 8,192 characters, keeps a fact when rare terms or an entity phrase cover the message or the fact, and skips progress notices. A pull-request watch stays eligible. Co-Authored-By: Claude Fable 5.2 Co-authored-by: Cursor --- .../scripts/replay-project-memory.test.ts | 33 +- apps/server/scripts/replay-project-memory.ts | 51 +- .../ProviderTurnStartService.ts | 1 + apps/server/src/persistence/Migrations.ts | 2 + .../113_ProjectKnowledgeFtsVocab.ts | 9 + .../knowledge/ProjectKnowledge.test.ts | 98 ++- .../src/project/knowledge/ProjectKnowledge.ts | 728 +++++++++--------- .../src/project/knowledge/persistence.ts | 42 +- .../project/knowledge/recallRelevance.test.ts | 192 +++++ .../src/project/knowledge/recallRelevance.ts | 167 ++++ .../contracts/src/projectKnowledge.test.ts | 46 -- packages/contracts/src/projectKnowledge.ts | 66 -- 12 files changed, 910 insertions(+), 525 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts create mode 100644 apps/server/src/project/knowledge/recallRelevance.test.ts create mode 100644 apps/server/src/project/knowledge/recallRelevance.ts 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.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index bd5db353885c3..c55e3666c2bc6 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1952,6 +1952,7 @@ export const layer: Layer.Layer< threadId: projection.thread.id, requestId: CommandId.make(`memory-recall:${attempt.id}`), query: providerMessage.text, + ...(message.notification === undefined ? {} : { notification: message.notification }), composer: pstackComposer, knowledgeAllowance: budget.knowledgeAllowance, turn: { diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index e5b04315655ed..5f72e2968a3dc 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -123,6 +123,7 @@ import Migration0109 from "./Migrations/109_QueuedTurnInputIndexJsonValid.ts"; 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_ProjectKnowledgeFtsVocab.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -238,6 +239,7 @@ const migrationEntries = [ [110, "ProviderTurnAttemptIndex", Migration0110], [111, "TurnItemMessageOrdinalIndex", Migration0111], [112, "TurnItemInlineWorkOutput", Migration0112], + [113, "ProjectKnowledgeFtsVocab", Migration0113], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts b/apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts new file mode 100644 index 0000000000000..d16e716d45814 --- /dev/null +++ b/apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts @@ -0,0 +1,9 @@ +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') + `; +}); diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts index 385accd092733..9e7c32c024955 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -1828,13 +1828,13 @@ it.effect("browsing searches can opt out of reinforcing retrieval counts", () => yield* knowledge.mutate( { ...createFact(projectId, "unicode"), - content: "缓存键必须包含租户标识", + content: "缓存键 必须包 含租户标", entities: [], tags: [], }, { kind: "user" }, ); - assert.deepEqual(yield* recalled("suggest-unicode", "缓存键必须包含租户标识"), [ + assert.deepEqual(yield* recalled("suggest-unicode", "缓存键 必须包 含租户标"), [ ProjectFactId.make("unicode"), ]); assert.deepEqual(yield* recalled("suggest-filler", "please can you help"), []); @@ -2251,6 +2251,86 @@ 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 returns the current fact when stale near-duplicates fill a page of 40", () => + 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("current")]); + }).pipe(Effect.provide(layerTest)), +); + it.effect( "recall attaches an older fact when closer matches were shown or came from this thread", () => @@ -3342,12 +3422,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, @@ -3358,8 +3436,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; @@ -3378,7 +3456,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"), @@ -3386,6 +3464,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({ diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.ts b/apps/server/src/project/knowledge/ProjectKnowledge.ts index f2f93faa1acb4..f180d631a3bb5 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; @@ -908,369 +916,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) => @@ -1304,10 +1245,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, @@ -1315,29 +1257,52 @@ 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 terms = [...recallTerms(text)]; 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 messageStats = yield* store + .termStats(terms) + .pipe(Effect.mapError(storageError(input.projectId))); + const present = terms.filter((term) => (messageStats.docs.get(term) ?? 0) > 0); + const candidates = yield* store + .recallCandidates( + input.projectId, + present, + 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 missing = new Set(); + for (const fact of active) + for (const term of recallTerms([fact.content, ...fact.entities].join(" "))) + if (!messageStats.docs.has(term)) missing.add(term); + const extra = + missing.size === 0 + ? messageStats + : yield* store + .termStats([...missing]) + .pipe(Effect.mapError(storageError(input.projectId))); + const docs = new Map([...messageStats.docs, ...extra.docs]); + const stats: TermStats = { + corpusSize: messageStats.corpusSize, + docs: (term) => docs.get(term) ?? 0, + }; + const ranked = rankRecallCandidates(text, active, stats); + const top = ranked.slice(0, 5).map((match) => ({ factId: match.fact.id })); + const selections = ranked + .flatMap((match) => + match.passes + ? [{ kind: "fact" as const, factId: match.fact.id, revision: match.fact.revision }] + : [], + ) + .slice(0, RECALL_MAX_FACTS); 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--) { @@ -1360,13 +1325,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..b6d73d1d58b4a 100644 --- a/apps/server/src/project/knowledge/persistence.ts +++ b/apps/server/src/project/knowledge/persistence.ts @@ -156,9 +156,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,14 +312,31 @@ export const makeStore = Effect.gen(function* () { partial: ids.length > 1000, }; }); + const termStats = Effect.fn("ProjectKnowledgeStore.termStats")(function* ( + terms: ReadonlyArray, + ) { + const [count] = yield* sql<{ + readonly n: number; + }>`SELECT count(*) AS n FROM project_knowledge_fts`; + const corpusSize = Number(count?.n ?? 0); + if (terms.length === 0) return { corpusSize, docs: new Map() }; + const rows = yield* sql<{ readonly term: string; readonly doc: number }>` + SELECT term, doc FROM project_knowledge_fts_vocab WHERE ${sql.in("term", terms)} + `; + return { + corpusSize, + docs: new Map(rows.map((row) => [row.term, Number(row.doc)])), + }; + }); const recallCandidates = Effect.fn("ProjectKnowledgeStore.recallCandidates")(function* ( projectId: ProjectId, terms: ReadonlyArray, minTrust: number, threadId: ThreadId, excludeFactIds: ReadonlyArray, + limit: number, ) { - const ftsQuery = ftsMatch(terms); + const ftsQuery = ftsMatch(terms, true); if (ftsQuery === "") return { facts: [], ranks: new Map(), partial: false }; const unseen = @@ -338,12 +358,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 rank ASC, 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), - ), + facts: rows.flatMap((row) => { + const fact = byId.get(row.id); + return fact === undefined ? [] : [fact]; + }), ranks: new Map(rows.map((row) => [row.id, row.rank])), partial: false, }; @@ -812,6 +837,7 @@ export const makeStore = Effect.gen(function* () { record, recordSearch, candidates, + 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..461395500a7c0 --- /dev/null +++ b/apps/server/src/project/knowledge/recallRelevance.test.ts @@ -0,0 +1,192 @@ +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, + 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 facts = [ledger, remaining]; + +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"], + }, + { + name: "continue with remaining work", + message: { text: "continue with remaining work" }, + ids: [], + }, + { + 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 names the fact", + message: { + text: "Checks failed for the ledger labs toggle.", + notification: { source: { kind: "monitor" } }, + }, + ids: ["ledger-labs"], + }, + { + 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( + 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).filter((term) => term.length >= 3)); + assert.deepEqual([...recallTokens(`${content} Café Menu`)].sort(), [...indexed].sort()); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/project/knowledge/recallRelevance.ts b/apps/server/src/project/knowledge/recallRelevance.ts new file mode 100644 index 0000000000000..f13cada31edb7 --- /dev/null +++ b/apps/server/src/project/knowledge/recallRelevance.ts @@ -0,0 +1,167 @@ +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_MIN_HIT = 10; +const RECALL_TUNED_CORPUS_SIZE = 718; +const RECALL_MIN_COVERAGE = 0.3; +// 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; +} + +/** Document frequencies from the FTS vocabulary. `docs` is 0 for a term no fact contains. */ +export interface TermStats { + readonly corpusSize: number; + readonly docs: (term: string) => number; +} + +export interface RecallMatch { + readonly fact: Fact; + readonly relevance: number; + readonly passes: boolean; +} + +const TOKEN = /[\p{L}\p{N}]+/gu; + +const fold = (text: string) => text.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase(); + +/** Same splits as the FTS5 unicode61 tokenizer, keeping tokens of at least 3 characters. */ +export const recallTokens = (text: string): ReadonlySet => { + const tokens = fold(text).match(TOKEN) ?? []; + return new Set(tokens.filter((token) => token.length >= 3)); +}; + +export const recallTerms = (text: string): ReadonlySet => + new Set([...recallTokens(text)].filter((token) => !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)); + +// `hit >= 10` was tuned at 718 facts. Below that it scales with ln(1+N), because three rare terms cannot sum to 10. +const recallHitFloor = (corpusSize: number) => + corpusSize >= RECALL_TUNED_CORPUS_SIZE + ? RECALL_MIN_HIT + : (RECALL_MIN_HIT * Math.log(1 + corpusSize)) / Math.log(1 + RECALL_TUNED_CORPUS_SIZE); + +const phraseIn = (entity: string, message: string) => { + const phrase = fold(entity.trim()); + if (phrase.length < 4) return false; + const escaped = phrase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`(? recallTerms([fact.content, ...fact.entities].join(" ")); + +export const rankRecallCandidates = ( + message: string, + facts: ReadonlyArray, + stats: TermStats, +): ReadonlyArray> => { + const text = message.slice(0, RECALL_MESSAGE_CHARS); + const queryTerms = recallTerms(text); + const queryMass = [...queryTerms].reduce( + (sum, term) => sum + idf(stats.docs(term), stats.corpusSize), + 0, + ); + const rareCeiling = Math.max(2, Math.floor(stats.corpusSize * 0.03)); + const floor = recallHitFloor(stats.corpusSize); + const ranked = facts.flatMap((fact) => { + const terms = factTerms(fact); + if (terms.size === 0) return []; + 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 rare = matched.some((term) => stats.docs(term) <= rareCeiling); + const entity = fact.entities.some((value) => phraseIn(value, text)); + // A fact contained in the message stays eligible when every saved fact uses the same words and idf collapses. + const passes = + matched.length >= RECALL_MIN_MATCHED_TERMS && + relevance >= RECALL_MIN_COVERAGE && + (rare || entity) && + (hit >= floor || factCoverage >= RECALL_MIN_COVERAGE); + return [{ fact, relevance, passes }]; + }); + // Stable, so equal coverage keeps the candidate order: bm25, then trust, then recency. + ranked.sort((left, right) => right.relevance - left.relevance); + return ranked; +}; + +const selectRecallMatches = ( + message: string, + facts: ReadonlyArray, + stats: TermStats, +): ReadonlyArray> => + rankRecallCandidates(message, facts, stats) + .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.text, 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 80c4ea03dd1b4..e9fbb53e4786c 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")); @@ -493,71 +492,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, From 7f13ebebefac5aa295e957b1c829f026273c5ec3 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 12:44:12 -0800 Subject: [PATCH 02/10] test(server): reject incidental recall in broad messages --- apps/server/src/project/knowledge/recallRelevance.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/apps/server/src/project/knowledge/recallRelevance.test.ts b/apps/server/src/project/knowledge/recallRelevance.test.ts index 461395500a7c0..14a5c7afaaaaa 100644 --- a/apps/server/src/project/knowledge/recallRelevance.test.ts +++ b/apps/server/src/project/knowledge/recallRelevance.test.ts @@ -88,6 +88,13 @@ it("recalls a fact the message actually names, and stays quiet otherwise", () => message: { text: delegateBrief }, ids: ["ledger-labs"], }, + { + 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: "continue with remaining work", message: { text: "continue with remaining work" }, From a9523bf93058d2cb7db9dd3af2eac28ee1b28bed Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 12:55:20 -0800 Subject: [PATCH 03/10] fix(server): bound recall overlap and avoid redundant entity checks --- apps/server/src/project/knowledge/recallRelevance.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/server/src/project/knowledge/recallRelevance.ts b/apps/server/src/project/knowledge/recallRelevance.ts index f13cada31edb7..d567ea53922d1 100644 --- a/apps/server/src/project/knowledge/recallRelevance.ts +++ b/apps/server/src/project/knowledge/recallRelevance.ts @@ -7,6 +7,7 @@ const RECALL_MIN_MATCHED_TERMS = 3; const RECALL_MIN_HIT = 10; const RECALL_TUNED_CORPUS_SIZE = 718; const RECALL_MIN_COVERAGE = 0.3; +const RECALL_MIN_MESSAGE_COVERAGE = 0.03; // 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; @@ -101,8 +102,10 @@ const recallHitFloor = (corpusSize: number) => const phraseIn = (entity: string, message: string) => { const phrase = fold(entity.trim()); if (phrase.length < 4) return false; + const foldedMessage = fold(message); + if (!foldedMessage.includes(phrase)) return false; const escaped = phrase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`(? recallTerms([fact.content, ...fact.entities].join(" ")); @@ -133,11 +136,12 @@ export const rankRecallCandidates = ( const factCoverage = factMass === 0 ? 0 : hit / factMass; const relevance = Math.max(queryCoverage, factCoverage); const rare = matched.some((term) => stats.docs(term) <= rareCeiling); - const entity = fact.entities.some((value) => phraseIn(value, text)); + const entity = !rare && fact.entities.some((value) => phraseIn(value, text)); // A fact contained in the message stays eligible when every saved fact uses the same words and idf collapses. const passes = matched.length >= RECALL_MIN_MATCHED_TERMS && relevance >= RECALL_MIN_COVERAGE && + queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE && (rare || entity) && (hit >= floor || factCoverage >= RECALL_MIN_COVERAGE); return [{ fact, relevance, passes }]; From fd2c20d19809a6e9a38bd5ac08dd9251619c8b42 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 13:11:40 -0800 Subject: [PATCH 04/10] test(server): require stronger evidence for watch notice recall Co-Authored-By: Claude Fable 5.2 --- .../project/knowledge/recallRelevance.test.ts | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/apps/server/src/project/knowledge/recallRelevance.test.ts b/apps/server/src/project/knowledge/recallRelevance.test.ts index 14a5c7afaaaaa..d863c0133ea46 100644 --- a/apps/server/src/project/knowledge/recallRelevance.test.ts +++ b/apps/server/src/project/knowledge/recallRelevance.test.ts @@ -54,7 +54,14 @@ const remaining: RecallFactText = { entities: ["checkout"], }; -const facts = [ledger, remaining]; +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); @@ -122,12 +129,20 @@ it("recalls a fact the message actually names, and stays quiet otherwise", () => ids: [], }, { - name: "pull request watch names the fact", + name: "pull request watch has only seven matching terms", message: { - text: "Checks failed for the ledger labs toggle.", + text: "Checks failed: archive receipts preserve invoice timestamps during exports.", notification: { source: { kind: "monitor" } }, }, - ids: ["ledger-labs"], + 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", From 045481a43a57c0b2b881cf7e1452f9b4cdf8da0c Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 13:18:23 -0800 Subject: [PATCH 05/10] fix(server): require eight matched terms for watch notice recall Co-Authored-By: Claude Fable 5.2 --- .../src/project/knowledge/ProjectKnowledge.ts | 2 +- .../src/project/knowledge/recallRelevance.ts | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.ts b/apps/server/src/project/knowledge/ProjectKnowledge.ts index f180d631a3bb5..ddfd51634c048 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.ts @@ -1294,7 +1294,7 @@ const make = Effect.gen(function* () { corpusSize: messageStats.corpusSize, docs: (term) => docs.get(term) ?? 0, }; - const ranked = rankRecallCandidates(text, active, stats); + const ranked = rankRecallCandidates(text, active, stats, input.notification); const top = ranked.slice(0, 5).map((match) => ({ factId: match.fact.id })); const selections = ranked .flatMap((match) => diff --git a/apps/server/src/project/knowledge/recallRelevance.ts b/apps/server/src/project/knowledge/recallRelevance.ts index d567ea53922d1..a5f1380a202ac 100644 --- a/apps/server/src/project/knowledge/recallRelevance.ts +++ b/apps/server/src/project/knowledge/recallRelevance.ts @@ -4,6 +4,7 @@ import type { OrchestrationV2NotificationSource } from "@t3tools/contracts"; 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_HIT = 10; const RECALL_TUNED_CORPUS_SIZE = 718; const RECALL_MIN_COVERAGE = 0.3; @@ -114,7 +115,12 @@ 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 queryTerms = recallTerms(text); const queryMass = [...queryTerms].reduce( @@ -139,7 +145,7 @@ export const rankRecallCandidates = ( const entity = !rare && fact.entities.some((value) => phraseIn(value, text)); // A fact contained in the message stays eligible when every saved fact uses the same words and idf collapses. const passes = - matched.length >= RECALL_MIN_MATCHED_TERMS && + matched.length >= minimumMatchedTerms && relevance >= RECALL_MIN_COVERAGE && queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE && (rare || entity) && @@ -152,11 +158,11 @@ export const rankRecallCandidates = ( }; const selectRecallMatches = ( - message: string, + message: RecallMessage, facts: ReadonlyArray, stats: TermStats, ): ReadonlyArray> => - rankRecallCandidates(message, facts, stats) + rankRecallCandidates(message.text, facts, stats, message.notification) .filter((match) => match.passes) .slice(0, RECALL_MAX_FACTS); @@ -167,5 +173,5 @@ export const recallForMessage = ( stats: TermStats, ): ReadonlyArray => { if (!recallTrigger(message).recall) return []; - return selectRecallMatches(message.text, facts, stats).map((match) => match.fact); + return selectRecallMatches(message, facts, stats).map((match) => match.fact); }; From a936619a372c67a1112f624c4bc2ab8c00aab7fc Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 13:57:09 -0800 Subject: [PATCH 06/10] test(server): reproduce recall eligibility and tokenizer regressions Co-Authored-By: Claude Fable 5.2 --- .../ProviderTurnStartService.test.ts | 38 ++++ .../server/src/persistence/Migrations.test.ts | 19 ++ .../reconcileV2PreviewMigration.test.ts | 4 + .../knowledge/ProjectKnowledge.test.ts | 213 +++++++++++++++++- .../project/knowledge/recallRelevance.test.ts | 35 +++ 5 files changed, 303 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index f1cd03a4ce75f..578c6463f918e 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -4656,3 +4656,41 @@ effectIt.effect("declares no replayed runs to the summary lookup on a provider s expect(lookups).toEqual([undefined]); }), ); +effectIt.effect("manual resume recalls with the original unsent message metadata", () => + 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, + ), + }); + 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(original!.notification); + expect(input.turn?.messageId).toEqual(original!.id); + }), +); diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index d00a052408658..cd10c7a5e0b89 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -1364,3 +1364,22 @@ it.effect("registers every migration file", () => ); }).pipe(Effect.provide(NodeServices.layer)), ); + +it.effect.each(["RepairSubagentGroups", "ProjectKnowledgeFtsVocab"])( + "installs recall indexes after either migration 113 preview (%s)", + (name) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 112 }); + if (name === "ProjectKnowledgeFtsVocab") + yield* sql`CREATE VIRTUAL TABLE project_knowledge_fts_vocab USING fts5vocab(project_knowledge_fts, 'row')`; + yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES (113, ${name})`; + yield* runMigrations(); + assert.deepEqual( + yield* sql`SELECT token FROM project_knowledge_tokenizer WHERE input = 'πύλη 캐시 ガバナンス'`, + [{ token: "πύλη" }, { token: "캐시" }, { token: "ガバナンス" }], + ); + assert.deepEqual(yield* sql`SELECT term FROM project_knowledge_fts_instances LIMIT 1`, []); + assert.deepEqual(yield* runMigrations(), []); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 6fa1b398dbe25..7017dff03064d 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -92,6 +92,8 @@ describe("V2 preview upgrade", () => { [110, "ProviderTurnAttemptIndex"], [111, "TurnItemMessageOrdinalIndex"], [112, "TurnItemInlineWorkOutput"], + [113, "RepairSubagentGroups"], + [114, "ProjectKnowledgeRecallIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -227,6 +229,8 @@ describe("V2 preview upgrade", () => { [110, "ProviderTurnAttemptIndex"], [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 9e7c32c024955..7799eff08ff00 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -1828,13 +1828,13 @@ it.effect("browsing searches can opt out of reinforcing retrieval counts", () => yield* knowledge.mutate( { ...createFact(projectId, "unicode"), - content: "缓存键 必须包 含租户标", + content: "缓存键必须包含租户标识", entities: [], tags: [], }, { kind: "user" }, ); - assert.deepEqual(yield* recalled("suggest-unicode", "缓存键 必须包 含租户标"), [ + assert.deepEqual(yield* recalled("suggest-unicode", "缓存键必须包含租户标识"), [ ProjectFactId.make("unicode"), ]); assert.deepEqual(yield* recalled("suggest-filler", "please can you help"), []); @@ -2357,6 +2357,7 @@ it.effect( ...createFact(projectId, factId), commandId: CommandId.make(`create:${factId}`), content: longer, + entities: [], }, { kind: "user" }, ); @@ -2368,11 +2369,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")), @@ -2392,10 +2396,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" }, @@ -2413,10 +2418,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, @@ -3613,3 +3619,198 @@ 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); + }).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)), +); diff --git a/apps/server/src/project/knowledge/recallRelevance.test.ts b/apps/server/src/project/knowledge/recallRelevance.test.ts index d863c0133ea46..ca4b52397fa2f 100644 --- a/apps/server/src/project/knowledge/recallRelevance.test.ts +++ b/apps/server/src/project/knowledge/recallRelevance.test.ts @@ -1,3 +1,4 @@ +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"; @@ -212,3 +213,37 @@ it.effect("splits terms the way the FTS vocabulary does", () => 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(); + } +}); From d465b59965c2ee24df692345b0055a8968ea5a96 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 15:45:28 -0800 Subject: [PATCH 07/10] fix(server): add project recall indexes at migration 113 Co-Authored-By: Claude Fable 5.2 --- .../server/src/persistence/Migrations.test.ts | 55 ++++++++++++++--- apps/server/src/persistence/Migrations.ts | 4 +- .../113_ProjectKnowledgeFtsVocab.ts | 9 --- .../113_ProjectKnowledgeRecallIndex.ts | 61 +++++++++++++++++++ .../reconcileV2PreviewMigration.test.ts | 6 +- 5 files changed, 111 insertions(+), 24 deletions(-) delete mode 100644 apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts create mode 100644 apps/server/src/persistence/Migrations/113_ProjectKnowledgeRecallIndex.ts diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index cd10c7a5e0b89..9be81f3c23472 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -1365,21 +1365,58 @@ it.effect("registers every migration file", () => }).pipe(Effect.provide(NodeServices.layer)), ); -it.effect.each(["RepairSubagentGroups", "ProjectKnowledgeFtsVocab"])( - "installs recall indexes after either migration 113 preview (%s)", - (name) => +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 }); - if (name === "ProjectKnowledgeFtsVocab") - yield* sql`CREATE VIRTUAL TABLE project_knowledge_fts_vocab USING fts5vocab(project_knowledge_fts, 'row')`; - yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES (113, ${name})`; + 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 token FROM project_knowledge_tokenizer WHERE input = 'πύλη 캐시 ガバナンス'`, - [{ token: "πύλη" }, { token: "캐시" }, { token: "ガバナンス" }], + 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* sql`SELECT term FROM project_knowledge_fts_instances LIMIT 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 5f72e2968a3dc..6cd1074b4557a 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -123,7 +123,7 @@ import Migration0109 from "./Migrations/109_QueuedTurnInputIndexJsonValid.ts"; 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_ProjectKnowledgeFtsVocab.ts"; +import Migration0113 from "./Migrations/113_ProjectKnowledgeRecallIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -239,7 +239,7 @@ const migrationEntries = [ [110, "ProviderTurnAttemptIndex", Migration0110], [111, "TurnItemMessageOrdinalIndex", Migration0111], [112, "TurnItemInlineWorkOutput", Migration0112], - [113, "ProjectKnowledgeFtsVocab", Migration0113], + [113, "ProjectKnowledgeRecallIndex", Migration0113], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts b/apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts deleted file mode 100644 index d16e716d45814..0000000000000 --- a/apps/server/src/persistence/Migrations/113_ProjectKnowledgeFtsVocab.ts +++ /dev/null @@ -1,9 +0,0 @@ -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') - `; -}); diff --git a/apps/server/src/persistence/Migrations/113_ProjectKnowledgeRecallIndex.ts b/apps/server/src/persistence/Migrations/113_ProjectKnowledgeRecallIndex.ts new file mode 100644 index 0000000000000..a4849964a61eb --- /dev/null +++ b/apps/server/src/persistence/Migrations/113_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 7017dff03064d..e72efa7893e63 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -92,8 +92,7 @@ describe("V2 preview upgrade", () => { [110, "ProviderTurnAttemptIndex"], [111, "TurnItemMessageOrdinalIndex"], [112, "TurnItemInlineWorkOutput"], - [113, "RepairSubagentGroups"], - [114, "ProjectKnowledgeRecallIndex"], + [113, "ProjectKnowledgeRecallIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -229,8 +228,7 @@ describe("V2 preview upgrade", () => { [110, "ProviderTurnAttemptIndex"], [111, "TurnItemMessageOrdinalIndex"], [112, "TurnItemInlineWorkOutput"], - [113, "RepairSubagentGroups"], - [114, "ProjectKnowledgeRecallIndex"], + [113, "ProjectKnowledgeRecallIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 651fc745b19176f2149a9d5cd39a59bd60c1c591 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 15:46:16 -0800 Subject: [PATCH 08/10] fix(server): isolate and recalibrate project memory recall Co-Authored-By: Claude Fable 5.2 --- .../knowledge/ProjectKnowledge.test.ts | 80 ++++++++- .../src/project/knowledge/ProjectKnowledge.ts | 55 +++--- .../src/project/knowledge/persistence.ts | 49 ++++-- .../project/knowledge/recallRelevance.test.ts | 166 +++++++++++++++++- .../src/project/knowledge/recallRelevance.ts | 80 ++++----- 5 files changed, 341 insertions(+), 89 deletions(-) diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts index 7799eff08ff00..7e5faa8ed2162 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -2278,7 +2278,7 @@ it.effect("recall does not score with the holographic kernel", () => ), ); -it.effect("recall returns the current fact when stale near-duplicates fill a page of 40", () => +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; @@ -2327,7 +2327,10 @@ it.effect("recall returns the current fact when stale near-duplicates fill a pag composer: { text: query, records: [] }, knowledgeAllowance: 48000, }); - assert.deepEqual(attachedFactIds(outcome), [ProjectFactId.make("current")]); + assert.deepEqual(attachedFactIds(outcome), [ + ProjectFactId.make("dup-00"), + ProjectFactId.make("dup-01"), + ]); }).pipe(Effect.provide(layerTest)), ); @@ -3690,6 +3693,22 @@ it.effect("recall in one project depends on facts saved in other projects", () = 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)), ); @@ -3814,3 +3833,60 @@ it.effect("lost-source fact outranks a valid one", () => 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 ddfd51634c048..3979386f5164e 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.ts @@ -1258,18 +1258,17 @@ const make = Effect.gen(function* () { return yield* note({ _tag: "Skipped", reason: "no_budget" }); const lookup = Effect.gen(function* () { const text = input.query.slice(0, RECALL_MESSAGE_CHARS); - const terms = [...recallTerms(text)]; + 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 messageStats = yield* store - .termStats(terms) - .pipe(Effect.mapError(storageError(input.projectId))); - const present = terms.filter((term) => (messageStats.docs.get(term) ?? 0) > 0); const candidates = yield* store .recallCandidates( input.projectId, - present, + terms, 0.5, input.threadId, [...seen], @@ -1279,30 +1278,36 @@ const make = Effect.gen(function* () { const active = candidates.facts.flatMap((fact) => fact.status === "forgotten" || fact.content === null ? [] : [fact], ); - const missing = new Set(); + 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(" "))) - if (!messageStats.docs.has(term)) missing.add(term); - const extra = - missing.size === 0 - ? messageStats - : yield* store - .termStats([...missing]) - .pipe(Effect.mapError(storageError(input.projectId))); - const docs = new Map([...messageStats.docs, ...extra.docs]); + 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: messageStats.corpusSize, - docs: (term) => docs.get(term) ?? 0, + 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 = ranked - .flatMap((match) => - match.passes - ? [{ kind: "fact" as const, factId: match.fact.id, revision: match.fact.revision }] - : [], - ) - .slice(0, RECALL_MAX_FACTS); + 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--) { diff --git a/apps/server/src/project/knowledge/persistence.ts b/apps/server/src/project/knowledge/persistence.ts index b6d73d1d58b4a..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)); @@ -312,20 +320,34 @@ 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_fts`; - const corpusSize = Number(count?.n ?? 0); - if (terms.length === 0) return { corpusSize, docs: new Map() }; - const rows = yield* sql<{ readonly term: string; readonly doc: number }>` - SELECT term, doc FROM project_knowledge_fts_vocab WHERE ${sql.in("term", terms)} - `; + }>`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, - docs: new Map(rows.map((row) => [row.term, Number(row.doc)])), + corpusSize: Number(count?.n ?? 0), + docs: new Map(rows.map((r) => [r.term, Number(r.doc)])), }; }); const recallCandidates = Effect.fn("ProjectKnowledgeStore.recallCandidates")(function* ( @@ -337,14 +359,13 @@ export const makeStore = Effect.gen(function* () { limit: number, ) { const ftsQuery = ftsMatch(terms, true); - if (ftsQuery === "") - return { facts: [], ranks: new Map(), partial: false }; + 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 @@ -358,7 +379,7 @@ 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 ${limit}`; + ORDER BY f.trust DESC, f.updated_at DESC, f.id ASC LIMIT ${limit}`; const loaded = yield* findMany( projectId, rows.map((row) => row.id), @@ -369,7 +390,6 @@ export const makeStore = Effect.gen(function* () { const fact = byId.get(row.id); return fact === undefined ? [] : [fact]; }), - ranks: new Map(rows.map((row) => [row.id, row.rank])), partial: false, }; }); @@ -837,6 +857,7 @@ export const makeStore = Effect.gen(function* () { record, recordSearch, candidates, + tokenize, termStats, recallCandidates, similar, diff --git a/apps/server/src/project/knowledge/recallRelevance.test.ts b/apps/server/src/project/knowledge/recallRelevance.test.ts index ca4b52397fa2f..4baf90d2f1fa0 100644 --- a/apps/server/src/project/knowledge/recallRelevance.test.ts +++ b/apps/server/src/project/knowledge/recallRelevance.test.ts @@ -11,6 +11,7 @@ import { recallForMessage, recallTokens, recallTrigger, + rankRecallCandidates, type RecallFactText, type RecallMessage, type TermStats, @@ -94,7 +95,7 @@ it("recalls a fact the message actually names, and stays quiet otherwise", () => { name: "delegate brief names the fact after the boilerplate", message: { text: delegateBrief }, - ids: ["ledger-labs"], + ids: ["ledger-labs", "remaining-work"], }, { name: "a narrow fact covers too little of a broad message", @@ -104,9 +105,9 @@ it("recalls a fact the message actually names, and stays quiet otherwise", () => ids: [], }, { - name: "continue with remaining work", + name: "a short request fully covers a common fact", message: { text: "continue with remaining work" }, - ids: [], + ids: ["remaining-work"], }, { name: "can you also do the work here", @@ -166,6 +167,13 @@ it("recalls a fact the message actually names, and stays quiet otherwise", () => 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]), @@ -209,7 +217,7 @@ it.effect("splits terms the way the FTS vocabulary does", () => 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).filter((term) => term.length >= 3)); + 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:" }))), ); @@ -247,3 +255,153 @@ it("uses unicode61 tokens across scripts and identifier punctuation", () => { 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 index a5f1380a202ac..eaa546c06dbf2 100644 --- a/apps/server/src/project/knowledge/recallRelevance.ts +++ b/apps/server/src/project/knowledge/recallRelevance.ts @@ -1,3 +1,4 @@ +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. */ @@ -5,10 +6,8 @@ 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_HIT = 10; -const RECALL_TUNED_CORPUS_SIZE = 718; const RECALL_MIN_COVERAGE = 0.3; -const RECALL_MIN_MESSAGE_COVERAGE = 0.03; +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; @@ -40,8 +39,9 @@ export interface RecallFactText { readonly entities: ReadonlyArray; } -/** Document frequencies from the FTS vocabulary. `docs` is 0 for a term no fact contains. */ +/** Project-local document frequencies of current saved facts. */ export interface TermStats { + readonly tokenize?: (text: string) => Iterable; readonly corpusSize: number; readonly docs: (term: string) => number; } @@ -52,18 +52,28 @@ export interface RecallMatch { readonly passes: boolean; } -const TOKEN = /[\p{L}\p{N}]+/gu; - -const fold = (text: string) => text.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase(); - -/** Same splits as the FTS5 unicode61 tokenizer, keeping tokens of at least 3 characters. */ -export const recallTokens = (text: string): ReadonlySet => { - const tokens = fold(text).match(TOKEN) ?? []; - return new Set(tokens.filter((token) => token.length >= 3)); +/** 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 recallTerms = (text: string): ReadonlySet => - new Set([...recallTokens(text)].filter((token) => !RECALL_STOPWORDS.has(token))); +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 => { @@ -94,23 +104,6 @@ export const recallTrigger = (message: RecallMessage): RecallTrigger => { const idf = (docs: number, corpusSize: number) => Math.log(1 + corpusSize / (1 + docs)); -// `hit >= 10` was tuned at 718 facts. Below that it scales with ln(1+N), because three rare terms cannot sum to 10. -const recallHitFloor = (corpusSize: number) => - corpusSize >= RECALL_TUNED_CORPUS_SIZE - ? RECALL_MIN_HIT - : (RECALL_MIN_HIT * Math.log(1 + corpusSize)) / Math.log(1 + RECALL_TUNED_CORPUS_SIZE); - -const phraseIn = (entity: string, message: string) => { - const phrase = fold(entity.trim()); - if (phrase.length < 4) return false; - const foldedMessage = fold(message); - if (!foldedMessage.includes(phrase)) return false; - const escaped = phrase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`(? recallTerms([fact.content, ...fact.entities].join(" ")); - export const rankRecallCandidates = ( message: string, facts: ReadonlyArray, @@ -122,16 +115,14 @@ export const rankRecallCandidates = ( ? RECALL_MONITOR_MIN_MATCHED_TERMS : RECALL_MIN_MATCHED_TERMS; const text = message.slice(0, RECALL_MESSAGE_CHARS); - const queryTerms = recallTerms(text); + 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 rareCeiling = Math.max(2, Math.floor(stats.corpusSize * 0.03)); - const floor = recallHitFloor(stats.corpusSize); const ranked = facts.flatMap((fact) => { - const terms = factTerms(fact); - if (terms.size === 0) return []; + 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( @@ -141,18 +132,19 @@ export const rankRecallCandidates = ( const queryCoverage = queryMass === 0 ? 0 : hit / queryMass; const factCoverage = factMass === 0 ? 0 : hit / factMass; const relevance = Math.max(queryCoverage, factCoverage); - const rare = matched.some((term) => stats.docs(term) <= rareCeiling); - const entity = !rare && fact.entities.some((value) => phraseIn(value, text)); - // A fact contained in the message stays eligible when every saved fact uses the same words and idf collapses. const passes = - matched.length >= minimumMatchedTerms && + (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 && - (rare || entity) && - (hit >= floor || factCoverage >= RECALL_MIN_COVERAGE); + queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE; return [{ fact, relevance, passes }]; }); - // Stable, so equal coverage keeps the candidate order: bm25, then trust, then recency. + // Equal coverage preserves project-local trust and recency order. ranked.sort((left, right) => right.relevance - left.relevance); return ranked; }; From 0fa0c1b0302259a386d07bb4a5fd43dca17077c6 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 15:47:21 -0800 Subject: [PATCH 09/10] fix(server): recall resumed turns with their provider notification Co-Authored-By: Claude Fable 5.2 --- .../ProviderTurnStartService.test.ts | 89 +++++++++++-------- .../ProviderTurnStartService.ts | 6 +- 2 files changed, 57 insertions(+), 38 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 578c6463f918e..6fb5f41658263 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -4656,41 +4656,58 @@ effectIt.effect("declares no replayed runs to the summary lookup on a provider s expect(lookups).toEqual([undefined]); }), ); -effectIt.effect("manual resume recalls with the original unsent message metadata", () => - 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", +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", + }, + } + : {}), }, - } - : m, - ), - }); - 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(original!.notification); - expect(input.turn?.messageId).toEqual(original!.id); - }), + ), + }); + 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); + }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index c55e3666c2bc6..cbec438463f66 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1952,11 +1952,13 @@ export const layer: Layer.Layer< threadId: projection.thread.id, requestId: CommandId.make(`memory-recall:${attempt.id}`), query: providerMessage.text, - ...(message.notification === undefined ? {} : { notification: message.notification }), + ...(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, From 4e3325d7ad2a0f74e4b74265292c79ecb64173fd Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 18:24:40 -0800 Subject: [PATCH 10/10] test(server): the peer-link leak scan reads stored tables, not virtual ones Migration 114 adds an fts3tokenize table that the recall triggers read with `input =`. SQLite refuses to scan it without that constraint, so the PeerLinkRequests helper that ran `SELECT *` over every sqlite_master table failed with "SQL logic error". The helper now lists tables and FTS shadow tables from pragma_table_list: every stored row is still read, and virtual tables, whose rows are computed or live in those shadow and content tables, are skipped. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/peer/PeerLinkRequests.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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}"`),