From b436794229c5844a287c93eac67973806c0d84a2 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 19:24:53 -0800 Subject: [PATCH] fix(server): recall skips a saved fact the message already states A brief that already carries a saved fact no longer spends one of recall's two slots on it; the next match takes the slot. A fact counts as stated when at least a tenth of its four-term runs appear in the message in order. Shared names and scattered vocabulary still attach. Co-Authored-By: Claude Opus 5.5 --- .../scripts/replay-project-memory.test.ts | 6 ++-- .../knowledge/ProjectKnowledge.test.ts | 25 ++++++------- .../project/knowledge/recallRelevance.test.ts | 22 +++++++++--- .../src/project/knowledge/recallRelevance.ts | 35 ++++++++++++++++--- 4 files changed, 64 insertions(+), 24 deletions(-) diff --git a/apps/server/scripts/replay-project-memory.test.ts b/apps/server/scripts/replay-project-memory.test.ts index 71ebd9aa1bb52..4771663da810b 100644 --- a/apps/server/scripts/replay-project-memory.test.ts +++ b/apps/server/scripts/replay-project-memory.test.ts @@ -32,7 +32,7 @@ const messages = [ project_id: "replay-project", thread_id: "asking-thread", payload_json: JSON.stringify({ - text: "Change cache keys to include tenant IDs.", + text: "Do the cache keys carry tenant IDs?", createdBy: "user", }), }, @@ -62,7 +62,7 @@ const messages = [ project_id: "replay-project", thread_id: "asking-thread", payload_json: JSON.stringify({ - text: "Change cache keys to include tenant IDs.", + text: "Do the cache keys carry tenant IDs?", createdBy: "agent", notification: { source: { kind: "background_command" }, @@ -93,7 +93,7 @@ it.effect("replays invented facts through recall and names the gate", () => assert.equal(match?.gate, "delivered"); assert.deepEqual(match?.deliveredFactIds, ["fact-one"]); assert.equal(match?.createdBy, "user"); - assert.equal(match?.characters, "Change cache keys to include tenant IDs.".length); + assert.equal(match?.characters, "Do the cache keys carry tenant IDs?".length); assert.isAbove(match?.candidatesMs ?? -1, -1); assert.equal(typeof match?.candidatesMs, "number"); assert.equal(byId.get("greeting")?.gate, "no_match"); diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts index b17b833330e73..0c8d80f2be32f 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -1890,7 +1890,7 @@ it.effect( yield* createProject(projectId); yield* knowledge.mutate(createFact(projectId), { kind: "user" }); const threadId = ThreadId.make("recall-thread"); - const query = "Change cache keys to include tenant IDs."; + const query = "Do the cache keys carry tenant IDs?"; const recall = ( overrides: Partial[0]> = {}, requestId = "recall", @@ -2031,7 +2031,7 @@ it.effect("does not recall a fact the thread's agent has already been shown", () const projections = yield* ProjectionStore.ProjectionStoreV2; const projectId = ProjectId.make("recall-seen"); yield* createProject(projectId); - const query = "Change cache keys to include tenant IDs."; + const query = "Do the cache keys carry tenant IDs?"; // The facts differ enough that reading one does not quote another as a look-alike. const contents = { one: "Cache keys include tenant IDs, rule one.", @@ -2241,7 +2241,7 @@ it.effect("recalls unseen facts beyond a full page of facts the thread has read" read.facts.map((fact) => fact.id), ids.slice(0, 9), ); - const query = "Change cache keys to include tenant IDs."; + const query = "Do the cache keys carry tenant IDs?"; const recalled = attachedComposer( yield* knowledge.recall({ projectId, @@ -2273,7 +2273,7 @@ it.effect("recall keeps the most trusted fact when more than the bound match equ for (const factId of ids) yield* knowledge.mutate(createFact(projectId, factId), { kind: "user" }); yield* sql`UPDATE project_knowledge_facts SET trust = 1 WHERE id = ${ids[40]!}`; - const query = "Change cache keys to include tenant IDs."; + const query = "Do the cache keys carry tenant IDs?"; const outcome = yield* knowledge.recall({ projectId, threadId: ThreadId.make("recall-trust-tie"), @@ -2292,7 +2292,7 @@ it.effect("recall does not score with the holographic kernel", () => 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 query = "Do the cache keys carry tenant IDs?"; const outcome = yield* knowledge.recall({ projectId, threadId: ThreadId.make("recall-no-kernel"), @@ -2353,7 +2353,7 @@ it.effect("recall preserves trust order for equally covered eligible near-duplic ); 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 query = "Toggle ledger labs, then ship billing."; const outcome = yield* knowledge.recall({ projectId, threadId: ThreadId.make("recall-near-duplicates"), @@ -2375,7 +2375,7 @@ it.effect( Effect.gen(function* () { const knowledge = yield* ProjectKnowledge.ProjectKnowledge; const projections = yield* ProjectionStore.ProjectionStoreV2; - const query = "Change cache keys to include tenant IDs."; + const query = "Do the cache keys carry tenant IDs?"; const longer = "Cache keys include tenant IDs. " + "background note ".repeat(40); const recallTarget = (projectId: ProjectId, threadId: ThreadId, requestId: string) => knowledge.recall({ @@ -3444,7 +3444,7 @@ it.effect( const blocked = yield* Deferred.make(); const stall: Statement.Transformer = (statement) => Deferred.await(blocked).pipe(Effect.as(statement)); - const query = "Change cache keys to include tenant IDs."; + const query = "Do the cache keys carry tenant IDs?"; const pending = yield* knowledge .recall({ projectId, @@ -3499,7 +3499,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."; + const query = "Do the cache keys carry tenant IDs?"; const outcome = yield* knowledge.recall({ projectId, threadId: ThreadId.make("recall-bounded"), @@ -3558,7 +3558,7 @@ it.effect("reads the recall lookup on the reader connection", () => const projectId = ProjectId.make("recall-reader"); yield* createProject(projectId); yield* knowledge.mutate(createFact(projectId), { kind: "user" }); - const query = "Change cache keys to include tenant IDs."; + const query = "Do the cache keys carry tenant IDs?"; yield* knowledge .recall({ projectId, @@ -3842,13 +3842,14 @@ it.effect("lost-source fact outranks a valid one", () => ); 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 query = "Which invoices and billing changes gate on the toggle in ledger labs?"; const run = (id: string) => knowledge.recall({ projectId, threadId: ThreadId.make("t-" + id), requestId: CommandId.make("r-" + id), - query: content, - composer: { text: content, records: [] }, + query, + composer: { text: query, records: [] }, knowledgeAllowance: 48000, }); const before = yield* run("before"); diff --git a/apps/server/src/project/knowledge/recallRelevance.test.ts b/apps/server/src/project/knowledge/recallRelevance.test.ts index 4baf90d2f1fa0..b24f6f7071876 100644 --- a/apps/server/src/project/knowledge/recallRelevance.test.ts +++ b/apps/server/src/project/knowledge/recallRelevance.test.ts @@ -133,7 +133,7 @@ it("recalls a fact the message actually names, and stays quiet otherwise", () => { name: "pull request watch has only seven matching terms", message: { - text: "Checks failed: archive receipts preserve invoice timestamps during exports.", + text: "Checks failed: during exports, invoice timestamps in archive receipts were lost; preserve them.", notification: { source: { kind: "monitor" } }, }, ids: [], @@ -141,7 +141,7 @@ it("recalls a fact the message actually names, and stays quiet otherwise", () => { name: "pull request watch has eight matching terms", message: { - text: "Checks failed: archive receipts preserve invoice timestamps during nightly exports.", + text: "Checks failed: during nightly exports, invoice timestamps in archive receipts were lost; preserve them.", notification: { source: { kind: "monitor" } }, }, ids: ["receipt-archive"], @@ -353,12 +353,26 @@ it("enforces coverage, overlap and relevance order", () => { 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`), + fact("middle", `${shared} harbor orchard violet copper quartz blossom crimson`), + fact("strong", `${shared} meadow badger willow harbor orchard violet copper`), ], docs: 1, ids: ["strong", "middle"], }, + { + name: "a fact the brief already states gives its slot to the next match", + text: "Update the invoice exporter. Archive receipts must preserve invoice timestamps during nightly exports, and the reconciliation job reads them afterwards.", + facts: [ + fact("stated", "Archive receipts preserve invoice timestamps during nightly exports."), + fact( + "shared-words", + "Nightly reconciliation rejects exports whose invoice timestamps differ from archive receipts.", + ), + fact("next", "The reconciliation job owns the invoice exporter schedule."), + ], + docs: 1, + ids: ["shared-words", "next"], + }, ]; for (const row of cases) { const attached = recallForMessage({ text: row.text }, row.facts, { diff --git a/apps/server/src/project/knowledge/recallRelevance.ts b/apps/server/src/project/knowledge/recallRelevance.ts index eaa546c06dbf2..326ed05655ace 100644 --- a/apps/server/src/project/knowledge/recallRelevance.ts +++ b/apps/server/src/project/knowledge/recallRelevance.ts @@ -8,6 +8,9 @@ const RECALL_MIN_MATCHED_TERMS = 3; const RECALL_MONITOR_MIN_MATCHED_TERMS = 8; const RECALL_MIN_COVERAGE = 0.3; const RECALL_MIN_MESSAGE_COVERAGE = 0.028; +// Four terms in a row are a statement, not a shared name. No fact judged useful shared one with its message. +const RECALL_RESTATED_RUN = 4; +const RECALL_RESTATED_SHARE = 0.1; // 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; @@ -69,11 +72,23 @@ const tokenizeRecallText = (text: string): ReadonlyArray => { export const recallTokens = (text: string): ReadonlySet => new Set(tokenizeRecallText(text)); +const recallTermSequence = ( + text: string, + tokenize: (text: string) => Iterable, +): ReadonlyArray => + [...tokenize(text)].filter((token) => token.length >= 3 && !RECALL_STOPWORDS.has(token)); + export const recallTerms = ( text: string, tokenize: (text: string) => Iterable = tokenizeRecallText, -): ReadonlySet => - new Set([...tokenize(text)].filter((token) => token.length >= 3 && !RECALL_STOPWORDS.has(token))); +): ReadonlySet => new Set(recallTermSequence(text, tokenize)); + +const termRuns = (terms: ReadonlyArray): ReadonlySet => + new Set( + terms + .slice(RECALL_RESTATED_RUN - 1) + .map((_, index) => terms.slice(index, index + RECALL_RESTATED_RUN).join(" ")), + ); /** Work already under way. A pull-request watch stays eligible and the gate decides. */ const isProgressNotice = (kind: OrchestrationV2NotificationSource["kind"]): boolean => { @@ -102,6 +117,12 @@ export const recallTrigger = (message: RecallMessage): RecallTrigger => { return { recall: true }; }; +/** The message already carries the fact, so attaching it only takes a slot another fact could use. */ +const restates = (messageRuns: ReadonlySet, factRuns: ReadonlySet): boolean => + factRuns.size > 0 && + [...factRuns].filter((run) => messageRuns.has(run)).length / factRuns.size >= + RECALL_RESTATED_SHARE; + const idf = (docs: number, corpusSize: number) => Math.log(1 + corpusSize / (1 + docs)); export const rankRecallCandidates = ( @@ -116,13 +137,16 @@ export const rankRecallCandidates = ( : RECALL_MIN_MATCHED_TERMS; const text = message.slice(0, RECALL_MESSAGE_CHARS); const tokenize = stats.tokenize ?? tokenizeRecallText; - const queryTerms = recallTerms(text, tokenize); + const querySequence = recallTermSequence(text, tokenize); + const queryTerms = new Set(querySequence); + const queryRuns = termRuns(querySequence); const queryMass = [...queryTerms].reduce( (sum, term) => sum + idf(stats.docs(term), stats.corpusSize), 0, ); const ranked = facts.flatMap((fact) => { - const terms = recallTerms([fact.content, ...fact.entities].join(" "), tokenize); + const sequence = recallTermSequence([fact.content, ...fact.entities].join(" "), tokenize); + const terms = new Set(sequence); 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,7 +165,8 @@ export const rankRecallCandidates = ( term.length >= 6, ))) && relevance >= RECALL_MIN_COVERAGE && - queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE; + queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE && + !restates(queryRuns, termRuns(sequence)); return [{ fact, relevance, passes }]; }); // Equal coverage preserves project-local trust and recency order.