Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(extraction): date grounding defaults on for dream synthesis, extract_atoms and propose_takes (per-consumer checks pass); life chronicle stays opt-in

garrytan5b97d9bee37c
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index e35238a0ae..b8521f1290 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -9,6 +9,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `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/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, synthesis, atoms and takes grounded by default, all off when the setting is false, and whether the chronicle prompt is 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.md
index 217829d8ef..37a249bb6c 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). 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/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, dream synthesis, extract_atoms and propose_takes add the rule by default (`extraction.date_grounding` unset or true; `false` turns all off; held-out verdict and per-consumer checks in `docs/eval/decisions/p2-e2-heldout/`); the life chronicle judge adds it only when the setting is explicitly `true` (`isConsumerDateGroundingOn(engine, consumer)`). 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.md
index 01f4c2311f..3d9066598e 100644
--- a/docs/eval/decisions/p2-e2-heldout/README.md
+++ b/docs/eval/decisions/p2-e2-heldout/README.md
@@ -21,20 +21,39 @@ 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.
+`extraction.date_grounding` defaults on for fact extraction and for the three other prompts that passed their per-consumer
+check. `false`, `off` or `0` turns all of them off. `true` also turns on life chronicle events, the one prompt that did not
+pass. `gbrain doctor` (`extraction_date_grounding`) reports which prompts are grounded on a brain.
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`.
+## Per-consumer checks (preregistration amendment 3)
+
+The held-out verdict measured fact extraction. The four other prompts that know the rule were each checked on 30 invented
+dated fixture pages. Each fixture has 3–6 relative time references, a decision, a plan and a prediction, and fixtures were
+written by `google:gemini-3.8-flash` before any prompt ran. Each prompt ran twice per fixture through its own product
+prompt builder (`anthropic:claude-sonnet-5-5`): as today, and grounded. Two measures:
+- unresolved relative phrases in the stored items (the facts lane's check);
+- a blind pairwise judge (`openai:gpt-6-sol`, 10 replicates per fixture, A/B order randomized per replicate).
+
+Pass needs (a) fewer unresolved phrases when grounded, and (b) a judge score (grounded win 1, tie 0.5, loss 0) with a 95%
+bootstrap lower bound of at least 0.45.
+
+| Prompt | Unresolved phrases, current → grounded | Judge score (95% CI) | Verdicts (grounded / tie / current) | Result | Default |
+|---|---|---|---|---|---|
+| dream synthesis | 49 → 1 (475 → 615 items) | 0.813 (0.71, 0.92) | 224 / 40 / 36 | pass | on |
+| extract_atoms | 5 → 0 (66 → 69 items) | 0.973 (0.94, 0.99) | 292 / 0 / 8 | pass | on |
+| propose_takes | 10 → 0 (96 → 99 items) | 0.933 (0.87, 0.99) | 275 / 10 / 15 | pass | on |
+| life chronicle events | 0 → 0 (149 → 155 items) | 0.937 (0.86, 0.99) | 281 / 0 / 19 | fail (a) | opt-in (`true`) |
+
+Life chronicle events fails criterion (a) on a floor: its events already carry an absolute `when` field, so neither arm
+stored an unresolved phrase (0 → 0). The judge preferred the grounded events in 281 of 300 comparisons. The preregistered
+bar is applied as written, so chronicle stays on its current prompt unless the setting is `true`. Changing that would
+need a new preregistered check.
+
+The fixtures, outputs, judgments and the script that produced them are in gbrain-evals at
+`docs/benchmarks/p2-e2-consumers/` (branch `capy/p2-preregistration`). `per-consumer-report.json` here is the summary.
+The budget ledger did not meter this spend, because the calls went to providers directly; the preregistered estimate was $12.
+
Development record: `../p2-date-grounding-dev/`.
diff --git a/docs/eval/decisions/p2-e2-heldout/per-consumer-report.json b/docs/eval/decisions/p2-e2-heldout/per-consumer-report.json
new file mode 100644
index 0000000000..877808e6c9
--- /dev/null
+++ b/docs/eval/decisions/p2-e2-heldout/per-consumer-report.json
@@ -0,0 +1,97 @@
+{
+ "generation_model": "anthropic:claude-sonnet-5-5",
+ "judge_model": "gpt-6-sol",
+ "replicates": 10,
+ "result": {
+ "chronicle": {
+ "fixtures_scored": 30,
+ "unresolved": {
+ "current": 0,
+ "grounded": 0,
+ "items_current": 149,
+ "items_grounded": 155
+ },
+ "judge_score": 0.9366666666666666,
+ "judge_ci95": [
+ 0.8599999999999999,
+ 0.9900000000000001
+ ],
+ "verdict_counts": {
+ "grounded": 281,
+ "current": 19
+ },
+ "generation_errors": 0,
+ "pass_a": false,
+ "pass_b": true,
+ "pass": false
+ },
+ "atoms": {
+ "fixtures_scored": 30,
+ "unresolved": {
+ "current": 5,
+ "grounded": 0,
+ "items_current": 66,
+ "items_grounded": 69
+ },
+ "judge_score": 0.9733333333333333,
+ "judge_ci95": [
+ 0.94,
+ 0.9933333333333334
+ ],
+ "verdict_counts": {
+ "grounded": 292,
+ "current": 8
+ },
+ "generation_errors": 0,
+ "pass_a": true,
+ "pass_b": true,
+ "pass": true
+ },
+ "takes": {
+ "fixtures_scored": 30,
+ "unresolved": {
+ "current": 10,
+ "grounded": 0,
+ "items_current": 96,
+ "items_grounded": 99
+ },
+ "judge_score": 0.9333333333333332,
+ "judge_ci95": [
+ 0.8666666666666667,
+ 0.9866666666666666
+ ],
+ "verdict_counts": {
+ "grounded": 275,
+ "tie": 10,
+ "current": 15
+ },
+ "generation_errors": 0,
+ "pass_a": true,
+ "pass_b": true,
+ "pass": true
+ },
+ "synthesis": {
+ "fixtures_scored": 30,
+ "unresolved": {
+ "current": 49,
+ "grounded": 1,
+ "items_current": 475,
+ "items_grounded": 615
+ },
+ "judge_score": 0.8133333333333332,
+ "judge_ci95": [
+ 0.7066666666666667,
+ 0.9166666666666666
+ ],
+ "verdict_counts": {
+ "grounded": 224,
+ "tie": 40,
+ "current": 36
+ },
+ "generation_errors": 0,
+ "pass_a": true,
+ "pass_b": true,
+ "pass": true
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/commands/doctor/checks/ranking-extraction.ts b/src/commands/doctor/checks/ranking-extraction.ts
index 946685666d..aa129890d9 100644
--- a/src/commands/doctor/checks/ranking-extraction.ts
+++ b/src/commands/doctor/checks/ranking-extraction.ts
@@ -53,22 +53,23 @@ export const hubDegreeShapeEntry: DoctorEntry = {
run: runHubDegreeShape,
};
-/** 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'];
+/** Prompts grounded by default with fact extraction, and the ones that need the setting set on explicitly. */
+const DEFAULT_CONSUMERS = 'fact extraction, dream synthesis, extract_atoms and propose_takes';
+const OPT_IN_LABEL = 'life chronicle events';
async function runExtractionDateGrounding(ctx: DoctorContext): Promise<Check[]> {
const engine = connectedEngine(ctx);
const checks: Check[] = [];
- const [variant, consumers] = await Promise.all([getExtractorVariant(engine), isConsumerDateGroundingOn(engine)]);
+ const [variant, optIn] = await Promise.all([getExtractorVariant(engine), isConsumerDateGroundingOn(engine, 'chronicle')]);
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
? '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}`,
+ : optIn
+ ? `Relative dates resolve against each source's observation date in ${DEFAULT_CONSUMERS}, and in ${OPT_IN_LABEL} (set on explicitly). ${reextract}`
+ : `Relative dates resolve against each source's observation date in ${DEFAULT_CONSUMERS} (the default). ${OPT_IN_LABEL} keep their current prompt 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.ts
index 3d934c5295..bf2fa0e343 100644
--- a/src/core/chronicle/extract-events.ts
+++ b/src/core/chronicle/extract-events.ts
@@ -310,7 +310,7 @@ 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 { isConsumerDateGroundingOn } = await import('../facts/extract.ts');
- const grounded = await isConsumerDateGroundingOn(engine);
+ const grounded = await isConsumerDateGroundingOn(engine, 'chronicle');
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.ts
index b9898115ac..a4a28aeada 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.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 isConsumerDateGroundingOn(engine);
+ const dateGrounding = await isConsumerDateGroundingOn(engine, 'atoms');
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.ts
index 93c8244203..59efb44dbd 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.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 isConsumerDateGroundingOn(engine) };
+ return { attributionRules, dateGrounding: await isConsumerDateGroundingOn(engine, 'takes') };
}
export async function defaultExtractor(
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index b07136fd89..95b33d63d3 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.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 isConsumerDateGroundingOn(engine),
+ dateGrounding: await isConsumerDateGroundingOn(engine, 'synthesis'),
cooldownHours,
maxPromptTokens,
maxChunksPerTranscript,
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 3bf4b3dc1d..659d6b71d6 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -134,14 +134,21 @@ export async function getExtractorVariant(engine?: BrainEngine): Promise<Extract
}
/**
- * 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.
+ * Date grounding for the other extraction prompts. Each defaulted from its own
+ * per-consumer check (preregistration amendment 3, results in
+ * docs/eval/decisions/p2-e2-heldout/): dream synthesis, extract_atoms and
+ * propose_takes passed and follow the fact-extraction default (on unless the
+ * setting is false/off/0); life chronicle events did not clear the
+ * unresolved-phrase criterion and stays on its current prompt unless the
+ * setting is explicitly true.
*/
-export async function isConsumerDateGroundingOn(engine?: BrainEngine): Promise<boolean> {
- return engine ? flagIs(await readFlag(engine, 'extraction.date_grounding'), FLAG_ON) : false;
+export type DateGroundingConsumer = 'chronicle' | 'synthesis' | 'atoms' | 'takes';
+const OPT_IN_CONSUMERS: ReadonlySet<DateGroundingConsumer> = new Set(['chronicle']);
+
+export async function isConsumerDateGroundingOn(engine: BrainEngine | undefined, consumer: DateGroundingConsumer): Promise<boolean> {
+ if (!engine) return false;
+ const raw = await readFlag(engine, 'extraction.date_grounding');
+ return OPT_IN_CONSUMERS.has(consumer) ? flagIs(raw, FLAG_ON) : !flagIs(raw, FLAG_OFF);
}
/**
diff --git a/test/cycle/extract-atoms-config-caps.test.ts b/test/cycle/extract-atoms-config-caps.test.ts
index 3ce5fdc2f6..166d6709ec 100644
--- a/test/cycle/extract-atoms-config-caps.test.ts
+++ b/test/cycle/extract-atoms-config-caps.test.ts
@@ -73,7 +73,8 @@ describe('extract_atoms configurable caps (#4540)', () => {
expect(calls[0].maxTokens).toBe(DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS);
const content = userContent(calls[0]);
// Body is prefix + truncated content: the 55k payload was cut to 50k.
- expect(content.length).toBeLessThan(DEFAULT_EXTRACT_MAX_INPUT_CHARS + 200);
+ // + the preamble (source line and the default observation-date line).
+ expect(content.length).toBeLessThan(DEFAULT_EXTRACT_MAX_INPUT_CHARS + 300);
expect(content.length).toBeGreaterThanOrEqual(DEFAULT_EXTRACT_MAX_INPUT_CHARS);
});
@@ -91,8 +92,8 @@ describe('extract_atoms configurable caps (#4540)', () => {
expect(calls.length).toBe(1);
expect(calls[0].maxTokens).toBe(512);
const content = userContent(calls[0]);
- // 2000 content chars + the small "Source: ..." preamble.
- expect(content.length).toBeLessThan(2_200);
+ // 2000 content chars + the small preamble ("Source: ..." and the observation-date line).
+ expect(content.length).toBeLessThan(2_300);
expect(content).toContain('y'.repeat(2_000));
expect(content).not.toContain('y'.repeat(2_001));
});
diff --git a/test/doctor-ranking-extraction.test.ts b/test/doctor-ranking-extraction.test.ts
index 19c03eabc7..d9dc8b1b71 100644
--- a/test/doctor-ranking-extraction.test.ts
+++ b/test/doctor-ranking-extraction.test.ts
@@ -52,11 +52,11 @@ describe('hub_degree_shape', () => {
describe('extraction_date_grounding', () => {
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');
+ expect(byDefault.message).toContain('fact extraction, dream synthesis, extract_atoms and propose_takes (the default)');
+ expect(byDefault.message).toContain('life chronicle events keep their current prompt 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('fact extraction and in: life chronicle events');
+ expect(on.message).toContain('and in life chronicle events (set on explicitly)');
await engine.setConfig('extraction.date_grounding', 'false');
const [off] = (await extractionDateGroundingEntry.run(ctx())) as Check[];
expect(off.message).toContain('is off');
diff --git a/test/facts/extract-date-grounding.test.ts b/test/facts/extract-date-grounding.test.ts
index 0eb8abc4a3..cd7fdb71ba 100644
--- a/test/facts/extract-date-grounding.test.ts
+++ b/test/facts/extract-date-grounding.test.ts
@@ -14,7 +14,7 @@
import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
import { configureGateway, resetGateway, __setChatTransportForTests } from '../../src/core/ai/gateway.ts';
import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';
-import { buildExtractorSystem, extractFactsFromTurnWithOutcome } from '../../src/core/facts/extract.ts';
+import { buildExtractorSystem, extractFactsFromTurnWithOutcome, getExtractorVariant, isConsumerDateGroundingOn } from '../../src/core/facts/extract.ts';
import { observationDateRule } from '../../src/core/ai/date-grounding.ts';
import { segmentObservationDate } from '../../src/commands/extract-conversation-facts.ts';
import type { Page } from '../../src/core/types.ts';
@@ -105,3 +105,19 @@ describe('segmentObservationDate', () => {
expect(segmentObservationDate(page({ date: '2025-12-24' }), '2025-12-24T00:00:00Z')).toEqual({ date: '2025-12-24', source: 'caller' });
});
});
+
+describe('defaults from the verdicts', () => {
+ const engineWith = (v: string | null) => ({ getConfig: async (k: string) => (k === 'extraction.date_grounding' ? v : null) }) as never;
+ test('unset: fact extraction, synthesis, atoms and takes grounded; chronicle not', async () => {
+ expect((await getExtractorVariant(engineWith(null))).dateGrounding).toBe(true);
+ for (const c of ['synthesis', 'atoms', 'takes'] as const) expect(await isConsumerDateGroundingOn(engineWith(null), c)).toBe(true);
+ expect(await isConsumerDateGroundingOn(engineWith(null), 'chronicle')).toBe(false);
+ });
+ test('true turns every prompt on; false turns every prompt off', async () => {
+ for (const c of ['chronicle', 'synthesis', 'atoms', 'takes'] as const) {
+ expect(await isConsumerDateGroundingOn(engineWith('true'), c)).toBe(true);
+ expect(await isConsumerDateGroundingOn(engineWith('false'), c)).toBe(false);
+ }
+ expect((await getExtractorVariant(engineWith('off'))).dateGrounding).toBe(false);
+ });
+});