Files
loki/scripts/test/loki-judgment-contract.ts
CatoandClaude Opus 5 e5f8e8ea49 fix(loki): let it think, and fetch the thing you asked about (#668)
Asked "what do you think about heidi", Loki answered:

    ...`.

    Everything is clean and strictly compliant.
    </think>An opinion or assessment is: Not in your data.

…and then listed every record containing "Heidi", including two unrelated
people who happen to be named Heidi. Four defects, stacked.

## 1. A model's private reasoning was persisted as the answer

There is a literal `</think>` in the database. This repo already knew the
trick — TWICE, in `frontier/propose.ts` and `orchestration/dod-gate.ts` — and
both copies exist to make JSON parse. The one path a HUMAN reads had none.

`stripReasoning` now lives once, at the model seam next to
`stripToolCallLines`, and is applied at all four seams (tool loop, groq
buffered, groq streamed, gateway). The two old copies call it.

`lastIndexOf` rather than a regex is load-bearing: the leak had a CLOSING tag
and no opening one, because the head of the reasoning was lost upstream. A
`<think>[\s\S]*?</think>` pattern matches nothing there.

While streaming, nothing can know text is reasoning until the tag arrives — so
the gate now RETRACTS what it showed the moment the tag proves what it was.

## 2. It was forbidden to have a view

`buildContract` says every claim must cite a record (1) and anything without
one gets exactly "Not in your data." (3). An opinion is not a record, so the
model looked one up, failed, and refused. It was obeying the contract exactly.

ai-kit's OTHER builder, `buildAssistantRules`, already carries the equivalent
carve-out as its rule 5 ("general knowledge … is not covered by rules 1–2").
The typed-record builder never grew one — so the WEAKER contract is the usable
one and the stronger contract forbids reasoning.

Rules 7–10 are added as a NARROWING, inserted INSIDE the contract section:
the contract opens with "this overrides every formatting instruction below",
so a narrowing placed after the records would be outranked by the rule it
narrows. Both grounded paths share one assembly point, because the production
refusal came through the gateway while the loop carried the same defect.

The durable fix belongs upstream in `buildContract`; noted in the module.

## 3. Retrieval fetched the wrong subject

This was the one that made the answer useless, and it survived the prompt fix.

`peopleFacts(userId, message)` searches by the message. `documentFacts(userId,
message, limit)` searches by the message. `projectFacts(userId)` ignored it:
projects came back in table order and were then head-sliced. With ~30
registered projects that is a lottery, and the `Heidi` PROJECT lost it — while
the people search matched two contacts by name. Retrieval chose the subject of
the answer, and chose wrong. No prompt rule can recover a record that was
never fetched.

Projects the message NAMES are now ranked ahead of the slice. Pure, in its own
module because `sources.ts` imports `@/db`, which throws at load without a
connection string — and this repo's unit suite is env-independent.

## 4. A citation the verifier could not see

Found only by running it: nemotron cited `【F16】` in fullwidth brackets. Both
readers are ASCII-only, so the verifier's unknown-citation check silently had
nothing to check, and the renderer printed the handle verbatim as plumbing.
Normalised at the seam, before verification.

## Verified

Against REAL production records through the read-only tunnel, same question:

    Heidi is an active project — status active [F16]. Its recorded description
    is "Learn to understand and text in Zurich Swiss German.
    heidi.orangecat.ch" [F16]. The latest development log notes the creation of
    a /check page … and a PR #4 that has not yet been merged [F16].

No reasoning tags, no refusal, ASCII citations, 0 grounding violations.

Three new pure suites, each proven by MUTATION: removing the judgment clause
fails 7/10 checks; a no-op `stripReasoning` fails 3. The prose-gate test
replays the exact production bytes.


Claude-Session: https://claude.ai/code/session_018SCNNZ3cqMFzQtuGe6e1V9

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 02:28:36 -07:00

108 lines
3.5 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The clause that lets Loki hold an opinion.
*
* Production, asked "what do you think about heidi":
*
* An opinion or assessment is: Not in your data.
*
* The model was obeying `buildContract` exactly — rule 1 says every claim must
* cite a record, rule 3 says anything with no supporting record gets exactly
* "Not in your data." An opinion is not a record, so it looked one up, failed,
* and refused.
*
* These checks are structural, not stylistic. They assert the narrowing is
* PRESENT, that it sits INSIDE the contract section (a rule placed after the
* line "this overrides every formatting instruction below" is outranked by the
* thing it is narrowing), and that both grounded paths get it. A prompt whose
* wording drifts is fine; a prompt that silently loses this clause is the
* original bug returning.
*
* Pure: no model, no database.
*/
import { buildLokiContext, JUDGMENT_RULES } from "@/lib/agent/grounded-context";
import type { Fact } from "@bitbaum/ai-kit/grounding";
let failures = 0;
function check(name: string, ok: boolean, detail = "") {
if (ok) {
console.log(` ✓ ${name}`);
} else {
console.error(` ✗ ${name}${detail ? `\n ${detail}` : ""}`);
failures++;
}
}
const facts: Fact[] = [
{
id: "F1",
subject: "heidi",
kind: "project",
fields: { name: "heidi", summary: "Learn Zurich Swiss German" },
} as unknown as Fact,
];
const ctx = buildLokiContext({
facts,
directives: [],
renderedFacts: "- [F1] heidi — Learn Zurich Swiss German",
});
console.log("loki judgment contract");
check("the narrowing is present", ctx.includes(JUDGMENT_RULES));
// The contract announces that it overrides everything BELOW it. A narrowing
// that lands after the records is therefore outranked by the rule it narrows.
const contractSection = ctx.split("\n\n---\n\n")[0] ?? "";
check(
"it sits inside the contract section, not after the records",
contractSection.includes(JUDGMENT_RULES),
"the clause must precede the first '---' separator or the contract outranks it",
);
check(
"the original contract survives — this narrows, never replaces",
ctx.includes("Every claim about the operator MUST cite a record id") &&
ctx.includes("Grounding contract"),
);
check("the records still reach the model", ctx.includes("Learn Zurich Swiss German"));
// The four failures of the production answer, each named.
check(
"it forbids answering a judgment request with the no-basis phrase",
/never the answer to a request for JUDGMENT/i.test(ctx),
);
check(
"it requires an assessment to show what it rests on",
/Ground the judgment and show its footing/i.test(ctx),
);
check(
"thin evidence is a hedge, not a refusal",
/Thin evidence earns a hedge/i.test(ctx) && /never a refusal/i.test(ctx),
);
check(
"a name-collision row must not be padded in as relevant",
/matched only because a NAME contains/i.test(ctx),
);
check(
"factual claims inside an assessment are still bound by rules 1-6",
/Rules 1–6 still bind every FACTUAL claim/i.test(ctx),
);
// An empty turn must still be allowed to say it has nothing — the narrowing is
// about judgment, not a licence to answer with no records at all.
const emptyCtx = buildLokiContext({ facts: [], directives: [], renderedFacts: "" });
check(
"with no records at all, the refusal instruction still stands",
emptyCtx.includes("NO records were retrieved for this turn"),
);
if (failures > 0) {
console.error(`\n${failures} check(s) failed`);
process.exit(1);
}
console.log("✓ loki judgment contract: all checks passed");