Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(chronicle): chronicle_backfill makes progress across repeat runs (#5329)
garrytandfee86c50c24
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 44e00c4aea..100fb2a900 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -25,7 +25,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 (warn-once preserved when cap is unset); `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/chronicle/{eligibility,config,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). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `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). 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); doctor `chronicle_projection_health` (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,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). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `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); doctor `chronicle_projection_health` (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/core/ops/chronicle.ts b/src/core/ops/chronicle.tsindex 95aa501466..01da87a983 100644--- a/src/core/ops/chronicle.ts+++ b/src/core/ops/chronicle.ts@@ -278,50 +278,72 @@ const chronicle_backfill: Operation = {outputRedaction: 'no_stored_text',description:'Life Chronicle: sweep existing meeting/conversation/calendar pages into timeline events by ' +- 'enqueuing chronicle_extract jobs (one per eligible page). --dry-run counts without enqueuing. ' +- 'Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--limit N] [--dry-run]`.',+ 'enqueuing chronicle_extract jobs (one per eligible page). A page whose current content was already ' ++ 'enqueued is skipped (already_enqueued), so repeat runs move on to pages not yet swept. --dry-run counts ' ++ 'without enqueuing. Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--limit N] [--dry-run]`.',scope: 'admin',mutating: true,localOnly: true,params: {since: { type: 'string', description: 'Only pages updated on/after this date (YYYY-MM-DD).' },- limit: { type: 'number', description: 'Max pages per type to sweep (default 1000).' },+ limit: { type: 'number', description: 'Max pages per type to enqueue in this run (default 1000); pages already enqueued for their current content do not count.' },dry_run: { type: 'boolean', description: 'Count eligible pages without enqueuing.' },},handler: async (ctx, p) => {const { isChronicleEligible } = await import('../chronicle/eligibility.ts');const TYPES = ['meeting', 'conversation', 'calendar-event'] as const;+ const PAGE_BATCH = 200;const limit = typeof p.limit === 'number' ? p.limit : 1000;const updated_after = typeof p.since === 'string' ? p.since : undefined;const dryRun = p.dry_run === true;const scope = sourceScopeOpts(ctx);- type QueueLike = { add: (n: string, d: Record<string, unknown>) => Promise<unknown> };+ type QueueLike = { add: (n: string, d: Record<string, unknown>, o?: { idempotency_key?: string }) => Promise<{ coalesced?: boolean }> };let queue: QueueLike | null = null;if (!dryRun) {const { MinionQueue } = await import('../minions/queue.ts');queue = new MinionQueue(ctx.engine) as unknown as QueueLike;}- let scanned = 0, eligible = 0, enqueued = 0;+ // #5329: one job per (source, page, content). The key makes a repeat run+ // skip pages already enqueued or extracted for their current content and+ // page past them, so the tail of the corpus is reached; an edited page+ // gets a new key and is swept again.+ const jobKey = (page: { source_id?: string; slug: string; content_hash?: string; updated_at?: Date | string }) =>+ `chronicle_extract:${page.source_id ?? 'default'}:${page.slug}:${page.content_hash ?? String(page.updated_at ?? '')}`;+ let scanned = 0, eligible = 0, enqueued = 0, alreadyEnqueued = 0;const errors: { slug: string; error: string }[] = [];for (const type of TYPES) {- const pages = await ctx.engine.listPages({ type, updated_after, limit, ...scope });- for (const page of pages) {- scanned++;- const dreamGenerated = (page.frontmatter as Record<string, unknown> | undefined)?.dream_generated === true;- const elig = isChronicleEligible({ type: page.type, slug: page.slug, body: page.compiled_truth, dreamGenerated });- if (!elig.ok) continue;- eligible++;- if (dryRun || !queue) continue;- try {- await queue.add('chronicle_extract', { slug: page.slug, sourceId: page.source_id });- enqueued++;- } catch (e) {- // Never swallow — surface per-page failures (the #2057 no-swallow pattern).- errors.push({ slug: page.slug, error: e instanceof Error ? e.message : String(e) });+ let taken = 0;+ for (let offset = 0; taken < limit; offset += PAGE_BATCH) {+ const pages = await ctx.engine.listPages({ type, updated_after, limit: PAGE_BATCH, offset, ...scope });+ const candidates = pages.filter((page) => {+ scanned++;+ const dreamGenerated = (page.frontmatter as Record<string, unknown> | undefined)?.dream_generated === true;+ return isChronicleEligible({ type: page.type, slug: page.slug, body: page.compiled_truth, dreamGenerated }).ok;+ });+ eligible += candidates.length;+ const keys = candidates.map(jobKey);+ const known = new Set(keys.length === 0 ? [] : (await ctx.engine.executeRaw<{ idempotency_key: string }>(+ `SELECT idempotency_key FROM minion_jobs WHERE idempotency_key = ANY($1::text[]) AND status NOT IN ('dead', 'cancelled')`,+ [keys],+ )).map((row) => row.idempotency_key));+ for (const [i, page] of candidates.entries()) {+ if (taken >= limit) break;+ if (known.has(keys[i])) { alreadyEnqueued++; continue; }+ taken++;+ if (dryRun || !queue) continue;+ try {+ const job = await queue.add('chronicle_extract', { slug: page.slug, sourceId: page.source_id }, { idempotency_key: keys[i] });+ if (job.coalesced) alreadyEnqueued++;+ else enqueued++;+ } catch (e) {+ // Never swallow — surface per-page failures (the #2057 no-swallow pattern).+ errors.push({ slug: page.slug, error: e instanceof Error ? e.message : String(e) });+ }}+ if (pages.length < PAGE_BATCH) break;}}- return { scanned, eligible, enqueued, dry_run: dryRun, errors };+ return { scanned, eligible, enqueued, already_enqueued: alreadyEnqueued, dry_run: dryRun, errors };},cliHints: { name: 'chronicle-backfill' },};diff --git a/test/chronicle-backfill.test.ts b/test/chronicle-backfill.test.tsindex 0487839839..fbb2b9e558 100644--- a/test/chronicle-backfill.test.ts+++ b/test/chronicle-backfill.test.ts@@ -63,4 +63,31 @@ describe('chronicle_backfill op', () => {{ slug: 'meetings/other-src', sourceId: 'other-src' },]);});++ // #5329: repeat runs used to enqueue the same head pages forever.+ test('#5329: repeat runs with a small limit progress through every page, then enqueue nothing', async () => {+ for (const n of [1, 2, 3]) await engine.putPage(`meetings/m${n}`, { type: 'meeting', title: `m${n}`, compiled_truth: LONG });+ type R = { enqueued: number; already_enqueued: number };+ const run = async () => await operationsByName.chronicle_backfill.handler(mkCtx(), { limit: 1 }) as R;+ for (let i = 0; i < 3; i++) expect((await run()).enqueued).toBe(1);+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE name = 'chronicle_extract'`);+ const again = await run();+ expect(again.enqueued).toBe(0);+ expect(again.already_enqueued).toBe(3);+ const slugs = await engine.executeRaw<{ slug: string }>(`SELECT data->>'slug' AS slug FROM minion_jobs WHERE name = 'chronicle_extract' ORDER BY 1`);+ expect(slugs.map(r => r.slug)).toEqual(['meetings/m1', 'meetings/m2', 'meetings/m3']);+ });++ test('#5329: an edited page is swept again; a dead job does not block a retry', async () => {+ await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG });+ await engine.putPage('meetings/m2', { type: 'meeting', title: 'm2', compiled_truth: LONG });+ await operationsByName.chronicle_backfill.handler(mkCtx(), {});+ await engine.putPage('meetings/m1', { type: 'meeting', title: 'm1', compiled_truth: LONG + ' edited' });+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'dead' WHERE name = 'chronicle_extract' AND data->>'slug' = 'meetings/m2'`);+ const dry = await operationsByName.chronicle_backfill.handler(mkCtx(), { dry_run: true }) as { eligible: number; already_enqueued: number };+ expect(dry.already_enqueued).toBe(0);+ const r = await operationsByName.chronicle_backfill.handler(mkCtx(), {}) as { enqueued: number; already_enqueued: number };+ expect(r.enqueued).toBe(2);+ expect(r.already_enqueued).toBe(0);+ });});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 4e8504af67..04fa6de2b0 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 204300,- "stdoutSha256": "90db6033940f46bd5594c9786287792ce46970d6aeba5f01fe31067083d003c2",+ "stdoutBytes": 204505,+ "stdoutSha256": "361a0a6ada8208de169e71c9f95264e6bd6e6a3dc652a6148f46230a824035af","toolNames": ["remember","entity",@@ -3956,7 +3956,7 @@}},{- "description": "Life Chronicle: sweep existing meeting/conversation/calendar pages into timeline events by enqueuing chronicle_extract jobs (one per eligible page). --dry-run counts without enqueuing. Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--limit N] [--dry-run]`.",+ "description": "Life Chronicle: sweep existing meeting/conversation/calendar pages into timeline events by enqueuing chronicle_extract jobs (one per eligible page). A page whose current content was already enqueued is skipped (already_enqueued), so repeat runs move on to pages not yet swept. --dry-run counts without enqueuing. Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--limit N] [--dry-run]`.","name": "chronicle_backfill","parameters": {"dry_run": "boolean?",@@ -3970,7 +3970,7 @@"type": "boolean"},"limit": {- "description": "Max pages per type to sweep (default 1000).",+ "description": "Max pages per type to enqueue in this run (default 1000); pages already enqueued for their current content do not count.","type": "number"},"since": {