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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions apps/server/scripts/replay-project-memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
}),
},
Expand Down Expand Up @@ -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" },
Expand Down Expand Up @@ -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");
Expand Down
25 changes: 13 additions & 12 deletions apps/server/src/project/knowledge/ProjectKnowledge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Parameters<typeof knowledge.recall>[0]> = {},
requestId = "recall",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"),
Expand All @@ -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"),
Expand Down Expand Up @@ -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"),
Expand All @@ -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({
Expand Down Expand Up @@ -3444,7 +3444,7 @@ it.effect(
const blocked = yield* Deferred.make<void>();
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,
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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");
Expand Down
22 changes: 18 additions & 4 deletions apps/server/src/project/knowledge/recallRelevance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,15 +133,15 @@ 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: [],
},
{
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"],
Expand Down Expand Up @@ -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, {
Expand Down
35 changes: 30 additions & 5 deletions apps/server/src/project/knowledge/recallRelevance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -69,11 +72,23 @@ const tokenizeRecallText = (text: string): ReadonlyArray<string> => {
export const recallTokens = (text: string): ReadonlySet<string> =>
new Set(tokenizeRecallText(text));

const recallTermSequence = (
text: string,
tokenize: (text: string) => Iterable<string>,
): ReadonlyArray<string> =>
[...tokenize(text)].filter((token) => token.length >= 3 && !RECALL_STOPWORDS.has(token));

export const recallTerms = (
text: string,
tokenize: (text: string) => Iterable<string> = tokenizeRecallText,
): ReadonlySet<string> =>
new Set([...tokenize(text)].filter((token) => token.length >= 3 && !RECALL_STOPWORDS.has(token)));
): ReadonlySet<string> => new Set(recallTermSequence(text, tokenize));

const termRuns = (terms: ReadonlyArray<string>): ReadonlySet<string> =>
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 => {
Expand Down Expand Up @@ -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<string>, factRuns: ReadonlySet<string>): 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 = <Fact extends RecallFactText>(
Expand All @@ -116,13 +137,16 @@ export const rankRecallCandidates = <Fact extends RecallFactText>(
: 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(
Expand All @@ -141,7 +165,8 @@ export const rankRecallCandidates = <Fact extends RecallFactText>(
term.length >= 6,
))) &&
relevance >= RECALL_MIN_COVERAGE &&
queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE;
queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE &&
!restates(queryRuns, termRuns(sequence));

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Preserve recall when the message questions or contradicts the saved fact

recallTermSequence removes negation and modality (never, not, must, should), and the tokenizer removes punctuation. Sharing a four-term run therefore does not establish that the message already states the saved claim.

I reproduced both cases through recallForMessage, using one fact with entities: [] and stats = { corpusSize: 1, docs: () => 1 }:

  • Saved: Cache keys must include tenant IDs. Message: Should cache keys include tenant IDs?
  • Saved: Never disable tenant authorization checks. Message: Disable tenant authorization checks.

Main returns the saved fact in both cases; this head returns []. These are situations where the stored rule is useful, but the new predicate hides it. An exact declarative restatement is suppressed too, so the current representation cannot distinguish the intended case from these regressions.

Please add these as regression cases and make suppression preserve the claim's polarity and whether it is being asserted or questioned. Re-evaluate useful-fact removals and the replacement deliveries before merging; a threshold adjustment alone cannot recover meaning already discarded by tokenization.

return [{ fact, relevance, passes }];
});
// Equal coverage preserves project-local trust and recency order.
Expand Down
Loading