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
4 changes: 4 additions & 0 deletions apps/server/src/project/knowledge/ProjectKnowledge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1842,6 +1842,10 @@ it.effect("browsing searches can opt out of reinforcing retrieval counts", () =>
["limit", longQuery.slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH)],
["over-limit", longQuery.slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH + 1)],
["long-with-whitespace", ` \n\t${longQuery}\n\t `],
[
"truncated-copy",
`${"Cache keys include tenant IDs.".padEnd(8_192)}Should we change that requirement?`,
],
] as const) {
const requestId = CommandId.make(`suggest-relevant-${name}`);
assert.deepEqual(yield* recalled(requestId, query), [ProjectFactId.make("fact-one")]);
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/project/knowledge/ProjectKnowledge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1304,7 +1304,7 @@ const make = Effect.gen(function* () {
docs: (term) => counted.docs.get(term) ?? 0,
tokenize,
};
const ranked = rankRecallCandidates(text, active, stats, input.notification);
const ranked = rankRecallCandidates(input.query, active, stats, input.notification);
const top = ranked.slice(0, 5).map((match) => ({ factId: match.fact.id }));
const selections = [];
for (const match of ranked) {
Expand Down
65 changes: 63 additions & 2 deletions apps/server/src/project/knowledge/recallRelevance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ it("enforces coverage, overlap and relevance order", () => {
ids: ["strong", "middle"],
},
{
name: "a fact the brief already states gives its slot to the next match",
name: "overlap in a longer brief still admits the complete fact",
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."),
Expand All @@ -371,7 +371,68 @@ it("enforces coverage, overlap and relevance order", () => {
fact("next", "The reconciliation job owns the invoice exporter schedule."),
],
docs: 1,
ids: ["shared-words", "next"],
ids: ["stated", "shared-words"],
},
{
name: "a question needs the saved requirement",
text: "Should cache keys include tenant IDs?",
facts: [fact("requirement", "Cache keys must include tenant IDs.")],
docs: 1,
ids: ["requirement"],
},
{
name: "a contradictory request needs the saved prohibition",
text: "Disable tenant authorization checks.",
facts: [fact("prohibition", "Never disable tenant authorization checks.")],
docs: 1,
ids: ["prohibition"],
},
{
name: "shared wording does not carry the fact's qualification",
text: "Rotate production cache keys.",
facts: [
fact(
"condition",
"Rotate production cache keys only after replicas have acknowledged the new encryption material.",
),
],
docs: 1,
ids: ["condition"],
},
{
name: "matching entities do not restate the saved content",
text: "tenant authorization policy checks",
facts: [
fact("entity-only", "Release migrations require a verified backup.", [
"tenant authorization policy checks",
]),
],
docs: 1,
ids: ["entity-only"],
},
{
name: "a complete copied statement gives up its slot",
text: "Cache keys must include tenant IDs.",
facts: [
fact("copied", "Cache keys must include tenant IDs."),
fact("additional", "Tenant IDs in cache keys prevent cross-tenant data leaks."),
],
docs: 1,
ids: ["additional"],
},
{
name: "surrounding whitespace still carries the complete statement",
text: " \nNever disable tenant authorization checks.\n ",
facts: [fact("copied", "Never disable tenant authorization checks.")],
docs: 1,
ids: [],
},
{
name: "internal whitespace can change a quoted cache prefix",
text: 'Cache keys use the prefix "tenant id".',
facts: [fact("prefix", 'Cache keys use the prefix "tenant id".')],
docs: 1,
ids: ["prefix"],
},
];
for (const row of cases) {
Expand Down
25 changes: 7 additions & 18 deletions apps/server/src/project/knowledge/recallRelevance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ 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;
const RECALL_RESTATED_MIN_TERMS = 4;
// 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 @@ -83,13 +81,6 @@ export const recallTerms = (
tokenize: (text: string) => Iterable<string> = tokenizeRecallText,
): 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 => {
switch (kind) {
Expand Down Expand Up @@ -117,12 +108,6 @@ 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 @@ -139,7 +124,11 @@ export const rankRecallCandidates = <Fact extends RecallFactText>(
const tokenize = stats.tokenize ?? tokenizeRecallText;
const querySequence = recallTermSequence(text, tokenize);
const queryTerms = new Set(querySequence);
const queryRuns = termRuns(querySequence);
// Partial overlap loses questions, negation and qualifications that can change the claim.
const copiedStatement =
message.length <= RECALL_MESSAGE_CHARS && querySequence.length >= RECALL_RESTATED_MIN_TERMS
? text.trim()
: undefined;
const queryMass = [...queryTerms].reduce(
(sum, term) => sum + idf(stats.docs(term), stats.corpusSize),
0,
Expand All @@ -166,7 +155,7 @@ export const rankRecallCandidates = <Fact extends RecallFactText>(
))) &&
relevance >= RECALL_MIN_COVERAGE &&
queryCoverage >= RECALL_MIN_MESSAGE_COVERAGE &&
!restates(queryRuns, termRuns(sequence));
copiedStatement !== fact.content.trim();
return [{ fact, relevance, passes }];
});
// Equal coverage preserves project-local trust and recency order.
Expand Down
Loading