Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): the fact extractor reads its system prompt from the prompt cache (#6917)
time-attackf256800cd161
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex ba6a597c12..51bc4ef358 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -10,7 +10,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). It also owns the granular collector aliases (`ALLOWED_TYPE_ALIASES`, `pageTypesForAllowed`) and the one eligibility rule (#5330): `isConversationFactsEligiblePage` and its SQL twin `conversationFactsEligibleSql` admit an allowed concrete type unless frontmatter says `conversation_parseable: false`; with `cycle.conversation_facts_backfill.require_parseable_flag` on, only `type: conversation` or `conversation_parseable: true`. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`. `isFrontmatterFlagOff` (the same off spellings) is shared with `facts/eligibility.ts`. Since #6267 it also owns the `ConversationMessage`, `ConversationSegment` and `SplitSegmentsOpts` types the windowing module and the command share.- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix (conversation-pipeline types, `CONVERSATION_PIPELINE_TYPES`, skip as `conversation_pipeline`, #6557: the opt-in conversation facts backfill owns them; doctor `facts_extraction_health` names the opt-in and its caps when such pages exist and the backfill is off). Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`. #6259: a quarantined page (the gate's `quarantine` marker) is ineligible with reason `quarantined`, which the page-write receipt reports as `facts_backstop.skipped` (registered in `facts_backstop_skipped`).-- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. The typed-claim examples keep a bare `$` as USD (series compare by `(metric, unit, period)`, so nulling it would split them) and, since wave 15 (PR #6274 by @jordanschwartz-js), show two explicit non-USD examples (EUR, CAD) with the rule to preserve a stated currency as the unit and never convert; pinned by `test/facts-extract-currency-examples-6274.test.ts`. Pinned by `test/facts-extract-structured-output.test.ts`.+- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). The first call and the truncation retry send `cacheSystem: true` (the system prompt is identical across calls; per-call data rides in the user message), so bulk extraction reads it from the provider's prompt cache; the malformed-output retry, whose system prompt differs, does not. Model: `resolveFactsExtractionModel(engine)` returns the model and the setting that chose it (`facts.extraction_model`, then the `resolveModelDetailed` chain on the `reasoning` tier); when nothing chose one and the tier's key-aware default resolved through Anthropic, `FACTS_EXTRACTION_MEASURED_DEFAULTS` substitutes `anthropic:claude-haiku-5-5` (source `measured_default`; the facts-absorb quality gate, gbrain-evals `docs/benchmarks/2026-10-08-facts-extraction-model.md`), and `gbrain models` reports that row through the same resolver. `getFactsExtractionModel` is its string wrapper. Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. The typed-claim examples keep a bare `$` as USD (series compare by `(metric, unit, period)`, so nulling it would split them) and, since wave 15 (PR #6274 by @jordanschwartz-js), show two explicit non-USD examples (EUR, CAD) with the rule to preserve a stated currency as the unit and never convert; pinned by `test/facts-extract-currency-examples-6274.test.ts`. Pinned by `test/facts-extract-structured-output.test.ts`.- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. `strikeFenceRow` and `supersededFact` are exported for the S9 checked supersede (`facts/proposal-supersede.ts`). `strikeFenceRow` returns null for a fence that parses with warnings (#6385 R12), so forget falls back to the DB-only expire and the file keeps the rows the parser could not read. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`. A segmented page's row is struck in the segment holding its fence (`rewriteLiveSegmentedFences`), on the DB-only and the file-mirror paths, with `strikeFenceRow`'s whole-string semantics: only the first facts fence is a candidate (of the compiled truth for the DB body, of truth then timeline for the mirror), and a first fence without the row strikes nothing.diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.tsindex b643929b43..bafdc33993 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -667,6 +667,10 @@ export async function extractFactsFromTurnWithOutcome(maxTokens,abortSignal: input.abortSignal,responseSchema,+ // The system prompt is identical across consecutive calls (everything+ // per-call rides in userContent), so bulk extraction reads it from the+ // provider's prompt cache instead of paying full input for it each time.+ cacheSystem: true,});// #2113: never checked pre-fix — a truncated response (stopReason// 'length', e.g. reasoning tokens eating the cap on mandatory-reasoning@@ -685,6 +689,7 @@ export async function extractFactsFromTurnWithOutcome(maxTokens: effectiveMaxTokens,abortSignal: input.abortSignal,responseSchema,+ cacheSystem: true,});if (result.stopReason === 'length') {process.stderr.write(@@ -718,6 +723,8 @@ export async function extractFactsFromTurnWithOutcome('retrying once with an explicit JSON-only reminder\n',);try {+ // No cacheSystem: the appended note makes this system block differ from+ // every other call's, so a cache write here would never be read.result = await chat({model,system: `${extractorSystem}\nThe previous attempt returned invalid JSON or an invalid facts schema. ` +diff --git a/test/facts-extract-prompt-cache.test.ts b/test/facts-extract-prompt-cache.test.tsnew file mode 100644index 0000000000..3e1cac5d22--- /dev/null+++ b/test/facts-extract-prompt-cache.test.ts@@ -0,0 +1,126 @@+/**+ * Facts extraction reads its system prompt from the Anthropic prompt cache.+ *+ * Every extractor call sends the same system prompt (about 2,200 tokens with+ * the default date-grounding and attribution blocks); the turn, observation+ * date and entity hints ride in the user message. The first call and the+ * #2113 truncation retry opt in with `cacheSystem: true`, so chat() puts an+ * explicit breakpoint on the system block and the next call reads it. The+ * malformed-output retry appends a note to the system prompt, so it does not+ * opt in: a write there would never be read.+ *+ * Pinned through the generateText transport seam, so the assertions see the+ * `system` param the Anthropic provider receives: a SystemModelMessage carrying+ * `providerOptions.anthropic.cacheControl` when caching, a bare string when not.+ */+import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test';+import {+ configureGateway,+ resetGateway,+ __setGenerateTextTransportForTests,+} from '../src/core/ai/gateway.ts';+import { buildExtractorSystem, extractFactsFromTurnWithOutcome } from '../src/core/facts/extract.ts';++const MODEL = 'anthropic:claude-sonnet-5-5';+const GOOD_JSON = '{"facts":[{"fact":"user gave up alcohol","kind":"commitment",' ++ '"entity":null,"confidence":1.0,"notability":"high",' ++ '"metric":null,"value":null,"unit":null,"period":null}]}';+const VARIANT = { dateGrounding: true, attribution: true };++function sdkResult(text: string, finishReason: 'stop' | 'length' = 'stop'): any {+ return { content: [{ type: 'text', text }], finishReason, usage: { inputTokens: 5, outputTokens: 5 } };+}++function extract(turnText: string, date: string, entityHints?: string[]) {+ return extractFactsFromTurnWithOutcome({+ turnText,+ source: 'test:prompt-cache',+ model: MODEL,+ variant: VARIANT,+ observationDate: { date, source: 'caller' },+ entityHints,+ });+}++/** The system param chat() handed the SDK, with its cache marker if any. */+function systemOf(call: any): { text: string; cacheControl: unknown } {+ if (typeof call.system === 'string') return { text: call.system, cacheControl: undefined };+ return { text: call.system.content, cacheControl: call.system.providerOptions?.anthropic?.cacheControl };+}++beforeEach(() => {+ resetGateway();+ __setGenerateTextTransportForTests(null);+ configureGateway({ chat_model: MODEL, env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+});++afterEach(() => {+ __setGenerateTextTransportForTests(null);+ resetGateway();+});++// Shard hygiene (same rationale as facts-extract-truncation.test.ts): restore+// the legacy 1536-d embedding pin so later fresh-schema files in this shard+// don't inherit a dimensionless gateway.+afterAll(() => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { ...process.env },+ });+});++describe('facts extraction — system prompt prompt-cache breakpoint', () => {+ test('consecutive calls send one identical, cache-marked system block; per-call data stays in the user message', async () => {+ const calls: any[] = [];+ __setGenerateTextTransportForTests(async (args: any) => { calls.push(args); return sdkResult(GOOD_JSON); });++ const a = await extract('alice-example (2026-09-01 09:00): I gave up alcohol in March.', '2026-09-01', ['people/alice-example']);+ const b = await extract('charlie-example (2026-09-02 10:30): We closed the seed round at $2M.', '2026-09-02', ['companies/acme-example']);++ expect(a.ok && b.ok).toBe(true);+ expect(calls).toHaveLength(2);+ const [s1, s2] = calls.map(systemOf);+ expect(s1!.cacheControl).toEqual({ type: 'ephemeral' });+ expect(s2!.cacheControl).toEqual({ type: 'ephemeral' });+ expect(s1!.text).toBe(buildExtractorSystem(true, VARIANT));+ expect(s2!.text).toBe(s1!.text);+ // The varying parts land after the breakpoint, in the user message.+ const user = (call: any) => JSON.stringify(call.messages);+ expect(s1!.text).not.toContain('2026-09-01');+ expect(user(calls[0])).toContain('2026-09-01');+ expect(user(calls[0])).toContain('people/alice-example');+ expect(user(calls[1])).toContain('companies/acme-example');+ });++ test('the #2113 truncation retry keeps the breakpoint', async () => {+ const calls: any[] = [];+ __setGenerateTextTransportForTests(async (args: any) => {+ calls.push(args);+ return calls.length === 1 ? sdkResult('{"facts":[{"fact":"user gave up alco', 'length') : sdkResult(GOOD_JSON);+ });++ const outcome = await extract('alice-example (2026-09-01 09:00): I gave up alcohol in March.', '2026-09-01');++ expect(outcome.ok).toBe(true);+ expect(calls).toHaveLength(2);+ expect(systemOf(calls[1]).cacheControl).toEqual({ type: 'ephemeral' });+ expect(systemOf(calls[1]).text).toBe(systemOf(calls[0]).text);+ });++ test('the malformed-output retry, whose system prompt differs, sends no breakpoint', async () => {+ const calls: any[] = [];+ __setGenerateTextTransportForTests(async (args: any) => {+ calls.push(args);+ return sdkResult(calls.length === 1 ? 'not json' : GOOD_JSON);+ });++ const outcome = await extract('alice-example (2026-09-01 09:00): I gave up alcohol in March.', '2026-09-01');++ expect(outcome.ok).toBe(true);+ expect(calls).toHaveLength(2);+ expect(systemOf(calls[0]).cacheControl).toEqual({ type: 'ephemeral' });+ expect(typeof calls[1].system).toBe('string');+ expect(calls[1].system).toContain('The previous attempt returned invalid JSON');+ });+});