Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(extraction): extraction.date_grounding defaults on for fact extraction (held-out verdict p2-e2-heldout-2026-10-04: PASS)
garrytan62dedd5c5bc5
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 75987c0c2f..e35238a0ae 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -8,6 +8,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/checks/chat-fallback.ts` — `chat_fallback_chain` (OPS, registered after `embedding_env_override` so `--only` connects the brain, and in `doctorReportRemote`): the effective chain, its plane, shadowed values, providers and refusal behavior from `src/core/ai/chat-fallback-planes.ts`. An active, healthy chain is `ok` with the optional per-plane removal fix (never `next: run`); an unreadable plane value or a malformed / unknown-provider / no-chat entry warns with the removal fix, a missing credential with a `credentials` fix, an unpriced model under a user cap with `noPricingFix`. Remote (`remote !== false`): only that a chain is configured and its problem count, `host_admin` fix. Pinned by `test/doctor-chat-fallback-chain.test.ts`.- `src/commands/doctor/checks/behavior-changes.ts` — `behavior_changes` (META, after `chat_fallback_chain`): the `behavior_changes` disclosure read again (`src/core/behavior-change-notice.ts`), always `ok`; reads the baseline and markers without recording either, and reports which channels were shown.- `src/commands/doctor/checks/ranking-extraction.ts` — two informational BRAIN checks registered after `timeline_history`: `hub_degree_shape` (inbound-link degree p50/p90/p99/max and, when `search.hub_dampening` is a half degree, how many pages keep less than half of their graph lift; never recommends a value) and `extraction_date_grounding` (whether `extraction.date_grounding` is on and which extraction prompts it changes). Pinned by `test/doctor-ranking-extraction.test.ts` and the doctor registry/JSON goldens.+- `src/commands/doctor/checks/ranking-extraction.ts` — two informational BRAIN checks registered after `timeline_history`: `hub_degree_shape` (inbound-link degree p50/p90/p99/max and, when `search.hub_dampening` is a half degree, how many pages keep less than half of their graph lift; never recommends a value) and `extraction_date_grounding` (fact extraction grounded by default, off when the setting is false, and whether the chronicle, synthesis, atoms and takes prompts are opted in). Pinned by `test/doctor-ranking-extraction.test.ts` and the doctor registry/JSON goldens.- `src/commands/doctor/checks/vector-plan.ts` — `vector_plan` (#5824, OPS, wave check with operator resolution). Postgres only: EXPLAINs (no ANALYZE) the statement `searchVector` emits for the active embedding column with a zero vector through `PostgresEngine.explainVectorSearch` (same builder, scoped read transaction and scan settings) and warns when an HNSW-indexed column's plan does not use its HNSW index, naming the observed scans, whether the index exists and is valid (`pg_index.indisvalid`, with the create/reindex command), the 8 s candidate-budget risk and the legacy guard as rollback. Skipped on PGLite, on columns wider than the HNSW cap, and below 10,000 embedded chunks (`pg_class.reltuples` x `pg_stats.null_frac`, a bounded count when never analyzed). A configured legacy guard warns "active after restarting the owning service". Details carry a sampled stale-text fraction and point to `gbrain embed --stale` above 5%. Tested in `test/e2e/vector-plan-real-column-postgres.test.ts` (empty, small, ok, unused valid index, INVALID index, guard via env and config).- `src/commands/doctor/checks/persistence-requests.ts` — two wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex e2914b68ea..217829d8ef 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.-- `src/core/ai/date-grounding.ts` — the time vocabulary every extraction prompt shares: observation time (when text was written or said), event/validity time (`facts.valid_from`), recording time (`created_at`). `resolveObservationDate` (filename / `date` / `published` / created keys via `computeEffectiveDate`; never `event_date`, row timestamps or now), `observationDateFrom` (turn/message timestamps), `observationDateRule` (static system-prompt rule: rewrite relative dates as absolute dates or bounds resolved against the observation date, never leaving the phrase beside its date; unknown → keep as written), `observationDateLine` (user-message date or `unknown`), `parseExtractedEventDate` (YYYY-MM-DD, 1900..now+1y), `resolveValidFrom` (extracted > caller > observation > now), `hasUnresolvedRelativeDate` (judge-free eval check). The fact extractor, chronicle judge, dream synthesis, extract_atoms and propose_takes add the rule when `extraction.date_grounding` is on (default off); page-body facts default to the page's observation date regardless. Pinned by `test/ai/date-grounding.test.ts`, `test/facts/extract-date-grounding.test.ts`, `test/facts/backstop-page-date.test.ts`.+- `src/core/ai/date-grounding.ts` — the time vocabulary every extraction prompt shares: observation time (when text was written or said), event/validity time (`facts.valid_from`), recording time (`created_at`). `resolveObservationDate` (filename / `date` / `published` / created keys via `computeEffectiveDate`; never `event_date`, row timestamps or now), `observationDateFrom` (turn/message timestamps), `observationDateRule` (static system-prompt rule: rewrite relative dates as absolute dates or bounds resolved against the observation date, never leaving the phrase beside its date; unknown → keep as written), `observationDateLine` (user-message date or `unknown`), `parseExtractedEventDate` (YYYY-MM-DD, 1900..now+1y), `resolveValidFrom` (extracted > caller > observation > now), `hasUnresolvedRelativeDate` (judge-free eval check). Fact extraction adds the rule by default (`extraction.date_grounding` unset or true; `false` opts out; held-out verdict in `docs/eval/decisions/p2-e2-heldout/`); the chronicle judge, dream synthesis, extract_atoms and propose_takes add it only when the setting is explicitly `true` (`isConsumerDateGroundingOn`), pending their own checks. Page-body facts default to the page's observation date regardless. Pinned by `test/ai/date-grounding.test.ts`, `test/facts/extract-date-grounding.test.ts`, `test/facts/backstop-page-date.test.ts`.- `src/core/ai/defaults.ts` — leaf module for canonical embedding and reranker defaults, without a gateway import. Voyage `voyage:voyage-4` at 1024 dimensions is the new-install embedding default; `voyage:rerank-2.5` is the runtime/mode-bundle reranker default. `renderCanonicalMigrationCommands` supplies an explicit-target cost preview and an OpenAI keep-width alternative where supported. These constants do not establish the identity of vectors in an existing database and must never authorize automatic provider conversion. Init preserves explicit choices, writes no reranker row when the Voyage key is available, disables reranking for keyed installs without that key, and preserves keyless setup.- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, retaining an incompatible 1536-dimensional setting from another provider). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.diff --git a/docs/eval/decisions/p2-e2-heldout/README.md b/docs/eval/decisions/p2-e2-heldout/README.mdnew file mode 100644index 0000000000..01f4c2311f--- /dev/null+++ b/docs/eval/decisions/p2-e2-heldout/README.md@@ -0,0 +1,40 @@+# Date-grounded extraction: held-out verdict (PASS)++Decision `p2-e2-heldout-2026-10-04` ran on the 7 sealed LoCoMo conversations (1,076 questions). The evaluation+custodian ran it under preregistration amendment 1 (gbrain-evals `docs/benchmarks/2026-10-04-p2-ranking-extraction-preregistration.md`).++The candidate was `extraction.date_grounding=true` on the frozen build. The baseline was the same build with the+setting absent. Both arms ran the decision kit's facts lane: gbrain's conversation-facts extractor on dated+conversation pages, two extractions per arm, and a fixed reader that answers from the saved facts with 10+replicates. The gate is correctness first. It decides on the share of saved facts that still hold a relative date+("yesterday", "3 days ago") with no absolute date. QA has to stay non-inferior.++| Gate | Baseline → candidate | 95% CI | Result |+|---|---|---|---|+| Primary: unresolved relative-date share in saved facts | 8.95% → 2.05% (−77% relative; bar ≥ 50%) | [−8.3, −5.5] pts | pass |+| Temporal QA from saved facts (lower bound ≥ −3 pts) | 67.5 → 68.3 | [−1.2, +2.7] | pass |+| Overall QA from saved facts (lower bound ≥ −3 pts) | 53.6 → 54.7 | [+0.6, +1.7] | pass |+| Page recall@5 (lower bound ≥ −1 pt) | unchanged | — | pass |+| Facts per conversation (within ±5%) | −0.3% | — | pass |++All 7 conversations improved individually on the primary metric.++## Default++`extraction.date_grounding` defaults on for fact extraction: the page hook, `extract_facts`, conversation facts and+the backstop. `false`, `off` or `0` opts out.++The verdict measured fact extraction only. The four other prompts that know the rule stay on their current prompts+unless the setting is set to `true` explicitly:+- life chronicle events;+- dream synthesis;+- extract_atoms;+- propose_takes.++The preregistration requires a per-consumer check before any of them changes. `gbrain doctor` (`extraction_date_grounding`)+reports which mode a brain is in.++Facts extracted before the default changed keep their original wording. Re-extracting a source is an explicit,+previewed action that needs the user's consent: `gbrain extract-conversation-facts --source-id <id> --dry-run`.++Development record: `../p2-date-grounding-dev/`.diff --git a/src/commands/doctor/checks/ranking-extraction.ts b/src/commands/doctor/checks/ranking-extraction.tsindex 1d91acfe0d..946685666d 100644--- a/src/commands/doctor/checks/ranking-extraction.ts+++ b/src/commands/doctor/checks/ranking-extraction.ts@@ -11,7 +11,7 @@ import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { checkError } from '../check-fix.ts';import { loadSearchModeConfig, resolveSearchMode } from '../../../core/search/mode.ts';-import { getExtractorVariant } from '../../../core/facts/extract.ts';+import { getExtractorVariant, isConsumerDateGroundingOn } from '../../../core/facts/extract.ts';async function runHubDegreeShape(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);@@ -53,19 +53,22 @@ export const hubDegreeShapeEntry: DoctorEntry = {run: runHubDegreeShape,};-/** Extraction prompts the `extraction.date_grounding` setting changes. */-const GROUNDED_CONSUMERS = ['fact extraction (page hook, extract_facts, conversation facts)', 'life chronicle events', 'dream synthesis', 'extract_atoms', 'propose_takes'];+/** Prompts that follow `extraction.date_grounding` only when it is set on explicitly. */+const OPT_IN_CONSUMERS = ['life chronicle events', 'dream synthesis', 'extract_atoms', 'propose_takes'];async function runExtractionDateGrounding(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);const checks: Check[] = [];- const variant = await getExtractorVariant(engine);+ const [variant, consumers] = await Promise.all([getExtractorVariant(engine), isConsumerDateGroundingOn(engine)]);+ const reextract = 'Facts extracted before this was on keep their original wording; re-extract a source only with the user\'s consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).';checks.push({name: 'extraction_date_grounding',status: 'ok',- message: variant.dateGrounding- ? `Relative dates resolve against each source's observation date in: ${GROUNDED_CONSUMERS.join(', ')}. Facts extracted before this was enabled keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).`- : 'extraction.date_grounding is off: extraction prompts keep relative dates ("last week") as written. Dated pages still store their facts at the page date.',+ message: !variant.dateGrounding+ ? 'extraction.date_grounding is off: extraction prompts keep relative dates ("last week") as written. Dated pages still store their facts at the page date.'+ : consumers+ ? `Relative dates resolve against each source's observation date in fact extraction and in: ${OPT_IN_CONSUMERS.join(', ')}. ${reextract}`+ : `Fact extraction resolves relative dates against each source's observation date (the default). ${OPT_IN_CONSUMERS.join(', ')} keep their current prompts unless extraction.date_grounding is set to true. ${reextract}`,});return checks;}diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex b22e6ca95e..3d934c5295 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -309,8 +309,8 @@ export function defaultJudge(engine: BrainEngine): ChronicleJudge {}// extraction.date_grounding: the page date is the observation date; a// relative "last Tuesday" resolves against it, never against today.- const { getExtractorVariant } = await import('../facts/extract.ts');- const grounded = (await getExtractorVariant(engine)).dateGrounding === true;+ const { isConsumerDateGroundingOn } = await import('../facts/extract.ts');+ const grounded = await isConsumerDateGroundingOn(engine);const { observationDateFrom, observationDateLine, observationDateRule } = await import('../ai/date-grounding.ts');const dateLine = grounded ? `${observationDateLine(observationDateFrom(input.effectiveDate))}\n` : '';let text: string;diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 6fd7851c55..b9898115ac 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -59,7 +59,7 @@// which made the NOT EXISTS guard ineffective on federated brains.import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';-import { getExtractorVariant } from '../facts/extract.ts';+import { isConsumerDateGroundingOn } from '../facts/extract.ts';import type { BrainEngine, LinkBatchInput } from '../engine.ts';import { stripReasoningBlocks } from '../llm-json.ts';import type { PhaseResult } from '../cycle.ts';@@ -904,7 +904,7 @@ export async function runPhaseExtractAtoms(// "Keep safe defaults" comment) still leaves extractModel on this default,// matching the pre-refactor fail-soft behavior exactly.let extractModel = resolveTierDefault('utility');- const dateGrounding = (await getExtractorVariant(engine)).dateGrounding === true;+ const dateGrounding = await isConsumerDateGroundingOn(engine);let budgetCap = DEFAULT_BUDGET_USD;let explicitBudget = false; // operator SET cycle.extract_atoms.budget_usd// #4529/#4540: the per-item input/output caps were hardcoded (slice(0, 50_000) +diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex 6862f9ab7e..93c8244203 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -38,7 +38,7 @@*/import { observationDateLine, observationDateRule, resolveObservationDate, type ObservationDate } from '../ai/date-grounding.ts';-import { getExtractorVariant } from '../facts/extract.ts';+import { isConsumerDateGroundingOn } from '../facts/extract.ts';import { randomUUID, createHash } from 'node:crypto';import { BaseCyclePhase, CYCLE_DEADLINE_RESERVE_MS, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';import { defaultTimeoutMsFor } from '../minions/handler-timeouts.ts';@@ -425,7 +425,7 @@ export const EXTRACTOR_FAILURE_HALT_STREAK = 5;/** Prompt flags read once per phase run: #5425 attribution rules and extraction.date_grounding. */async function takesPromptFlags(engine: BrainEngine): Promise<{ attributionRules: boolean; dateGrounding: boolean }> {const attributionRules = String(await Promise.resolve(engine.getConfig?.('dream.propose_takes.attribution_rules')).catch(() => null) ?? '').trim() === 'true';- return { attributionRules, dateGrounding: (await getExtractorVariant(engine)).dateGrounding === true };+ return { attributionRules, dateGrounding: await isConsumerDateGroundingOn(engine) };}export async function defaultExtractor(diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 79f7e3559b..b07136fd89 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -1,5 +1,5 @@import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';-import { getExtractorVariant } from '../facts/extract.ts';+import { isConsumerDateGroundingOn } from '../facts/extract.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { postprocessManagedSynthesis, withPublishPending } from './synthesize-postprocess.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';@@ -1753,7 +1753,7 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>budgetUsd: parseBudgetUsd(await engine.getConfig('dream.synthesize.budget_usd'), DEFAULT_SYNTH_BUDGET_USD),allowUnpriced: await loadAllowUnpriced(engine),attributionRules: (await engine.getConfig('dream.synthesize.attribution_rules'))?.trim() === 'true',- dateGrounding: (await getExtractorVariant(engine)).dateGrounding === true,+ dateGrounding: await isConsumerDateGroundingOn(engine),cooldownHours,maxPromptTokens,maxChunksPerTranscript,diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.tsindex 7f9eb80cab..3bf4b3dc1d 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -109,9 +109,11 @@ export async function getFactsExtractionPromptAppendix(}/**- * Extraction prompt variants (`extraction.date_grounding`,- * `facts.attribution`): both default off until a held-out verdict sets them.- * `true` / `on` enable; anything else (unset included) is off.+ * Extraction prompt variants. `extraction.date_grounding` defaults ON for fact+ * extraction (held-out verdict p2-e2-heldout-2026-10-04: unresolved relative+ * dates in saved facts 8.95% -> 2.05%, QA non-inferior); `false` / `off` / `0`+ * opt out. `facts.attribution` stays off until its own verdict: `true` / `on`+ * / `1` enable it.*/export interface ExtractorVariant {/** Resolve relative dates against the observation date; emit valid_from. */@@ -120,12 +122,26 @@ export interface ExtractorVariant {attribution?: boolean;}+const flagIs = (v: string | null, values: readonly string[]) => v != null && values.includes(v.trim().toLowerCase());+const FLAG_ON = ['true', 'on', '1'] as const;+const FLAG_OFF = ['false', 'off', '0'] as const;+const readFlag = (engine: BrainEngine, key: string) => Promise.resolve().then(() => engine.getConfig(key)).catch(() => null);+export async function getExtractorVariant(engine?: BrainEngine): Promise<ExtractorVariant> {if (!engine) return {};- const on = (v: string | null) => v != null && ['true', 'on', '1'].includes(v.trim().toLowerCase());- const read = (key: string) => Promise.resolve().then(() => engine.getConfig(key)).catch(() => null);- const [grounding, attribution] = await Promise.all([read('extraction.date_grounding'), read('facts.attribution')]);- return { dateGrounding: on(grounding), attribution: on(attribution) };+ const [grounding, attribution] = await Promise.all([readFlag(engine, 'extraction.date_grounding'), readFlag(engine, 'facts.attribution')]);+ return { dateGrounding: !flagIs(grounding, FLAG_OFF), attribution: flagIs(attribution, FLAG_ON) };+}++/**+ * Date grounding for the other extraction prompts (life chronicle events,+ * dream synthesis, extract_atoms, propose_takes): on only when+ * `extraction.date_grounding` is set on explicitly. The held-out verdict+ * measured fact extraction; each of these keeps its current prompt until its+ * own check passes.+ */+export async function isConsumerDateGroundingOn(engine?: BrainEngine): Promise<boolean> {+ return engine ? flagIs(await readFlag(engine, 'extraction.date_grounding'), FLAG_ON) : false;}/**diff --git a/test/doctor-ranking-extraction.test.ts b/test/doctor-ranking-extraction.test.tsindex 4a1660d4f4..19c03eabc7 100644--- a/test/doctor-ranking-extraction.test.ts+++ b/test/doctor-ranking-extraction.test.ts@@ -50,13 +50,16 @@ describe('hub_degree_shape', () => {});describe('extraction_date_grounding', () => {- test('reports off by default and lists consumers when on', async () => {- const [off] = (await extractionDateGroundingEntry.run(ctx())) as Check[];- expect(off.message).toContain('is off');+ test('fact extraction is grounded by default; the other prompts only when set on; false turns it off', async () => {+ const [byDefault] = (await extractionDateGroundingEntry.run(ctx())) as Check[];+ expect(byDefault.message).toContain('(the default)');+ expect(byDefault.message).toContain('unless extraction.date_grounding is set to true');await engine.setConfig('extraction.date_grounding', 'true');const [on] = (await extractionDateGroundingEntry.run(ctx())) as Check[];- expect(on.message).toContain('propose_takes');- expect(categorizeCheck('extraction_date_grounding')).toBe(categorizeCheck('graph_coverage'));+ expect(on.message).toContain('fact extraction and in: life chronicle events');await engine.setConfig('extraction.date_grounding', 'false');+ const [off] = (await extractionDateGroundingEntry.run(ctx())) as Check[];+ expect(off.message).toContain('is off');+ expect(categorizeCheck('extraction_date_grounding')).toBe(categorizeCheck('graph_coverage'));});});diff --git a/test/facts-extract-junk-filter.test.ts b/test/facts-extract-junk-filter.test.tsindex 1c3dc8cb53..abb904eb7c 100644--- a/test/facts-extract-junk-filter.test.ts+++ b/test/facts-extract-junk-filter.test.ts@@ -223,6 +223,8 @@ afterAll(() => {describe('extraction_prompt_appendix — composes with BOTH prompt variants (#3852)', () => {const APPENDIX = 'Durable-vs-ephemeral rubric: work-session narration is never a fact.';+ // extraction.date_grounding defaults on, so an unconfigured brain gets the grounded variant.+ const GROUNDED = { dateGrounding: true } as const;async function systemSentFor(engine: BrainEngine,@@ -247,19 +249,19 @@ describe('extraction_prompt_appendix — composes with BOTH prompt variants (#38test('label-honestly variant (no admission) gets the appendix appended verbatim', async () => {const engine = stubEngine({ 'facts.extraction_prompt_appendix': APPENDIX });- expect(await systemSentFor(engine)).toBe(`${buildExtractorSystem(true)}\n\n${APPENDIX}`);+ expect(await systemSentFor(engine)).toBe(`${buildExtractorSystem(true, GROUNDED)}\n\n${APPENDIX}`);});test('skip-low variant (high-only admission) gets the SAME appendix', async () => {const engine = stubEngine({ 'facts.extraction_prompt_appendix': APPENDIX });expect(await systemSentFor(engine, { allowed: ['high'], invalid: 'drop' }))- .toBe(`${buildExtractorSystem(false)}\n\n${APPENDIX}`);+ .toBe(`${buildExtractorSystem(false, GROUNDED)}\n\n${APPENDIX}`);});test('unset / empty appendix leaves the precomputed prompt untouched', async () => {- expect(await systemSentFor(stubEngine({}))).toBe(buildExtractorSystem(true));+ expect(await systemSentFor(stubEngine({}))).toBe(buildExtractorSystem(true, GROUNDED));expect(await systemSentFor(stubEngine({ 'facts.extraction_prompt_appendix': ' ' })))- .toBe(buildExtractorSystem(true));+ .toBe(buildExtractorSystem(true, GROUNDED));});});