Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(chronicle): use lane-core's config reader names and decision shape (#5876)
garrytan69949075a1f7
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex e176dfb001..222be20020 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend — each admitted projection is held until its `record()` settles it, so N concurrent callers (skillopt's validation gate) can't all pass against the same cumulative and breach `--max-cost-usd` by (N-1)×per-call cost; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps, its message and `BudgetExhausted.pricing` built by `no-pricing.ts` (warn-once preserved when cap is unset, naming the registration command); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Pricing math (`reservationCostUsd`, overrides, free local providers, unknown-price `null`) lives in the pure `src/core/budget/reservation-cost.ts`, shared with skillopt preflight's impossible-reservation check so the two cannot disagree. Every `record()` also feeds an in-memory model ledger keyed by (requested model, served model, touchpoint, purpose) — updated BEFORE the cap throw and before the unpriced early return — exposed as `snapshot().models`; `BudgetActualUsage` carries `requestedModelId`, `purpose`, `failed`, `countsAsCall` (default true) and `estimated`, and rows track `calls` (gateway operations), `attempts` (every record), `failed_calls`, tokens, `cost_usd` (`null` when unpriced) and `cost_basis` (`estimated` if any contributing record was). `src/core/budget/models-used.ts` maps labels to touchpoints (`gateway.chat`→chat, `gateway.expand*`→expansion, `gateway.embed*`→embedding, `gateway.rerank*`→rerank, `gateway.ocr*`→ocr, else other), builds receipt rows (`buildModelsUsed`), merges resumed segments and renders the "Models called" table. No DB change. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases.- `src/core/budget/no-pricing.ts` — the one `no_pricing` refusal builder. `noPricingGuidance(model, kind)` returns the structured fields (`code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope: 'local_cli'`, `docs` = the `ERROR_CATALOGUE.no_pricing` anchor); `noPricingMessage` renders the one-line cause plus `noPricingSteps` (look up the provider's price, run the `gbrain pricing set` command on the brain host, retry; remote MCP callers ask the operator); `pricingSetCommand` gives the command alone for warnings (chat: `--input`/`--output`, other kinds: `--rate`). Used by BudgetTracker, enrich, conversation facts (CLI and cycle phase), skillopt receipts, the embedding migration authorization and the extract-atoms, budget-meter, embed-backfill and conversation-budget warnings. Pinned by `test/budget/no-pricing-registration.test.ts`.-- `src/core/chronicle/{eligibility,config,reasons,ledger-stats,upgrade-notice,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `config.ts` owns the switch and knobs: `auto_chronicle` is on when unset, true/false words parse, any other word reads as off (`source: 'invalid'`); `readChronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never `next`) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `ledger-stats.ts` rolls up `chronicle_page_state` + `chronicle_judge_reservations` for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). `backstop.runChronicleBackstop` is the former put_page hook body; it has no caller. `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly; each `chronicle_extract` job carries idempotency key `chronicle_extract:<source>:<slug>:<content_hash>`, so a repeat run skips pages already enqueued or extracted for their current content, reports them as `already_enqueued`, and pages past them until `limit` new pages per type are enqueued, #5329). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.+- `src/core/chronicle/{eligibility,config,reasons,ledger-stats,upgrade-notice,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never `next`) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `ledger-stats.ts` rolls up `chronicle_page_state` + `chronicle_judge_reservations` for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). `backstop.runChronicleBackstop` is the former put_page hook body; it has no caller. `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly; each `chronicle_extract` job carries idempotency key `chronicle_extract:<source>:<slug>:<content_hash>`, so a repeat run skips pages already enqueued or extracted for their current content, reports them as `already_enqueued`, and pages past them until `limit` new pages per type are enqueued, #5329). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.- `src/core/chunkers/` — 3-tier chunking (recursive, semantic, LLM-guided). `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.diff --git a/src/commands/config.ts b/src/commands/config.tsindex 2f61d0230e..a572de59ea 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -320,9 +320,9 @@ async function refuseInvalidChronicleValue(key: string, value: string, force: bo* durable doctor/advisor `auto_chronicle_default_on` notice. Best-effort: the value already persisted.*/async function acknowledgeAutoChronicle(engine: BrainEngine, value: string): Promise<void> {- const { CHRONICLE_ACK_KEY, parseAutoChronicle } = await import('../core/chronicle/config.ts');+ const { CHRONICLE_ACK_KEY, autoChronicleSetting } = await import('../core/chronicle/config.ts');try { await engine.setConfig(CHRONICLE_ACK_KEY, new Date().toISOString()); } catch { /* the notice stays; harmless */ }- if (parseAutoChronicle(value).enabled) {+ if (autoChronicleSetting(value) === 'on') {console.log('Automatic event extraction is on: each eligible new or changed meeting, conversation or calendar page gets one paid chat call, bounded by chronicle.job_budget_usd per page and chronicle.auto_daily_limit per day.');console.log('To turn it off: gbrain config set auto_chronicle false');} else {diff --git a/src/commands/doctor/checks/auto-chronicle.ts b/src/commands/doctor/checks/auto-chronicle.tsindex c86eb19832..9f4a3eca41 100644--- a/src/commands/doctor/checks/auto-chronicle.ts+++ b/src/commands/doctor/checks/auto-chronicle.ts@@ -9,7 +9,7 @@*/import {AUTO_CHRONICLE_KEEP_ARGV, AUTO_CHRONICLE_OPT_OUT_ARGV, CHRONICLE_NUMERIC_KEYS, autoChronicleNeedsAcknowledgement,- readAutoChronicle, readChronicleSettings,+ autoChronicleSetting, chronicleSettings,} from '../../../core/chronicle/config.ts';import { describeChronicleActivity, readChronicleLedgerStats } from '../../../core/chronicle/ledger-stats.ts';import { CHRONICLE_REASONS, CHRONICLE_RUN_NOW_ARGV, chronicleBackfillArgv, type ChronicleAction } from '../../../core/chronicle/reasons.ts';@@ -37,26 +37,27 @@ function warn(code: string, message: string, fix: ChronicleAction, extra: Recordasync function runAutoChronicle(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);- const setting = await readAutoChronicle(engine);- const settings = await readChronicleSettings(engine);+ const raw = await engine.getConfig('auto_chronicle');+ const setting = autoChronicleSetting(raw);+ const settings = await chronicleSettings(engine);const checks: Check[] = [];const backfillPreview = command(chronicleBackfillArgv({ since: daysAgo(30), dryRun: true }));- if (setting.source === 'invalid') {+ if (setting === 'invalid') {checks.push({ name: 'auto_chronicle', ...warn('auto_chronicle_invalid',- `auto_chronicle is '${setting.raw}', which is neither true nor false, so automatic event extraction is off. ` ++ `auto_chronicle is '${raw}', which is neither true nor false, so automatic event extraction is off. ` +`Ask the user which they want, then run \`${command(AUTO_CHRONICLE_KEEP_ARGV)}\` or \`${command(AUTO_CHRONICLE_OPT_OUT_ARGV)}\`.`,CHRONICLE_REASONS.auto_chronicle_invalid.fix(), { enabled: false, readiness: 'degraded' }) });- } else if (!setting.enabled) {+ } else if (setting === 'off') {checks.push({ name: 'auto_chronicle', status: 'ok',message: `auto_chronicle is off by choice. History stays available on request (paid; ask the user first): \`${backfillPreview}\`.`,details: { enabled: false, severity: 'info', readiness: 'disabled_by_choice', docs: AUTO_CHRONICLE_DOCS } });} else {const stats = await readChronicleLedgerStats(engine);const chat = await chatAvailable();- const activity = stats.available ? describeChronicleActivity(stats, settings.autoDailyLimit)+ const activity = stats.available ? describeChronicleActivity(stats, settings.dailyLimit): 'The chronicle ledger is not created yet; run `gbrain apply-migrations --yes --no-autopilot-install`.';- const summary = { enabled: true, source: setting.source, daily_limit: settings.autoDailyLimit,+ const summary = { enabled: true, source: raw == null ? 'default' : 'explicit', daily_limit: settings.dailyLimit,job_budget_usd: settings.jobBudgetUsd, ledger_available: stats.available, pending: stats.pending,auto_calls_24h: stats.autoCalls24h, principals_24h: stats.principals24h, last_7d: stats.last7d, spend_7d: stats.spend7d,chat_available: chat, run_now: [...CHRONICLE_RUN_NOW_ARGV] };@@ -69,20 +70,20 @@ async function runAutoChronicle(ctx: DoctorContext): Promise<Check[]> {} else if (stats.last7d.failed > 0 && failures.length > 0) {const [reason] = failures[0];const entry = CHRONICLE_REASONS[reason as keyof typeof CHRONICLE_REASONS];- const ctxFix = { since: daysAgo(7), dailyLimit: settings.autoDailyLimit, recentDays: settings.autoRecentDays };+ const ctxFix = { since: daysAgo(7), dailyLimit: settings.dailyLimit, recentDays: settings.recentDays };const fix: ChronicleAction = ('fix' in entry ? entry.fix(ctxFix) : undefined)?? { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-check after the next cycle.' };checks.push({ name: 'auto_chronicle', ...warn(reason,`auto_chronicle is on; ${stats.last7d.failed} automatic extraction(s) failed in 7 days, most often ${reason}: ${entry.meaning(ctxFix)} ${activity}`,fix, { ...summary, readiness: 'degraded' }) });} else {- const limited = stats.pending > 0 && stats.autoCalls24h >= settings.autoDailyLimit+ const limited = stats.pending > 0 && stats.autoCalls24h >= settings.dailyLimit? ' The daily limit is used up, so pending pages wait for a free slot; raising chronicle.auto_daily_limit needs the user\'s agreement.' : '';const runNow = stats.pending > 0 && !limited? ` Pending pages run in the next autopilot cycle; to run them now: \`${command(CHRONICLE_RUN_NOW_ARGV)}\` (paid).` : limited;const noChat = chat ? '' : ' No chat provider is configured, so nothing will be extracted until one is.';checks.push({ name: 'auto_chronicle', status: 'ok',- message: `auto_chronicle is on${setting.source === 'default' ? ' (default)' : ''}. ${activity}${runNow}${noChat}`,+ message: `auto_chronicle is on${raw == null ? ' (default)' : ''}. ${activity}${runNow}${noChat}`,details: { ...summary, severity: 'info', readiness: chat ? 'ok' : 'missing', docs: AUTO_CHRONICLE_DOCS } });}}@@ -101,11 +102,11 @@ async function runAutoChronicle(ctx: DoctorContext): Promise<Check[]> {}if (await autoChronicleNeedsAcknowledgement(engine)) {- const ceiling = settings.autoDailyLimit * settings.jobBudgetUsd;+ const ceiling = settings.dailyLimit * settings.jobBudgetUsd;checks.push({ name: 'auto_chronicle_default_on', status: 'ok',message: 'Automatic event extraction is on by default and the user has not confirmed it yet. ' +`Each eligible new or changed meeting, conversation or calendar page gets one paid chat call (cap $${settings.jobBudgetUsd.toFixed(2)} per page; ` +- `at most ${settings.autoDailyLimit} calls per day, so at most $${ceiling.toFixed(2)} per day for a priced model; an unpriced model has no cap), ` ++ `at most ${settings.dailyLimit} calls per day, so at most $${ceiling.toFixed(2)} per day for a priced model; an unpriced model has no cap), ` +'and page text goes to the configured chat provider. Relay this to the user, then run ' +`\`${command(AUTO_CHRONICLE_KEEP_ARGV)}\` to keep it or \`${command(AUTO_CHRONICLE_OPT_OUT_ARGV)}\` to opt out.`,details: { code: 'auto_chronicle_default_on', severity: 'info', ask_user: true, docs: AUTO_CHRONICLE_DOCS,diff --git a/src/core/advisor/collect-chronicle.ts b/src/core/advisor/collect-chronicle.tsindex c7c8c1e9f1..b972393419 100644--- a/src/core/advisor/collect-chronicle.ts+++ b/src/core/advisor/collect-chronicle.ts@@ -7,7 +7,7 @@// Advisory display only (no dispatch_id) — the user runs the shown command.import type { AdvisorCollector, AdvisorContext, AdvisorFinding } from './types.ts';import {- AUTO_CHRONICLE_KEEP_ARGV, AUTO_CHRONICLE_OPT_OUT_ARGV, autoChronicleNeedsAcknowledgement, readAutoChronicle, readChronicleSettings,+ AUTO_CHRONICLE_KEEP_ARGV, AUTO_CHRONICLE_OPT_OUT_ARGV, autoChronicleNeedsAcknowledgement, autoChronicleSetting, chronicleSettings,} from '../chronicle/config.ts';import { describeChronicleActivity, readChronicleLedgerStats } from '../chronicle/ledger-stats.ts';import { CHRONICLE_REASONS, chronicleBackfillArgv, type ChronicleAction } from '../chronicle/reasons.ts';@@ -24,12 +24,13 @@ async function chatAvailable(): Promise<boolean> {}async function collectAutoChronicle(ctx: AdvisorContext): Promise<AdvisorFinding[]> {- const setting = await readAutoChronicle(ctx.engine);- if (setting.source === 'invalid') {+ const raw = await ctx.engine.getConfig('auto_chronicle');+ const setting = autoChronicleSetting(raw);+ if (setting === 'invalid') {return [{id: 'auto_chronicle_invalid',severity: 'warn',- title: `auto_chronicle is '${setting.raw}', which reads as off`,+ title: `auto_chronicle is '${raw}', which reads as off`,detail: 'Ask the user whether automatic event extraction should be on (one paid chat call per eligible page) or off, ' +`then run \`${AUTO_CHRONICLE_KEEP_ARGV.join(' ')}\` or \`${AUTO_CHRONICLE_OPT_OUT_ARGV.join(' ')}\`.`,fix: { command_argv: [...AUTO_CHRONICLE_KEEP_ARGV] },@@ -37,18 +38,18 @@ async function collectAutoChronicle(ctx: AdvisorContext): Promise<AdvisorFindingask_user: true,}];}- if (!setting.enabled) return [];+ if (setting === 'off') return [];const findings: AdvisorFinding[] = [];- const settings = await readChronicleSettings(ctx.engine);+ const settings = await chronicleSettings(ctx.engine);const stats = await readChronicleLedgerStats(ctx.engine);- const activity = stats.available ? describeChronicleActivity(stats, settings.autoDailyLimit, { nameWriters: ctx.remote === false }) : '';+ const activity = stats.available ? describeChronicleActivity(stats, settings.dailyLimit, { nameWriters: ctx.remote === false }) : '';if (await autoChronicleNeedsAcknowledgement(ctx.engine)) {findings.push({id: 'auto_chronicle_default_on',severity: 'info',title: 'Automatic event extraction is on by default; confirm it with the user',detail: `Each eligible new or changed meeting, conversation or calendar page gets one paid chat call (cap $${settings.jobBudgetUsd.toFixed(2)} per page, ` +- `at most ${settings.autoDailyLimit} calls per day: $${(settings.autoDailyLimit * settings.jobBudgetUsd).toFixed(2)} per day at most for a priced model; ` ++ `at most ${settings.dailyLimit} calls per day: $${(settings.dailyLimit * settings.jobBudgetUsd).toFixed(2)} per day at most for a priced model; ` +'an unpriced model has no cap). Page text goes to the configured chat provider. ' +`Keep it: \`${AUTO_CHRONICLE_KEEP_ARGV.join(' ')}\`. Opt out: \`${AUTO_CHRONICLE_OPT_OUT_ARGV.join(' ')}\`.` +(activity ? ` ${activity}` : ''),@@ -70,7 +71,7 @@ async function collectAutoChronicle(ctx: AdvisorContext): Promise<AdvisorFinding}const failed = Object.entries(stats.last7d.failedReasons).find(([reason]) => reason in CHRONICLE_REASONS);if (stats.last7d.failed > 0 && failed) {- const reasonCtx = { since: daysAgo(ctx.now ?? new Date(), 7), dailyLimit: settings.autoDailyLimit, recentDays: settings.autoRecentDays };+ const reasonCtx = { since: daysAgo(ctx.now ?? new Date(), 7), dailyLimit: settings.dailyLimit, recentDays: settings.recentDays };const entry = CHRONICLE_REASONS[failed[0] as keyof typeof CHRONICLE_REASONS];const fix: ChronicleAction | undefined = 'fix' in entry ? entry.fix(reasonCtx) : undefined;findings.push({@@ -83,12 +84,12 @@ async function collectAutoChronicle(ctx: AdvisorContext): Promise<AdvisorFindingask_user: fix ? fix.consent.length > 0 || fix.actor !== 'agent' : false,});}- if (stats.pending > 0 && stats.autoCalls24h >= settings.autoDailyLimit) {- const fix = CHRONICLE_REASONS.daily_limit.fix({ dailyLimit: settings.autoDailyLimit, since: daysAgo(ctx.now ?? new Date(), 7) });+ if (stats.pending > 0 && stats.autoCalls24h >= settings.dailyLimit) {+ const fix = CHRONICLE_REASONS.daily_limit.fix({ dailyLimit: settings.dailyLimit, since: daysAgo(ctx.now ?? new Date(), 7) });findings.push({id: 'chronicle_daily_limit',severity: 'info',- title: `The automatic daily limit (${settings.autoDailyLimit} calls) is used up; ${stats.pending} page(s) wait for a free slot`,+ title: `The automatic daily limit (${settings.dailyLimit} calls) is used up; ${stats.pending} page(s) wait for a free slot`,detail: `${fix.why} ${activity}`,fix: { command_argv: fix.argv ?? null },collector: 'chronicle',diff --git a/src/core/chronicle/config.ts b/src/core/chronicle/config.tsindex 800a105ab6..4271e7b9d3 100644--- a/src/core/chronicle/config.ts+++ b/src/core/chronicle/config.ts@@ -16,25 +16,16 @@ const TRUE_WORDS = ['true', '1', 'yes', 'on'];const FALSE_WORDS = ['false', '0', 'no', 'off'];/**- * `default`: unset, so on. `explicit`: a recognized true/false word.- * `invalid`: any other value, read as off (fail closed on spend) and reported by doctor.+ * How a stored `auto_chronicle` value reads (same contract as capy/chronicle-lane-core): unset is on;+ * a recognized true/false word is on/off; any other value reads as off and doctor warns+ * `auto_chronicle_invalid` (fail closed on spend).*/-export interface AutoChronicleSetting {- enabled: boolean;- source: 'default' | 'explicit' | 'invalid';- raw: string | null;-}--export function parseAutoChronicle(raw: string | null | undefined): AutoChronicleSetting {- if (raw == null || raw.trim() === '') return { enabled: true, source: 'default', raw: raw ?? null };+export function autoChronicleSetting(raw: string | null | undefined): 'on' | 'off' | 'invalid' {+ if (raw == null) return 'on';const word = raw.trim().toLowerCase();- if (TRUE_WORDS.includes(word)) return { enabled: true, source: 'explicit', raw };- if (FALSE_WORDS.includes(word)) return { enabled: false, source: 'explicit', raw };- return { enabled: false, source: 'invalid', raw };-}--export async function readAutoChronicle(engine: BrainEngine): Promise<AutoChronicleSetting> {- return parseAutoChronicle(await engine.getConfig(AUTO_CHRONICLE_KEY));+ if (TRUE_WORDS.includes(word)) return 'on';+ if (FALSE_WORDS.includes(word)) return 'off';+ return 'invalid';}/**@@ -43,7 +34,7 @@ export async function readAutoChronicle(engine: BrainEngine): Promise<AutoChroni* bounded by `chronicle.job_budget_usd` per page and `chronicle.auto_daily_limit` per rolling day.*/export async function isAutoChronicleEnabled(engine: BrainEngine): Promise<boolean> {- return (await readAutoChronicle(engine)).enabled;+ return autoChronicleSetting(await engine.getConfig(AUTO_CHRONICLE_KEY)) === 'on';}/**@@ -52,8 +43,7 @@ export async function isAutoChronicleEnabled(engine: BrainEngine): Promise<boole* was a no-op, so it does not count as an answer).*/export async function autoChronicleNeedsAcknowledgement(engine: BrainEngine): Promise<boolean> {- const setting = await readAutoChronicle(engine);- if (!setting.enabled) return false;+ if (!(await isAutoChronicleEnabled(engine))) return false;const ack = await engine.getConfig(CHRONICLE_ACK_KEY);return ack == null || ack.trim() === '';}@@ -107,7 +97,7 @@ function parseNumeric(key: ChronicleNumericKey, raw: string): number | null {/** `config set` validation for auto_chronicle and chronicle.*; returns the refusal text or null. */export function validateChronicleConfigValue(key: string, value: string): string | null {if (key === AUTO_CHRONICLE_KEY) {- return parseAutoChronicle(value).source === 'explicit' ? null+ return autoChronicleSetting(value) !== 'invalid' ? null: `auto_chronicle must be true or false (got '${value}'). Nothing was written. ` +'To turn automatic event extraction off: gbrain config set auto_chronicle false';}@@ -118,23 +108,26 @@ export function validateChronicleConfigValue(key: string, value: string): stringreturn null;}+/** Field names match capy/chronicle-lane-core's `chronicleSettings`, plus `judgeMaxTokens` and `invalid`. */export interface ChronicleSettings {jobBudgetUsd: number;- /** True when the operator set the cap: an unpriced model then refuses with no_pricing instead of warn-and-run. */- jobBudgetExplicit: boolean;- autoDailyLimit: number;- autoRecentDays: number;- autoSettleSeconds: number;+ /** The operator set chronicle.job_budget_usd: an unpriced model then refuses with no_pricing instead of warn-and-run. */+ explicitBudget: boolean;+ dailyLimit: number;+ recentDays: number;+ settleSeconds: number;judgeMaxTokens: number;+ /** When the automatic path activated on this brain (written by the ledger migration); null when unset or unreadable. */+ activatedAt: Date | null;/** Stored values outside the valid range; each fell back to its default. */invalid: Array<{ key: ChronicleNumericKey; raw: string; fallback: number }>;}-/** Reads every chronicle.* knob; a malformed or unreadable row falls back to its default. */-export async function readChronicleSettings(engine: BrainEngine): Promise<ChronicleSettings> {+/** Reads every chronicle.* knob; a malformed or unreadable row falls back to its default and is listed in `invalid`. */+export async function chronicleSettings(engine: BrainEngine): Promise<ChronicleSettings> {const invalid: ChronicleSettings['invalid'] = [];const values = {} as Record<ChronicleNumericKey, number>;- let budgetExplicit = false;+ let explicitBudget = false;for (const key of Object.keys(CHRONICLE_NUMERIC_KEYS) as ChronicleNumericKey[]) {const fallback = CHRONICLE_NUMERIC_KEYS[key].fallback;const raw = await engine.getConfig(key).catch(() => null);@@ -142,15 +135,18 @@ export async function readChronicleSettings(engine: BrainEngine): Promise<Chroniconst parsed = parseNumeric(key, raw);if (parsed === null) { invalid.push({ key, raw, fallback }); values[key] = fallback; continue; }values[key] = parsed;- if (key === 'chronicle.job_budget_usd') budgetExplicit = true;+ if (key === 'chronicle.job_budget_usd') explicitBudget = true;}+ const activated = await engine.getConfig(CHRONICLE_ACTIVATED_AT_KEY).catch(() => null);+ const activatedAt = activated ? new Date(activated) : null;return {jobBudgetUsd: values['chronicle.job_budget_usd'],- jobBudgetExplicit: budgetExplicit,- autoDailyLimit: values['chronicle.auto_daily_limit'],- autoRecentDays: values['chronicle.auto_recent_days'],- autoSettleSeconds: values['chronicle.auto_settle_seconds'],+ explicitBudget,+ dailyLimit: values['chronicle.auto_daily_limit'],+ recentDays: values['chronicle.auto_recent_days'],+ settleSeconds: values['chronicle.auto_settle_seconds'],judgeMaxTokens: values['chronicle.judge_max_tokens'],+ activatedAt: activatedAt && !Number.isNaN(activatedAt.getTime()) ? activatedAt : null,invalid,};}diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.tsindex 0adfba190c..7e29feb252 100644--- a/src/core/chronicle/reasons.ts+++ b/src/core/chronicle/reasons.ts@@ -145,7 +145,12 @@ export type ChronicleReasonCode = keyof typeof CHRONICLE_REASONS;/** Eligibility reasons for pages that are not chronicle-shaped: the receipt omits the field for them. */const NOT_CHRONICLE_SHAPED = /^(kind:|diary_excluded$|event_self$|subagent_scratch$)/;-export type ChronicleDecision = { state: 'pending' } | { state: 'skipped'; reason: string };+/**+ * The write-time decision (capy/chronicle-lane-core `decideChronicle`): `pending` with no reason is+ * queued for the next cycle; `pending` with a reason (`not_yet_happened`) waits and reports that+ * reason like a skip; `skipped` carries its reason.+ */+export type ChronicleDecision = { state: 'pending' | 'skipped'; reason?: string | null };export type ChronicleBackstopReceipt =| { pending: 'next_cycle'; daily_remaining?: number }@@ -157,18 +162,21 @@ export type ChronicleBackstopReceipt =* still reports itself with a doctor pointer rather than disappearing.*/export function chronicleBackstopReceipt(decision: ChronicleDecision, ctx: ChronicleReasonContext & { dailyRemaining?: number }): ChronicleBackstopReceipt | undefined {- if (decision.state === 'pending') {- return { pending: 'next_cycle', ...(ctx.dailyRemaining === undefined ? {} : { daily_remaining: ctx.dailyRemaining }) };+ if (!decision.reason) {+ return decision.state === 'pending'+ ? { pending: 'next_cycle', ...(ctx.dailyRemaining === undefined ? {} : { daily_remaining: ctx.dailyRemaining }) }+ : chronicleBackstopReceipt({ state: 'skipped', reason: 'unknown' }, ctx);}- if (NOT_CHRONICLE_SHAPED.test(decision.reason)) return undefined;- const entry: ChronicleReason | undefined = (CHRONICLE_REASONS as Record<string, ChronicleReason>)[decision.reason];+ const reason = decision.reason;+ if (NOT_CHRONICLE_SHAPED.test(reason)) return undefined;+ const entry: ChronicleReason | undefined = (CHRONICLE_REASONS as Record<string, ChronicleReason>)[reason];if (!entry) {- return { skipped: decision.reason, stage: 'decision', why: `Extraction was skipped (${decision.reason}).`,+ return { skipped: reason, stage: 'decision', why: `Extraction was skipped (${reason}).`,fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,why: 'Read the auto_chronicle check for details.' } };}const fix = entry.fix?.(ctx);- return { skipped: decision.reason, stage: entry.stage, why: entry.meaning(ctx), ...(fix ? { fix } : {}) };+ return { skipped: reason, stage: entry.stage, why: entry.meaning(ctx), ...(fix ? { fix } : {}) };}function shellWord(word: string): string {diff --git a/src/core/chronicle/upgrade-notice.ts b/src/core/chronicle/upgrade-notice.tsindex b3b4be1c16..3a195a39f4 100644--- a/src/core/chronicle/upgrade-notice.ts+++ b/src/core/chronicle/upgrade-notice.ts@@ -5,7 +5,7 @@import type { BrainEngine } from '../engine.ts';import {AUTO_CHRONICLE_KEEP_ARGV, AUTO_CHRONICLE_OPT_OUT_ARGV, CHRONICLE_NOTICE_SHOWN_KEY, autoChronicleNeedsAcknowledgement,- readChronicleSettings,+ chronicleSettings,} from './config.ts';import { chronicleBackfillArgv } from './reasons.ts';@@ -34,18 +34,18 @@ export async function autoChronicleUpgradeNotice(engine: BrainEngine, view?: Chrconst shown = await engine.getConfig(CHRONICLE_NOTICE_SHOWN_KEY);if (shown != null && shown.trim() !== '') return null;if (!(await autoChronicleNeedsAcknowledgement(engine))) return null;- const settings = await readChronicleSettings(engine);+ const settings = await chronicleSettings(engine);const provider = view ?? await providerView(engine);- const ceiling = settings.autoDailyLimit * settings.jobBudgetUsd;+ const ceiling = settings.dailyLimit * settings.jobBudgetUsd;const since = new Date(Date.now() - 30 * 86_400_000).toISOString().slice(0, 10);const runs = engine.kind === 'pglite'? 'On this PGLite brain, pending pages run inside the autopilot cycle; `gbrain dream --phase chronicle` runs them now.': 'On this Postgres brain, pending pages run in the autopilot cycle; `gbrain dream --phase chronicle` runs them now.';const cost = provider.priced- ? `Worst case: ${settings.autoDailyLimit} calls/day x $${settings.jobBudgetUsd.toFixed(2)} per-page cap = $${ceiling.toFixed(2)}/day with ${provider.model}. ` ++ ? `Worst case: ${settings.dailyLimit} calls/day x $${settings.jobBudgetUsd.toFixed(2)} per-page cap = $${ceiling.toFixed(2)}/day with ${provider.model}. ` +'The cap is per page, not a daily budget; typical pages cost far less.': `gbrain has no price for ${provider.model ?? 'the configured chat model'}, so the per-page cap ($${settings.jobBudgetUsd.toFixed(2)}) cannot apply: ` +- `calls are unbounded in dollars (still at most ${settings.autoDailyLimit} per day).`;+ `calls are unbounded in dollars (still at most ${settings.dailyLimit} per day).`;return ['','═══════════════════════════════════════════════════════════════',@@ -55,7 +55,7 @@ export async function autoChronicleUpgradeNotice(engine: BrainEngine, view?: Chr'═══════════════════════════════════════════════════════════════',`[AGENT] Relay this to the user: it spends money and sends page text to the configured chat provider${provider.model ? ` (${provider.model})` : ''}.`,`[AGENT] ${cost}`,- `[AGENT] Only pages written after this upgrade, dated within ${settings.autoRecentDays} days, run automatically; history is not swept.`,+ `[AGENT] Only pages written after this upgrade, dated within ${settings.recentDays} days, run automatically; history is not swept.`,`[AGENT] ${runs}`,...(provider.chatAvailable ? [] : ['[AGENT] No chat provider is configured, so nothing runs until the user sets one up.']),`[AGENT] Keep it (records the user's answer): ${AUTO_CHRONICLE_KEEP_ARGV.join(' ')}`,diff --git a/test/chronicle-config-5876.test.ts b/test/chronicle-config-5876.test.tsindex f228a0844b..2a346b81cd 100644--- a/test/chronicle-config-5876.test.ts+++ b/test/chronicle-config-5876.test.ts@@ -13,7 +13,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runConfig } from '../src/commands/config.ts';import {- CHRONICLE_ACK_KEY, autoChronicleNeedsAcknowledgement, isAutoChronicleEnabled, parseAutoChronicle, readChronicleSettings,+ CHRONICLE_ACK_KEY, autoChronicleNeedsAcknowledgement, isAutoChronicleEnabled, autoChronicleSetting, chronicleSettings,validateChronicleConfigValue,} from '../src/core/chronicle/config.ts';import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';@@ -42,21 +42,23 @@ async function runConfigCapture(args: string[]) {describe('auto_chronicle parsing', () => {test('unset is on by default; true/false words parse; anything else reads as off and invalid', async () => {expect(await isAutoChronicleEnabled(engine)).toBe(true);- expect(parseAutoChronicle(null)).toEqual({ enabled: true, source: 'default', raw: null });- for (const v of ['true', 'YES', ' on ', '1']) expect(parseAutoChronicle(v)).toMatchObject({ enabled: true, source: 'explicit' });- for (const v of ['false', 'No', 'off', '0']) expect(parseAutoChronicle(v)).toMatchObject({ enabled: false, source: 'explicit' });- expect(parseAutoChronicle('flase')).toEqual({ enabled: false, source: 'invalid', raw: 'flase' });+ expect(autoChronicleSetting(null)).toBe('on');+ for (const v of ['true', 'YES', ' on ', '1']) expect(autoChronicleSetting(v)).toBe('on');+ for (const v of ['false', 'No', 'off', '0']) expect(autoChronicleSetting(v)).toBe('off');+ expect(autoChronicleSetting('flase')).toBe('invalid');+ await engine.setConfig('auto_chronicle', 'flase');+ expect(await isAutoChronicleEnabled(engine)).toBe(false);await engine.setConfig('auto_chronicle', 'false');expect(await isAutoChronicleEnabled(engine)).toBe(false);});test('chronicle.* rails: defaults, explicit budget flag, malformed rows fall back', async () => {- expect(await readChronicleSettings(engine)).toMatchObject({ jobBudgetUsd: 0.25, jobBudgetExplicit: false, autoDailyLimit: 200,- autoRecentDays: 30, autoSettleSeconds: 180, judgeMaxTokens: 4000, invalid: [] });+ expect(await chronicleSettings(engine)).toMatchObject({ jobBudgetUsd: 0.25, explicitBudget: false, dailyLimit: 200,+ recentDays: 30, settleSeconds: 180, judgeMaxTokens: 4000, invalid: [] });await engine.setConfig('chronicle.job_budget_usd', '0.4');await engine.setConfig('chronicle.auto_daily_limit', 'lots');- const s = await readChronicleSettings(engine);- expect(s).toMatchObject({ jobBudgetUsd: 0.4, jobBudgetExplicit: true, autoDailyLimit: 200 });+ const s = await chronicleSettings(engine);+ expect(s).toMatchObject({ jobBudgetUsd: 0.4, explicitBudget: true, dailyLimit: 200 });expect(s.invalid).toEqual([{ key: 'chronicle.auto_daily_limit', raw: 'lots', fallback: 200 }]);});diff --git a/test/chronicle-reasons-5876.test.ts b/test/chronicle-reasons-5876.test.tsindex d324d1f2d1..9613aca0ef 100644--- a/test/chronicle-reasons-5876.test.ts+++ b/test/chronicle-reasons-5876.test.ts@@ -36,6 +36,15 @@ describe('chronicle_backstop receipt', () => {});});+ test('a pending decision that waits for its end time reports the reason, not next_cycle', () => {+ expect(chronicleBackstopReceipt({ state: 'pending', reason: 'not_yet_happened' }, ctx)).toEqual({+ skipped: 'not_yet_happened', stage: 'decision',+ why: 'The calendar event has not ended yet; it is picked up automatically after its end time, with no edit needed.',+ });+ expect(chronicleBackstopReceipt({ state: 'pending', reason: null }, { ...ctx, dailyRemaining: 3 }))+ .toEqual({ pending: 'next_cycle', daily_remaining: 3 });+ });+test('confined writers route the fix to the brain host; off-by-choice carries no fix', () => {expect(chronicleBackstopReceipt({ state: 'skipped', reason: 'slug_bound_client' }, ctx)).toMatchObject({ fix: { actor: 'host_admin' } });const off = chronicleBackstopReceipt({ state: 'skipped', reason: 'auto_chronicle_off' }, ctx);diff --git a/test/helpers/chronicle-ledger-stub.ts b/test/helpers/chronicle-ledger-stub.tsindex 025caed2ce..257515a9e6 100644--- a/test/helpers/chronicle-ledger-stub.ts+++ b/test/helpers/chronicle-ledger-stub.ts@@ -1,6 +1,6 @@/*** TEMPORARY (Lane 2 of the #5876 wave): Lane 1's `chronicle_page_state` and- * `chronicle_judge_reservations` DDL (capy/chronicle-lane-core 95e8d6d04, migration+ * `chronicle_judge_reservations` DDL (capy/chronicle-lane-core a643de5bd, migration* `chronicle_page_state`) minus the foreign keys, so the surface tests run before that migration* merges. The integrator deletes this helper once the migration is on the branch.*/@@ -12,7 +12,7 @@ export async function createChronicleLedgerStub(engine: BrainEngine): Promise<voslug TEXT NOT NULL, state TEXT NOT NULL CHECK (state IN ('pending','skipped','extracted','failed')), reason TEXT,trigger TEXT NOT NULL CHECK (trigger IN ('auto','backfill')), principal_kind TEXT, principal_id TEXT, request_id UUID,no_extract BOOLEAN NOT NULL DEFAULT false, attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), next_attempt_at TIMESTAMPTZ,- cost_usd NUMERIC, unpriced BOOLEAN NOT NULL DEFAULT false, event_slugs TEXT[] NOT NULL DEFAULT '{}',+ cost_usd NUMERIC, unpriced BOOLEAN NOT NULL DEFAULT false, event_slugs TEXT[] NOT NULL DEFAULT '{}', event_hashes TEXT[] NOT NULL DEFAULT '{}',decided_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (source_id, page_id, content_hash, extractor_version))`);await engine.executeRaw(`CREATE TABLE IF NOT EXISTS chronicle_judge_reservations (