Files
loki/scripts/sync-agent-core.ts
T
5317762404 feat(loki): ground every answer in typed records instead of prose (#212)
* feat(loki): ground every answer in typed records instead of prose

Loki answered a five-part "plan my day" prompt with three fabricated
answers, then produced an unverified correction when challenged. Traced:

  - "rotate the expired GROQ_API_KEY, it blocks truthseeker" — the key
    returns HTTP 200. Both cited .env paths were invented.
  - "Ilya Druzhnikov (UZH)" — the record has no org field and "UZH"
    exists nowhere in the operator's data. It is the substring inside
    dr-UZH-nikov: a keyword-match artifact narrated as an affiliation.
  - "Elena Weber, Accelerator & Bridge Program Manager, University of
    Liechtenstein alumna" — the record is a display name and a phone
    number. No web search was performed.

Root cause is architectural, not prompt quality. buildLokiFleetContext
injected projects + RAG only; people, goals, habits, commitments and
events were never in context, though FleetCrown could already answer
every one of those questions exactly (getStuckGoals, getGoalsDueSoon,
listUpcomingCommitments, getEventsDueSoon have existed for months).
So a prompt demanding five items met a context supporting one, and the
model filled the rest — the ordinary failure mode of a small model
under format pressure, which is precisely who will be running this.

The fix makes unsupported claims hard to EXPRESS, not just discouraged:

  agent/core/facts.ts     records with a declared field set; unstored
                          fields render as an explicit `<not recorded>`,
                          turning absence into a stated negative
  agent/core/contract.ts  rules generated from THIS turn's facts —
                          enumerated citation ids, named concrete gaps,
                          a verbatim refusal phrase; plus Directive for
                          answers computed in SQL that the model may
                          only phrase, never re-derive
  agent/core/verify.ts    deterministic post-generation check. No extra
                          model call, so it runs on free-tier turns too.
                          Flags unresolvable citations and proper nouns
                          / numbers / paths absent from the records.

  agent/brief.ts          wires the existing SQL into the assistant at
                          last; an empty result is reported as empty
  agent/sources.ts        people (new), projects, pgvector docs, and
                          OrangeCat demand → Facts
  agent/context.ts        assembly; contract first, records last

loki-core now verifies each answer and gives the model one repair pass
to DELETE unsupported claims. Surviving violations ride back as
`grounding` metadata rather than being swallowed: the original failure
was not that Loki was wrong, it was that wrong looked exactly like right.

scripts/test/agent-grounding.ts asserts all four fabrications above are
caught and that a clean grounded answer still passes. core/ is mirrored
to OrangeCat with a SHA-256 drift gate, pending @fleet/agent-core.

Removes loki-fleet-context/-index — superseded, and a second definition
of the fleet index would be the SSOT violation this replaces.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(agent): scope the name check by assistant, not one rule for both

The verifier's original closed-world rule — every proper noun must be
attested in the records — is right for Loki and wrong for Cat, and
shipping it unchanged to both would have made Cat unusable.

Loki reports one operator's records. Any unattested name there is a
fabrication. Cat also answers general questions ("how do I get paid in
Switzerland"), where naming Twint, Lightning or PayPal is correct and
required. Flagging those would have produced constant false positives on
a live multi-tenant product, and a check that cries wolf gets switched
off within a week — at which point it protects nothing.

So `mode`:

  closed-world        every unattested proper noun is a violation (Loki)
  entity-attribution  only sentences naming one of the USER'S OWN records
                      are checked (Cat)

The narrower mode is genuinely weaker and that is a real trade, not a
loophole: Cat can still be wrong about the wider world. It can no longer
invent an employer for someone in your contacts — the failure that
actually destroys trust in a personal assistant.

Also adds buildAssistantRules() — the fact-id-free half of the contract,
for an assistant whose context is still prose. Weaker by construction
(nothing to cite), but it keeps the rules that stopped the worst failure:
never state an attribute a record does not carry, never imply research
you did not perform. A stepping stone to typed records, not a
destination.

Two new adversarial checks assert BOTH halves — general economic advice
passes in entity-attribution mode, an invented employer for a known
contact does not, and closed-world remains strictly stronger.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: test <test@test>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-13 10:34:36 +00:00

42 lines
1.7 KiB
TypeScript

/**
* Push the canonical agent/core into OrangeCat's mirror.
* Run: npx tsx scripts/sync-agent-core.ts (npm run sync:agent-core)
*
* FleetCrown owns the canonical copy; OrangeCat mirrors it byte-for-byte. See
* src/lib/agent/core/README.md for why the harness is duplicated rather than
* packaged, and scripts/test/agent-core-drift.ts for the check that makes the
* duplication safe.
*
* Deliberately a no-op when the sibling repo is absent — CI clones one repo at
* a time, and a sync script that fails there would block every unrelated build.
*/
import { readdirSync, readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const HERE = dirname(fileURLToPath(import.meta.url));
const SRC = join(HERE, "..", "src", "lib", "agent", "core");
const DEST = process.env.ORANGECAT_DIR
? join(process.env.ORANGECAT_DIR, "src", "services", "agent-core")
: join(HERE, "..", "..", "orangecat", "src", "services", "agent-core");
if (!existsSync(dirname(dirname(DEST)))) {
console.log(`↷ OrangeCat not found at ${DEST} — skipping mirror (set ORANGECAT_DIR to override)`);
process.exit(0);
}
mkdirSync(DEST, { recursive: true });
let changed = 0;
for (const file of readdirSync(SRC).sort()) {
const body = readFileSync(join(SRC, file), "utf8");
const target = join(DEST, file);
const current = existsSync(target) ? readFileSync(target, "utf8") : null;
if (current === body) continue;
writeFileSync(target, body);
console.log(` → ${file}`);
changed++;
}
console.log(changed === 0 ? "✓ agent-core mirror already in sync" : `✓ mirrored ${changed} file(s) to ${DEST}`);