fix(loki): shedding records was silent, so the count was confidently wrong (#286)

Asked "how many projects am I tracking, and what are their names?",
prod Loki answered "You are tracking 5 projects" and named them, with
citations. The account holds 22. The five were simply the tail of the
list that survived trimFactsToBudget — sbb-lost-found, solon,
surf-your-life, truthseeker, vitareba, the last five alphabetically.

Nothing in the prompt told the model a longer list existed. It received
a short list and answered the question in front of it, correctly. A
wrong count that arrives with source citations is worse than "not in
your data": it reads as a checked answer, and the most basic question
you can ask a fleet dashboard is how many projects it is watching.

facts.ts already solved this exact problem one level down — a field
with no value renders as `<not recorded>` rather than being omitted,
because a stated negative is far harder to overwrite than silence.
Budget-dropped records had no such statement. So give them one: when
the fit sheds records, the prompt now says how many were withheld, that
the list is therefore incomplete, and that a total must not be stated
from it.

The notice is measured INSIDE fitFactsToBudget rather than appended
after it — otherwise the very text that reports the shedding is what
busts the budget and causes more of it.

Not fixed here: the counts themselves still come from records rather
than SQL. Directives (core/contract.ts) are the right home for an exact
count and are currently built only for the daily brief. This change
stops the confident wrong answer; it does not yet produce the confident
right one.

Guard: four cases in test:fact-budget, including that the notice is
charged against the budget. Verified they bite by reverting the notice
to a no-op and watching the suite fail.

Co-authored-by: t <t@t.t>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-08-15 10:25:51 +00:00
1 parent 15faf227b8
commit 6b6cff070c
3 files changed
+91 -8

No files matched your search

+41
View File
@@ -13,6 +13,7 @@ import {
mergeFactsWithCap,
fitFactsToBudget,
estimateTokens,
omissionNotice,
} from "@/lib/agent/fact-budget";
import type { Fact } from "@/lib/agent/core/facts";
@@ -119,6 +120,46 @@ function runTests(): void {
assert(out.length === 0, `expected 0 facts, got ${out.length}`);
});
// ── shedding must be announced ────────────────────────────────────────────
// Loki reported "You are tracking 5 projects" against an account holding 22:
// the five were the tail that survived the trim, and nothing told the model a
// longer list existed. A count drawn from a silently shortened list is worse
// than a refusal, because it arrives with citations.
check("nothing withheld ⇒ no notice (a notice that always fires is ignored)", () => {
assert(omissionNotice(40, 40) === "", "notice emitted when the whole set was sent");
assert(omissionNotice(0, 0) === "", "notice emitted for an empty fact set");
});
check("withholding states BOTH the sent count and the true total", () => {
const notice = omissionNotice(22, 5);
// The true total is the number the wrong answer got wrong — it has to appear.
assert(notice.includes("22"), "notice omits the true total");
assert(notice.includes("5"), "notice omits how many were sent");
assert(notice.includes("17"), "notice omits how many were withheld");
});
check("the notice forbids the specific move that caused the bug", () => {
const notice = omissionNotice(22, 5).toLowerCase();
assert(notice.includes("incomplete"), "notice does not say the list is incomplete");
assert(
notice.includes("do not state a total") && notice.includes("complete list"),
"notice does not forbid stating a total / presenting a complete list",
);
});
check("the notice is sized INSIDE the fit, so reporting shedding cannot cause it", () => {
// Render exactly as loop.ts does: context plus the notice for what was cut.
const all = range("f", 40);
const withNotice = (fs: Fact[]) => render(fs) + omissionNotice(all.length, fs.length);
const out = fitFactsToBudget(all, withNotice, 0, 300);
assert(out.length > 0, "fit shed everything once the notice was charged");
assert(
estimateTokens(withNotice(out)) <= 300,
"prompt busts the budget once the notice is included — the notice was not charged",
);
});
console.log(`\n${passed} passed`);
}
+32
View File
@@ -31,6 +31,38 @@ export function mergeFactsWithCap(existing: Fact[], fresh: Fact[], cap: number):
return [...existing.slice(0, room), ...kept];
}
/**
* Say out loud that records were withheld.
*
* Shedding facts to fit a call is silent to the model: it receives a shorter
* list and no indication that a longer one exists, so a question about "how
* many" is answered by counting what happens to be in front of it. Asked how
* many projects it was tracking, Loki answered "You are tracking 5 projects"
* and named them, with citations, while the operator's account held 22 — the
* five were simply the tail of the list that survived `trimFactsToBudget`.
* Nothing in the answer marked it as partial, which makes it worse than a
* refusal: a wrong count that cites sources reads as a checked one.
*
* This is the same principle as `<not recorded>` in facts.ts — absence has to
* be *stated* to be resistible — applied to the records dropped by the budget
* rather than the fields missing from a record.
*/
export function omissionNotice(total: number, sent: number): string {
const omitted = total - sent;
if (omitted <= 0) return "";
return [
"## Withheld records — the list below is INCOMPLETE",
"",
`${omitted} of ${total} retrieved records did not fit this request and were withheld.`,
`You can see ${sent}. You cannot see the other ${omitted}, and they are not described anywhere in this prompt.`,
"",
"Therefore: do not state a total, do not say how many there are, and do not",
"present the records below as a complete list. If the question asks for a",
`count or "all" of something, answer that you can see ${sent} of ${total} retrieved`,
"records and give those, rather than counting what is in front of you.",
].join("\n");
}
/**
* Rough token count. Deliberately crude — ~4 characters per token is close
* enough for English prose, and the alternative (shipping a tokenizer for the
+18 -8
View File
@@ -25,7 +25,12 @@
* "answer with what you have" rather than to an error.
*/
import { assignFactIds, renderFacts, type Fact } from "@/lib/agent/core/facts";
import { trimFactsToBudget, mergeFactsWithCap, fitFactsToBudget } from "@/lib/agent/fact-budget";
import {
trimFactsToBudget,
mergeFactsWithCap,
fitFactsToBudget,
omissionNotice,
} from "@/lib/agent/fact-budget";
import { buildGroundedContext, buildContract, directiveId, NO_BASIS, type Directive } from "@/lib/agent/core/contract";
import { verifyAnswer, buildRepairPrompt, type Violation } from "@/lib/agent/core/verify";
import { callModelWithTools, type ChatMessage, type ToolCall } from "@/lib/agent/llm";
@@ -280,12 +285,17 @@ export async function runLokiTurn(input: {
input.message.length +
(lastRound ? 0 : JSON.stringify(nativeTools).length) +
conversation.reduce((n, m) => n + m.content.length, 0);
const fitted = fitFactsToBudget(
facts,
(f) => buildGroundedContext({ facts: f, directives, renderedFacts: renderFacts(f) }),
overheadChars,
CALL_TOKEN_BUDGET,
);
// The notice is measured as part of the fit, not bolted on afterwards —
// otherwise the very prompt that reports the shedding is what busts the
// budget and triggers more of it.
const withNotice = (f: Fact[]) =>
[
buildGroundedContext({ facts: f, directives, renderedFacts: renderFacts(f) }),
omissionNotice(facts.length, f.length),
]
.filter(Boolean)
.join("\n\n---\n\n");
const fitted = fitFactsToBudget(facts, withNotice, overheadChars, CALL_TOKEN_BUDGET);
if (fitted.length < facts.length) {
console.warn(`[loki] round ${rounds}: ${facts.length} facts exceed the call budget — sending ${fitted.length}`);
}
@@ -297,7 +307,7 @@ export async function runLokiTurn(input: {
const ctx =
budget >= fitted.length && fitted.length === facts.length
? grounded
: buildGroundedContext({ facts: trimmed, directives, renderedFacts: renderFacts(trimmed) });
: withNotice(trimmed);
try {
return await callModel({
messages: [