Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
belief ledger lane C review fixes: coverage state ignores restores, enable/complete/disable under the source lock (#7 #27 #16 #17), restore marks read purge-mirror's fields (#8), backfill outside drift (#15), read-only drift scan (#24), bounded routine scans (#28), one stale-preparation code (#29), ambient source (#37), lifetime cut (#41)
garrytan7b18238b77c1
diff --git a/docs/architecture/key-files/belief-ledger.md b/docs/architecture/key-files/belief-ledger.mdindex 45258d79ad..17e593c2f8 100644--- a/docs/architecture/key-files/belief-ledger.md+++ b/docs/architecture/key-files/belief-ledger.md@@ -10,10 +10,10 @@ Design: [BELIEF_LEDGER.md](../../designs/BELIEF_LEDGER.md). Operator surface: `g- `src/core/belief/state.ts` / `subjects.ts` — raw stream state (a page, its fence and DB-only facts, takes, and links whose origin, else from, page it is) and its keyed subjects; row ids are payload, never keys.- `src/core/belief/ledger.ts` — the finalization contract. `withBeliefBatch` reads the state of the held page keys before and after the transaction's projections and appends the canonical diff (origin `live` on a managed brain, `unmanaged` otherwise, or the caller's override). `beliefBatchCovers` and `insideBeliefBatch` let a nested writer skip its own batch. Managed mode comes from `readManagedMode`, never a direct `persistence_brain` read.- `src/core/belief/append.ts` — the one insert (`appendBeliefEvents`): tombstones and the redaction register first, then deterministic `event_key`s. `markBeliefCommits` writes the post-commit observation (`observed_at >= recorded_at`); `__setBeliefEmitterFaultForTests` is the forced-probe seam.-- `src/core/belief/coverage.ts` — `enableBeliefLedger` (`coverage.started`, a resumable per-page baseline, `coverage.complete` whose recorded_at is the watermark; certified only on a managed brain) and `disableBeliefLedger` (`coverage.stopped`).-- `src/core/belief/coverage-report.ts` — readers: `coverageIntervals`, `coverageAt` (refuses `coverage_from` before the watermark, `coverage_gap` in a stopped span), `beliefEventVisibility` (an unmarked publication is `unproven` until a commit mark or a later event of the page proves it). Drift: `scanBeliefDrift` (sampled, or deep) compares each slug's current `state_hash` with its newest event; `reconcileBeliefDrift` appends `reconcile` events (the slug interval stays uncertified). `orphanLifetimes`, `unmarkedPublications`/`fillCommitMarks`, and `cycleBeliefReconcile` for the extract phase.+- `src/core/belief/coverage.ts` — `enableBeliefLedger` (`coverage.started`, a resumable per-page baseline, `coverage.complete` whose recorded_at is the watermark; certified only on a managed brain) and `disableBeliefLedger` (`coverage.stopped`). Start, complete and stop are decided under the source row FOR UPDATE: a second enable resumes the open run, a disable mid-walk ends it with no `complete`, and the completion re-checks the pending set (a page renamed behind the cursor). A slug no page key can name is skipped and listed (`unkeyable_slugs`). The coverage state is the newest event other than `coverage.restored`, so a restore never restarts a stopped ledger.+- `src/core/belief/coverage-report.ts` — readers: `coverageIntervals` (restore marks carry purge-mirror's `archived_at`, `purge_replay`, `replays`), `coverageAt` (refuses `coverage_from` before the slug's cut, found under the slug or its page lifetime, and `coverage_gap` in a stopped span or a restore gap), `beliefEventVisibility` (an unmarked publication is `unproven` until a commit mark or a later event of the page proves it). Drift: `scanBeliefDrift` (sampled, or deep; read-only, it mints no lifetime) compares each slug's current `state_hash` with its newest non-backfill event; `reconcileBeliefDrift` appends `reconcile` events (the slug interval stays uncertified). `orphanLifetimes` and `unmarkedPublications`/`fillCommitMarks` read a recent window unless `deep`; `cycleBeliefReconcile` for the extract phase.- `src/core/belief/projection-point.ts` — `unmanagedBeliefPoint` (and `withUnmanagedBeliefs` for one transaction): the legacy import, `extract_facts` fence reconcile, takes reextract and the derived link writers (`derived-links.ts`, the remote auto-links effect, attendance repair) lock their sorted page keys and run in an `unmanaged` batch, then mark the commit. Every other unmanaged writer is found by drift.-- `src/core/belief/backfill.ts` — `backfillBeliefHistory`: marked history from `page_versions` only (git is not read), origin `backfill`, historical time in `source_time`, recorded_at the run time; a purge during the run retries (`belief_preparation_stale`), and the summary event says whether pruned versions left it incomplete.+- `src/core/belief/backfill.ts` — `backfillBeliefHistory`: marked history from `page_versions` only (git is not read), origin `backfill`, historical time in `source_time`, recorded_at the run time; a purge during the run retries (`belief_stale_preparation`), and the summary event says whether pruned versions left it incomplete.- `src/core/belief/history.ts` — the one history reader (`readBeliefHistory`); remote callers see only events that were world-visible when recorded on a page visible now, failing closed.- `src/commands/beliefs.ts` — `gbrain beliefs enable|disable|status|reconcile|backfill` (local only; `--json`); an unknown source is `invalid_params`.- `src/commands/doctor/checks/belief-ledger.ts` — doctor `belief_ledger_coverage`: intervals and certification, baseline progress, drift (sampled; complete under `--tier deep`), orphan lifetimes, unmarked publications, and a restore whose purge replay was partial, unavailable or unverified (`ask_user`). `--fix` reconciles and fills marks; a brain without coverage is information with an `ask_user` enable.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 8677f5b47e..c0d0a1315e 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -188,9 +188,9 @@ More: [docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database](../.More: [docs/designs/BELIEF_LEDGER.md#72-the-marked-history-backfill](../../docs/designs/BELIEF_LEDGER.md#72-the-marked-history-backfill)-### belief_preparation_stale+### belief_stale_preparation-<a id="belief_preparation_stale"></a>+<a id="belief_stale_preparation"></a>| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|diff --git a/src/commands/beliefs.ts b/src/commands/beliefs.tsindex 7ed0736ea0..2f98dcd282 100644--- a/src/commands/beliefs.ts+++ b/src/commands/beliefs.ts@@ -16,6 +16,7 @@ import { coverageIntervals, coveredSources, fillCommitMarks, orphanLifetimes, reimport { backfillBeliefHistory } from '../core/belief/backfill.ts';import { readLedgerSource } from '../core/belief/ledger.ts';import { readManagedMode } from '../core/persistence/managed-mode.ts';+import { resolveSourceId, SourceTargetError } from '../core/source-resolver.ts';export const BELIEFS_USAGE = ['Usage: gbrain beliefs <enable|disable|status|reconcile|backfill> [--source <id>] [--json]',@@ -26,15 +27,16 @@ export const BELIEFS_USAGE = [' reconcile Appends reconcile events for slugs whose state drifted from their newest event, and fills missing commit marks.',' A drifted slug\'s interval stays uncertified on a managed source.',' backfill Seeds best-effort history before the coverage start from retained page versions (never certified).',- ' --source <id> The source (default: every covered source for status and reconcile, "default" for the others).',+ ' --source <id> The source (default: every covered source for status and reconcile; the resolved source, as for other commands, for the rest).',].join('\n');const SUBCOMMANDS = ['enable', 'disable', 'status', 'reconcile', 'backfill'] as const;function sourceArg(args: string[]): string | undefined {const at = args.indexOf('--source');- if (at >= 0) return args[at + 1];- return args.find(a => a.startsWith('--source='))?.slice('--source='.length);+ const value = at >= 0 ? args[at + 1] : args.find(a => a.startsWith('--source='))?.slice('--source='.length);+ if ((at >= 0 || value !== undefined) && (!value || value.startsWith('-'))) throw opError('invalid_params', '--source needs a source id.', 'Pass --source <id>; gbrain sources list shows the ids.');+ return value;}const unknownSource = (sourceId: string) => opError('invalid_params', `Source ${sourceId} does not exist.`, 'Run gbrain sources list to see the source ids.');@@ -50,7 +52,7 @@ async function sourceStatus(engine: BrainEngine, sourceId: string) {function renderInterval(i: CoverageInterval): string[] {const lines = [` interval from ${i.started_at}${i.stopped_at ? ` to ${i.stopped_at}` : ' (open)'}: ${i.certified ? 'certified (links: journaled publications only)' : 'uncertified'}`,` watermark: ${i.watermark ?? 'none yet'}; baseline: ${i.baseline.pages_done} page(s) done${i.baseline.complete ? ', complete' : `, ${i.baseline.pending ?? '?'} pending (rerun gbrain beliefs enable to resume)`}`];- for (const r of i.restores) lines.push(` restore at ${r.at} from an archive of ${r.archive_created_at ?? 'unknown time'} (gap); purge replay: ${r.purge_replay ?? 'unknown'}`);+ for (const r of i.restores) lines.push(` restore at ${r.at} from an archive of ${r.archived_at ?? 'unknown time'} (gap); purge replay: ${r.purge_replay ?? 'unknown'}`);if (i.drift.length) lines.push(` drift: ${i.drift.length} reconcile mark(s), uncertified permanently for ${[...new Set(i.drift.map(d => d.slug))].slice(0, 5).join(', ')}`);return lines;}@@ -69,21 +71,26 @@ export async function runBeliefs(engine: BrainEngine, args: string[]): Promise<v}const named = sourceArg(args);if (named !== undefined && !await readLedgerSource(engine, named)) throw unknownSource(named);+ const target = () => resolveSourceId(engine, named).catch(error => {+ throw error instanceof SourceTargetError ? opError('invalid_params', error.message, 'Pass --source <id>; gbrain sources list shows the ids.') : error;+ });if (sub === 'enable') {- const sourceId = named ?? 'default';+ const sourceId = await target();const run = await enableBeliefLedger(engine, sourceId);- await report(args, { source_id: sourceId, ...run }, `Belief ledger ${run.resumed ? 'resumed' : 'enabled'} on ${sourceId}: ${run.pages} page(s) baselined; `- + `${run.certified ? 'certified (managed source)' : 'uncertified (unmanaged source: recorded, never certified)'}.`);+ const outcome = !run.complete ? 'stopped before the baseline finished (a disable ran meanwhile); nothing is certified'+ : run.certified ? 'certified (managed source)' : 'uncertified (unmanaged source: recorded, never certified)';+ await report(args, { source_id: sourceId, ...run }, `Belief ledger ${run.resumed ? 'resumed' : 'enabled'} on ${sourceId}: ${run.pages} page(s) baselined; ${outcome}.`+ + `${run.unkeyable.length ? ` ${run.unkeyable.length} slug(s) no page key can name were not baselined: ${run.unkeyable.slice(0, 5).join(', ')}.` : ''}`);return;}if (sub === 'disable') {- const sourceId = named ?? 'default';+ const sourceId = await target();const stopped = await disableBeliefLedger(engine, sourceId);await report(args, { source_id: sourceId, stopped }, stopped ? `Belief ledger stopped on ${sourceId}.` : `The belief ledger was not recording ${sourceId}.`);return;}if (sub === 'backfill') {- const sourceId = named ?? 'default';+ const sourceId = await target();const result = await backfillBeliefHistory(engine, sourceId);const incomplete = result.pages.filter(p => !p.complete);await report(args, result, `Backfilled ${result.events} event(s) before ${result.since} across ${result.pages.length} page(s) of ${sourceId} (best effort, never certified)`@@ -105,7 +112,7 @@ export async function runBeliefs(engine: BrainEngine, args: string[]): Promise<vconst results = [];for (const sourceId of sources) {const drift = await reconcileBeliefDrift(engine, sourceId);- results.push({ source_id: sourceId, checked: drift.scan.checked, reconciled: drift.reconciled, events: drift.events, commit_marks_filled: await fillCommitMarks(engine, sourceId) });+ results.push({ source_id: sourceId, checked: drift.scan.checked, reconciled: drift.reconciled, events: drift.events, commit_marks_filled: await fillCommitMarks(engine, sourceId, { deep: true }) });}await report(args, { sources: results }, results.length ? results.map(r => `${r.source_id}: ${r.checked} slug(s) checked, ${r.reconciled.length} reconciled (${r.events} event(s)), `+ `${r.commit_marks_filled} commit mark(s) filled.`).join('\n') : 'No source has belief ledger coverage; nothing to reconcile.');diff --git a/src/commands/doctor/checks/belief-ledger.ts b/src/commands/doctor/checks/belief-ledger.tsindex 4071e5a424..243addc783 100644--- a/src/commands/doctor/checks/belief-ledger.ts+++ b/src/commands/doctor/checks/belief-ledger.ts@@ -42,24 +42,25 @@ async function runBeliefLedger(ctx: DoctorContext): Promise<Check[]> {for (const sourceId of sources) {if (ctx.doFix && !ctx.dryRun) {await reconcileBeliefDrift(engine, sourceId, deep ? { op: 'doctor_fix' } : { op: 'doctor_fix', limit: DRIFT_SAMPLE_PAGES });- await fillCommitMarks(engine, sourceId);+ await fillCommitMarks(engine, sourceId, { deep });}const intervals = await coverageIntervals(engine, sourceId);const drift = await scanBeliefDrift(engine, sourceId, { deep });const open = intervals.at(-1)!;perSource.push({ source_id: sourceId, recording: !open.stopped_at, certified: open.certified, watermark: open.watermark, baseline: open.baseline,intervals: intervals.length, drift: { checked: drift.checked, candidates: drift.candidates, exact: drift.exact, slugs: drift.drifted.slice(0, 10).map(d => d.slug), count: drift.drifted.length },- drift_marks: open.drift.length, orphans: await orphanLifetimes(engine, sourceId, 5), unmarked: (await unmarkedPublications(engine, sourceId, 1000)).length,+ drift_marks: open.drift.length, orphans: await orphanLifetimes(engine, sourceId, 5, { deep }), unmarked: (await unmarkedPublications(engine, sourceId, 1000, { deep })).length,restores: open.restores.filter(r => r.purge_replay && UNSAFE_REPLAY.has(r.purge_replay)) });}const details = { sources: perSource, deep, docs: DOCS };const restore = perSource.find(s => s.restores.length);if (restore) {const r = restore.restores.at(-1)!;+ const unreplayed = r.replays.filter(x => x.outcome !== 'complete').map(x => x.request_id);checks.push({ name: 'belief_ledger_coverage', status: 'warn', details,- message: `A backup restore of ${restore.source_id} at ${r.at} could not replay every purge made after the archive (${r.archive_created_at ?? 'unknown time'}): purge replay ${r.purge_replay}`- + `${r.purge_requests.length ? ` for ${r.purge_requests.join(', ')}` : ''}. Content purged after the backup may be readable again.`,- fix: { argv: r.replay_argv ?? ['gbrain', 'beliefs', 'status', '--source', restore.source_id, '--json'], consent: [], actor: 'user', ask_user: true, requires_exclusive: false, docs: DOCS,+ message: `A backup restore of ${restore.source_id} at ${r.at} could not replay every purge made after the archive (${r.archived_at ?? 'unknown time'}): purge replay ${r.purge_replay}`+ + `${unreplayed.length ? ` for ${unreplayed.join(', ')}` : ''}. Content purged after the backup may be readable again.`,+ fix: { argv: ['gbrain', 'beliefs', 'status', '--source', restore.source_id, '--json'], consent: [], actor: 'user', ask_user: true, requires_exclusive: false, docs: DOCS,why: 'The replay reads the purge events of the original brain; only the user can say where it is, or whether to run those purges again.',user_message: `Your restored brain may contain content you purged after the backup was made (${restore.source_id}). Do you have the original brain available so the purges can be replayed, or should they be run again?`,verify: doctorVerify('belief_ledger_coverage') } });diff --git a/src/core/belief/backfill.ts b/src/core/belief/backfill.tsindex 5af5c99d32..4e77a9d5e1 100644--- a/src/core/belief/backfill.ts+++ b/src/core/belief/backfill.ts@@ -85,7 +85,7 @@ async function bodySubjects(engine: BrainEngine, lifetime: string, text: string,}/** Reads one page's retained versions before `since` and builds its backfill publications, under the epoch it read. */-async function preparePage(engine: BrainEngine, sourceId: string, slug: string, since: string): Promise<Prepared | null> {+async function preparePage(engine: BrainEngine, sourceId: string, slug: string, since: string, hidden: ReadonlySet<string>): Promise<Prepared | null> {const source = await readLedgerSource(engine, sourceId);if (!source) return null;const [page] = await engine.executeRaw<{ id: number; created_at: string; large: boolean; visible: boolean; compiled_truth: string | null; timeline: string | null; revision: string }>(`SELECT p.id, p.created_at, p.knowledge_revision::text AS revision,@@ -106,8 +106,6 @@ async function preparePage(engine: BrainEngine, sourceId: string, slug: string,const atStart: Body = { revision: closing ? closing.revision : page.revision, source_time: before.length ? iso(before.at(-1)!.snapshot_at)! : iso(page.created_at)!,text: closing ? text(closing) : page.large ? null : `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}` };const chain = [...bodies, atStart];- const hidden = new Set((await engine.executeRaw<{ subject_key: string }>(`SELECT DISTINCT subject_key FROM belief_events WHERE source_id = $1 AND event_type = 'derived.hidden'`,- [sourceId])).map(r => r.subject_key));const drafts: BeliefEventDraft[][] = [];let prior: Keyed[] = [];let priorRevision: string | null = null;@@ -143,7 +141,7 @@ async function preparePage(engine: BrainEngine, sourceId: string, slug: string,return { epoch: source.purgeEpoch, incarnation: source.incarnation, lifetime, pageId: Number(page.id), versions: chain, drafts, summary, complete, reasons: [...new Set(reasons)].sort() };}-/** Appends one prepared page under its key; refuses (`belief_preparation_stale`) when a purge moved the source's epoch since preparation. */+/** Appends one prepared page under its key; refuses (`belief_stale_preparation`) when a purge moved the source's epoch since preparation. */async function appendPrepared(engine: BrainEngine, sourceId: string, slug: string, prepared: Prepared): Promise<{ events: number; publications: string[] }> {const publications: string[] = [];const events = await engine.transaction(async tx => {@@ -151,7 +149,7 @@ async function appendPrepared(engine: BrainEngine, sourceId: string, slug: strinconst source = await readLedgerSource(tx, sourceId);if (!source || source.incarnation !== prepared.incarnation) return 0;if (source.purgeEpoch !== prepared.epoch) {- throw opError('belief_preparation_stale', `A purge ran in source ${sourceId} after the backfill of ${slug} was prepared.`,+ throw opError('belief_stale_preparation', `A purge ran in source ${sourceId} after the backfill of ${slug} was prepared.`,'The backfill prepares the page again from the current, redacted versions; rerun gbrain beliefs backfill if it gave up.');}let n = 0;@@ -181,9 +179,12 @@ export async function backfillBeliefHistory(engine: BrainEngine, sourceId: strinconst since = first.started_at;const slugs = opts.slugs ?? (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id = $1 ORDER BY slug', [sourceId])).map(r => r.slug);const report: BackfillReport = { source_id: sourceId, since, pages: [], events: 0, retried: 0 };+ const hiddenKeys = async () => new Set((await engine.executeRaw<{ subject_key: string }>(`SELECT DISTINCT subject_key FROM belief_events+ WHERE source_id = $1 AND event_type = 'derived.hidden'`, [sourceId])).map(r => r.subject_key));+ let hidden = await hiddenKeys();for (const slug of slugs) {for (let attempt = 0; ; attempt++) {- const prepared = await preparePage(engine, sourceId, slug, since);+ const prepared = await preparePage(engine, sourceId, slug, since, hidden);if (!prepared) break;await opts.prepareHook?.(slug, attempt);try {@@ -193,8 +194,9 @@ export async function backfillBeliefHistory(engine: BrainEngine, sourceId: strinreport.events += events;break;} catch (error) {- if ((error as { code?: string }).code !== 'belief_preparation_stale' || attempt + 1 >= MAX_EPOCH_RETRIES) throw error;+ if ((error as { code?: string }).code !== 'belief_stale_preparation' || attempt + 1 >= MAX_EPOCH_RETRIES) throw error;report.retried++;+ hidden = await hiddenKeys();}}}diff --git a/src/core/belief/coverage-report.ts b/src/core/belief/coverage-report.tsindex a3fe61f24d..467f3b4fe3 100644--- a/src/core/belief/coverage-report.ts+++ b/src/core/belief/coverage-report.ts@@ -17,14 +17,15 @@*/import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';+import type { PurgeReplayState, ReplayRecord } from './purge-mirror.ts';import { COVERAGE_KEY, pageKey, valueHash } from './keys.ts';import { appendBeliefEvents, markBeliefCommits, type BeliefEventDraft } from './append.ts';import { coverageActive, currentStateHash, readLedgerSource } from './ledger.ts';import { keyedSubjects } from './subjects.ts';import { endLifetime, readOpenLifetimes } from './lifetimes.ts';-export type PurgeReplay = 'complete' | 'partial' | 'unavailable' | 'unverified';-export interface RestoreMark { event_id: number; at: string; archive_created_at: string | null; purge_replay: PurgeReplay | null; purge_requests: string[]; replay_argv: string[] | null }+/** One `coverage.restored` (purge-mirror.ts `replayPurgesInRestore`): the archive time and the purge replay outcome. */+export interface RestoreMark { event_id: number; at: string; archived_at: string | null; purge_replay: PurgeReplayState | null; replays: ReplayRecord[] }export interface DriftMark { slug: string; event_id: number; from: string | null; to: string }export interface CoverageInterval {run: string | null; incarnation: string; started_id: number; started_at: string;@@ -65,22 +66,24 @@ export async function coverageIntervals(engine: BrainEngine, sourceId: string):current.certified = obj(row.cause).certified === true;current.links_certified = current.certified ? 'journaled_only' : false;current.baseline.complete = true;+ const pages = obj(row.cause).pages;+ if (typeof pages === 'number') current.baseline.pages_done = pages;} else if (row.event_type === 'coverage.stopped') current.stopped_at = iso(row.recorded_at);else if (row.event_type === 'coverage.restored') {- const archive = field(row, 'archive_created_at');- const requests = field(row, 'purge_requests');- const argv = field(row, 'replay_argv');- current.restores.push({ event_id: id, at: iso(row.recorded_at), archive_created_at: archive ? iso(archive) : null,- purge_replay: (field(row, 'purge_replay') as PurgeReplay | undefined) ?? null, purge_requests: Array.isArray(requests) ? requests.map(String) : [],- replay_argv: Array.isArray(argv) ? argv.map(String) : null });+ const archive = field(row, 'archived_at');+ const replays = field(row, 'replays');+ current.restores.push({ event_id: id, at: iso(row.recorded_at), archived_at: archive ? iso(archive) : null,+ purge_replay: (field(row, 'purge_replay') as PurgeReplayState | undefined) ?? null, replays: Array.isArray(replays) ? replays as ReplayRecord[] : [] });}}for (const interval of intervals) {- const [done] = await engine.executeRaw<{ n: number }>(`SELECT count(DISTINCT slug)::int AS n FROM belief_events- WHERE source_id = $1 AND event_type = 'baseline' AND cause->>'run' = $2`, [sourceId, interval.run ?? '']);- interval.baseline.pages_done = Number(done?.n ?? 0);+ if (!interval.baseline.complete || !interval.baseline.pages_done) {+ const [done] = await engine.executeRaw<{ n: number }>(`SELECT count(DISTINCT slug)::int AS n FROM belief_events+ WHERE source_id = $1 AND event_type = 'baseline' AND cause->>'run' = $2`, [sourceId, interval.run ?? '']);+ interval.baseline.pages_done = Number(done?.n ?? 0);+ }const drift = await engine.executeRaw<{ id: number; slug: string; recorded_at: string; from: string | null }>(`SELECT id, slug, recorded_at, cause->>'uncertified_from' AS "from"- FROM belief_events WHERE source_id = $1 AND origin = 'reconcile' AND subject_kind = 'page' AND source_incarnation = $2::uuid AND id > $3+ FROM belief_events WHERE source_id = $1 AND subject_kind = 'page' AND origin = 'reconcile' AND source_incarnation = $2::uuid AND id > $3AND ($4::timestamptz IS NULL OR recorded_at <= $4::timestamptz) ORDER BY id`,[sourceId, interval.incarnation, interval.started_id, interval.stopped_at]);interval.drift = drift.map(d => ({ slug: d.slug, event_id: Number(d.id), from: d.from ? iso(d.from) : null, to: iso(d.recorded_at) }));@@ -102,10 +105,11 @@ export type CoverageAt =| { ok: false; code: 'coverage_from'; from: string | null; message: string }| { ok: false; code: 'coverage_gap'; reason: 'not_covered' | 'restore'; from: string | null; until: string | null; message: string };-/** The first recorded cut of `slug` in the interval: its baseline, creation snapshot or first page-less assertion. */+/** The first recorded cut of `slug` in the interval: its baseline, creation snapshot or first page-less assertion, under the slug or its page's lifetime (a renamed page keeps its cut). */async function slugCut(engine: BrainEngine, sourceId: string, interval: CoverageInterval, slug: string): Promise<string | null> {const [row] = await engine.executeRaw<{ recorded_at: string }>(`SELECT recorded_at FROM belief_events- WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND id > $4+ WHERE source_id = $1 AND source_incarnation = $2::uuid AND id > $4 AND origin <> 'backfill'+ AND (slug = $3 OR page_lifetime = (SELECT l.page_lifetime FROM belief_page_lifetimes l WHERE l.source_incarnation = $2::uuid AND l.slug = $3 AND l.ended_at IS NULL))AND (event_type = 'baseline' OR (event_type = 'page.published' AND value->>'revision_before' IS NULL)OR (page_lifetime IS NULL AND subject_kind = 'fact' AND event_type = 'fact.asserted'))ORDER BY id LIMIT 1`, [sourceId, interval.incarnation, slug, interval.started_id]);@@ -133,10 +137,10 @@ export async function coverageAt(engine: BrainEngine, sourceId: string, at: Datereturn { ok: false, code: 'coverage_gap', reason: 'not_covered', from: interval?.stopped_at ?? null, until: next?.started_at ?? null,message: `The belief ledger was not recording ${sourceId} at ${new Date(t).toISOString()}.` };}- const gap = interval.restores.find(r => r.archive_created_at && t > Date.parse(r.archive_created_at) && t <= Date.parse(r.at));+ const gap = interval.restores.find(r => r.archived_at && t > Date.parse(r.archived_at) && t <= Date.parse(r.at));if (gap) {- return { ok: false, code: 'coverage_gap', reason: 'restore', from: gap.archive_created_at, until: gap.at,- message: `A backup restore at ${gap.at} replaced the ledger with an archive from ${gap.archive_created_at}; what happened between them is unknown.` };+ return { ok: false, code: 'coverage_gap', reason: 'restore', from: gap.archived_at, until: gap.at,+ message: `A backup restore at ${gap.at} replaced the ledger with an archive from ${gap.archived_at}; what happened between them is unknown.` };}const cut = slug ? await slugCut(engine, sourceId, interval, slug) : interval.watermark;if (!cut || t < Date.parse(cut)) {@@ -168,6 +172,7 @@ export async function beliefEventVisibility(engine: BrainEngine, eventId: numberexport interface DriftFinding { slug: string; recorded_hash: string | null; current_hash: string; last_event_id: number | null }export interface DriftScan { checked: number; candidates: number; exact: boolean; drifted: DriftFinding[] }export const DRIFT_SAMPLE_PAGES = 200;+export const UNMARKED_WINDOW_DAYS = 7;/*** Slugs whose current belief set no longer hashes to the `state_hash` of their@@ -195,13 +200,13 @@ export async function scanBeliefDrift(engine: BrainEngine, sourceId: string, optasync function newestEvent(tx: BrainEngine, sourceId: string, incarnation: string, slug: string): Promise<{ id: number; state_hash: string; recorded_at: string } | null> {const [row] = await tx.executeRaw<{ id: number; state_hash: string; recorded_at: string }>(`SELECT id, state_hash, recorded_at FROM belief_events- WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND subject_kind <> 'coverage' ORDER BY id DESC LIMIT 1`, [sourceId, incarnation, slug]);+ WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND subject_kind <> 'coverage' AND origin <> 'backfill' ORDER BY id DESC LIMIT 1`, [sourceId, incarnation, slug]);return row ? { id: Number(row.id), state_hash: row.state_hash, recorded_at: iso(row.recorded_at) } : null;}async function driftOf(engine: BrainEngine, sourceId: string, incarnation: string, slug: string): Promise<DriftFinding | null> {return engine.transaction(async tx => {- const [{ hash, state }, last] = [await currentStateHash(tx, sourceId, incarnation, slug), await newestEvent(tx, sourceId, incarnation, slug)];+ const [{ hash, state }, last] = [await currentStateHash(tx, sourceId, incarnation, slug, { readOnly: true }), await newestEvent(tx, sourceId, incarnation, slug)];if (last?.state_hash === hash) return null;const open = await readOpenLifetimes(tx, [{ incarnation, slug }]);if (!last && !state.pages.some(p => p.slug === slug) && !state.facts.length && !open.size) return null;@@ -242,8 +247,8 @@ export async function reconcileSlug(engine: BrainEngine, sourceId: string, slug:id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world').filter(s => s.stream === slug && (page && !page.deleted || s.dbOnly));const recorded = await tx.executeRaw<{ id: number; subject_kind: string; subject_key: string; event_type: string; value: unknown; value_hash: string | null; trust_tier: string;visibility: string; claim_fp: string | null }>(`SELECT DISTINCT ON (subject_kind, subject_key) id, subject_kind, subject_key, event_type, value, value_hash, trust_tier, visibility, claim_fp- FROM belief_events WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND subject_kind NOT IN ('page','coverage')- AND id > COALESCE((SELECT max(id) FROM belief_events s WHERE s.source_id = $1 AND s.source_incarnation = $2::uuid AND s.slug = $3 AND s.subject_kind = 'page'+ FROM belief_events WHERE source_id = $1 AND source_incarnation = $2::uuid AND slug = $3 AND subject_kind NOT IN ('page','coverage') AND origin <> 'backfill'+ AND id > COALESCE((SELECT max(id) FROM belief_events s WHERE s.source_id = $1 AND s.source_incarnation = $2::uuid AND s.slug = $3 AND s.subject_kind = 'page' AND s.origin <> 'backfill'AND (s.event_type IN ('baseline','reconcile') OR (s.event_type = 'page.published' AND s.value->>'revision_before' IS NULL))), 0)ORDER BY subject_kind, subject_key, id DESC`, [sourceId, source.incarnation, slug]);const proven = new Map(recorded.filter(r => PROVEN_KINDS.test(r.event_type) && r.value_hash).map(r => [`${r.subject_kind}\u0000${r.subject_key}`, recordedVhash(r)]));@@ -292,30 +297,35 @@ export async function reconcileBeliefDrift(engine: BrainEngine, sourceId: stringreturn { scan, reconciled, events };}-/** Open lifetimes with no page at their slug (an untracked hard delete), and events naming a lifetime that does not exist. */-export async function orphanLifetimes(engine: BrainEngine, sourceId: string, limit = 20): Promise<{ count: number; samples: Array<{ slug: string; page_lifetime: string; reason: 'no_page' | 'no_lifetime' }> }> {+/** Open lifetimes with no page at their slug (an untracked hard delete), and (`deep`, a whole-ledger read) events naming a lifetime that does not exist. */+export async function orphanLifetimes(engine: BrainEngine, sourceId: string, limit = 20, opts: { deep?: boolean } = {}): Promise<{ count: number; samples: Array<{ slug: string; page_lifetime: string; reason: 'no_page' | 'no_lifetime' }> }> {const rows = await engine.executeRaw<{ slug: string; page_lifetime: string; reason: 'no_page' | 'no_lifetime'; total: number }>(`SELECT slug, page_lifetime, reason, count(*) OVER ()::int AS total FROM (SELECT l.slug, l.page_lifetime::text AS page_lifetime, 'no_page' AS reason FROM belief_page_lifetimes l JOIN sources s ON s.id = l.source_id AND s.incarnation = l.source_incarnationWHERE l.source_id = $1 AND l.ended_at IS NULL AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id = l.source_id AND p.slug = l.slug)UNION ALL SELECT DISTINCT e.slug, e.page_lifetime::text, 'no_lifetime' FROM belief_events e- WHERE e.source_id = $1 AND e.page_lifetime IS NOT NULL AND NOT EXISTS (SELECT 1 FROM belief_page_lifetimes l WHERE l.page_lifetime = e.page_lifetime)- ) o ORDER BY slug LIMIT ${Math.max(1, Math.floor(limit))}`, [sourceId]);+ WHERE $2::boolean AND e.source_id = $1 AND e.page_lifetime IS NOT NULL AND NOT EXISTS (SELECT 1 FROM belief_page_lifetimes l WHERE l.page_lifetime = e.page_lifetime)+ ) o ORDER BY slug LIMIT ${Math.max(1, Math.floor(limit))}`, [sourceId, opts.deep === true]);return { count: Number(rows[0]?.total ?? 0), samples: rows.map(r => ({ slug: r.slug, page_lifetime: r.page_lifetime, reason: r.reason })) };}-/** Committed publications of the source with no commit mark (a crash before the post-commit mark). */-export async function unmarkedPublications(engine: BrainEngine, sourceId: string, limit = 1000): Promise<string[]> {+/**+ * Committed publications of the source with no commit mark (a crash before the post-commit mark). The routine scan+ * (cycle, doctor, status) reads events recorded in the last UNMARKED_WINDOW_DAYS through the recorded_at index; `deep`+ * (`gbrain beliefs reconcile`, `doctor --tier deep`) reads the whole source.+ */+export async function unmarkedPublications(engine: BrainEngine, sourceId: string, limit = 1000, opts: { deep?: boolean } = {}): Promise<string[]> {const rows = await engine.executeRaw<{ publication_id: string }>(`SELECT DISTINCT e.publication_id::text AS publication_id FROM belief_events e- WHERE e.source_id = $1 AND NOT EXISTS (SELECT 1 FROM belief_commit_marks m WHERE m.publication_id = e.publication_id)- ORDER BY 1 LIMIT ${Math.max(1, Math.floor(limit))}`, [sourceId]);+ WHERE e.source_id = $1 AND ($2::boolean OR e.recorded_at > now() - make_interval(days => ${UNMARKED_WINDOW_DAYS}))+ AND NOT EXISTS (SELECT 1 FROM belief_commit_marks m WHERE m.publication_id = e.publication_id)+ ORDER BY 1 LIMIT ${Math.max(1, Math.floor(limit))}`, [sourceId, opts.deep === true]);return rows.map(r => r.publication_id);}/** Writes the missing commit marks (a reader that finds a committed event with no mark writes one, section 5.3). */-export async function fillCommitMarks(engine: BrainEngine, sourceId: string): Promise<number> {+export async function fillCommitMarks(engine: BrainEngine, sourceId: string, opts: { deep?: boolean } = {}): Promise<number> {let filled = 0;for (;;) {- const ids = await unmarkedPublications(engine, sourceId);+ const ids = await unmarkedPublications(engine, sourceId, 1000, opts);if (!ids.length) return filled;await markBeliefCommits(engine, ids);filled += ids.length;@@ -325,9 +335,9 @@ export async function fillCommitMarks(engine: BrainEngine, sourceId: string): Pr/** Sources with any coverage event in their current incarnation. */export async function coveredSources(engine: BrainEngine): Promise<string[]> {- const rows = await engine.executeRaw<{ source_id: string }>(`SELECT DISTINCT e.source_id FROM belief_events e JOIN sources s ON s.id = e.source_id AND s.incarnation = e.source_incarnation- WHERE e.subject_kind = 'coverage' ORDER BY 1`);- return rows.map(r => r.source_id);+ const rows = await engine.executeRaw<{ id: string }>(`SELECT s.id FROM sources s WHERE EXISTS (SELECT 1 FROM belief_events e+ WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $1 AND e.source_incarnation = s.incarnation) ORDER BY 1`, [COVERAGE_KEY]);+ return rows.map(r => r.id);}/** The cycle's extract phase: a sampled drift reconcile and commit-mark fill on each covered source (or the cycle's source); failures become details. */diff --git a/src/core/belief/coverage.ts b/src/core/belief/coverage.tsindex 7cad9f892c..7b2e2e82c4 100644--- a/src/core/belief/coverage.ts+++ b/src/core/belief/coverage.ts@@ -15,38 +15,54 @@ import { appendBeliefEvents, markBeliefCommits, type BeliefEventDraft } from './import { coverageActive, currentStateHash, readLedgerSource } from './ledger.ts';import { keyedSubjects, type Subject } from './subjects.ts';import { readManagedMode } from '../persistence/managed-mode.ts';+import { validateSlug } from '../utils.ts';-export interface CoverageRun { runId: string; resumed: boolean; pages: number; dbOnlySubjects: number; complete: boolean; certified: boolean }+export interface CoverageRun { runId: string; resumed: boolean; pages: number; complete: boolean; certified: boolean; unkeyable: string[] }const BASELINE_BATCH = 200;-/** The latest coverage event of the source's current incarnation. */-export async function latestCoverage(engine: BrainEngine, sourceId: string): Promise<{ type: string; run: string | null; recorded_at: string; id: number } | null> {+type Coverage = { type: string; run: string | null; recorded_at: string; id: number };++/** The coverage state of the source's current incarnation: its newest coverage event other than `coverage.restored` (a restore never starts or stops recording). */+export async function latestCoverage(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<Coverage | null> {const [row] = await engine.executeRaw<{ event_type: string; run: string | null; recorded_at: string; id: number }>(`SELECT e.event_type, e.cause->>'run' AS run, e.recorded_at, e.idFROM belief_events e JOIN sources s ON s.id = e.source_id AND s.incarnation = e.source_incarnation- WHERE e.source_id = $1 AND e.subject_kind = 'coverage' AND e.subject_key = $2 ORDER BY e.id DESC LIMIT 1`, [sourceId, COVERAGE_KEY]);+ WHERE e.source_id = $1 AND e.subject_kind = 'coverage' AND e.subject_key = $2 AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1`, [sourceId, COVERAGE_KEY]);return row ? { type: row.event_type, run: row.run, recorded_at: new Date(row.recorded_at).toISOString(), id: Number(row.id) } : null;}-async function appendCoverage(engine: BrainEngine, sourceId: string, eventType: string, cause: Record<string, unknown>): Promise<void> {+/**+ * Appends the coverage event `decide` picks from the state re-read under the source row FOR UPDATE (which every page-key+ * holder waits on), or nothing when it returns null. Returns that state and whether it appended.+ */+async function appendCoverage(engine: BrainEngine, sourceId: string,+ decide: (latest: Coverage | null, tx: BrainEngine) => Promise<{ eventType: string; cause: Record<string, unknown> } | null>): Promise<{ latest: Coverage | null; appended: Record<string, unknown> | null }> {const publicationId = randomUUID();- await engine.transaction(async tx => {- const source = await readLedgerSource(tx, sourceId);- if (!source) throw new Error(`source not found: ${sourceId}`);- await tx.executeRaw('SELECT id FROM sources WHERE id = $1 FOR UPDATE', [sourceId]);+ const out = await engine.transaction(async tx => {+ if (!(await tx.executeRaw('SELECT id FROM sources WHERE id = $1 FOR UPDATE', [sourceId])).length) throw new Error(`source not found: ${sourceId}`);+ const source = (await readLedgerSource(tx, sourceId))!;+ const latest = await latestCoverage(tx, sourceId);+ const next = await decide(latest, tx);+ if (!next) return { latest, appended: null };await appendBeliefEvents(tx, [{ sourceId, incarnation: source.incarnation, lifetime: null, slug: '', subjectKind: 'coverage', subjectKey: COVERAGE_KEY,- eventType, trustTier: 'unknown', tierBasis: 'unknown', visibility: 'world', value: null, stateHash: '', cause: { op: eventType, ...cause } }],+ eventType: next.eventType, trustTier: 'unknown', tierBasis: 'unknown', visibility: 'world', value: null, stateHash: '', cause: { op: next.eventType, ...next.cause } }],{ publicationId, origin: 'live', purgesPossible: false });+ return { latest, appended: next.cause };});- await markBeliefCommits(engine, [publicationId]);+ if (out.appended) await markBeliefCommits(engine, [publicationId]);+ return out;}-/** One page's baseline under its key, in the same form as a creation snapshot (or per subject when over 1 MiB). */-async function baselinePage(engine: BrainEngine, sourceId: string, slug: string, runId: string): Promise<boolean> {+/**+ * One page's baseline under its key, in the same form as a creation snapshot (or per subject when over 1 MiB).+ * 'baselined', 'nothing' (no state to baseline, already baselined, or recording stopped) or 'dropped' (drafts that appended nothing).+ */+async function baselinePage(engine: BrainEngine, sourceId: string, slug: string, runId: string): Promise<'baselined' | 'nothing' | 'dropped'> {const publicationId = randomUUID();const appended = await engine.transaction(async tx => {await tx.lockPageKeys([{ sourceId, slug }]);const source = await readLedgerSource(tx, sourceId);- if (!source || !coverageActive(source.coverage)) return 0;+ if (!source || !coverageActive(source.coverage)) return null;+ if (!await lacksBaseline(tx, sourceId, slug, runId)) return null;const { hash, state, lifetimes } = await currentStateHash(tx, sourceId, source.incarnation, slug);const page = state.pages.find(p => p.slug === slug);const subjects = keyedSubjects({ incarnation: source.incarnation, lifetimes, pagesBySlug: new Map(page ? [[slug, page]] : []) }, state,@@ -68,47 +84,73 @@ async function baselinePage(engine: BrainEngine, sourceId: string, slug: string,if (page.large) drafts.push(...perSubject(bound));}drafts.push(...perSubject(subjects.filter(s => s.dbOnly)));- return appendBeliefEvents(tx, drafts, { publicationId, origin: 'baseline', purgesPossible: source.purgesPossible });+ return drafts.length ? appendBeliefEvents(tx, drafts, { publicationId, origin: 'baseline', purgesPossible: source.purgesPossible }) : null;});if (appended) await markBeliefCommits(engine, [publicationId]);- return appended > 0;+ return appended === null ? 'nothing' : appended > 0 ? 'baselined' : 'dropped';}+const lacksBaseline = async (engine: BrainEngine, sourceId: string, slug: string, runId: string) => !(await engine.executeRaw(`SELECT 1 FROM belief_events+ WHERE source_id = $1 AND slug = $2 AND event_type = 'baseline' AND cause->>'run' = $3 LIMIT 1`, [sourceId, slug, runId])).length;+/** Slugs of the source still lacking a baseline in this run: live and soft-deleted pages, then page-less database-only fact subjects. */-async function pendingSlugs(engine: BrainEngine, sourceId: string, runId: string, after: string): Promise<string[]> {+async function pendingSlugs(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, runId: string, after: string, skip: readonly string[]): Promise<string[]> {const rows = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM (SELECT p.slug FROM pages p WHERE p.source_id = $1UNION SELECT f.entity_slug FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug IS NULL AND f.expired_at IS NULL AND f.entity_slug IS NOT NULLUNION SELECT f.source_markdown_slug FROM facts f WHERE f.source_id = $1 AND f.dimension IS NOT NULL AND f.row_num IS NULL AND f.expired_at IS NULL AND f.source_markdown_slug IS NOT NULL- ) s WHERE s.slug > $3 AND NOT EXISTS (SELECT 1 FROM belief_events e WHERE e.source_id = $1 AND e.slug = s.slug AND e.event_type = 'baseline' AND e.cause->>'run' = $2)- ORDER BY s.slug LIMIT ${BASELINE_BATCH}`, [sourceId, runId, after]);+ ) s WHERE s.slug > $3 AND NOT (s.slug = ANY($4::text[])) AND NOT EXISTS (SELECT 1 FROM belief_events e WHERE e.source_id = $1 AND e.slug = s.slug AND e.event_type = 'baseline' AND e.cause->>'run' = $2)+ ORDER BY s.slug LIMIT ${BASELINE_BATCH}`, [sourceId, runId, after, skip]);return rows.map(r => r.slug);}+/**+ * Starts (or resumes) the source's run and baselines every pending slug. Start, completion and stop are decided under+ * the source row FOR UPDATE: a second enable resumes the open run, a disable during the walk ends it without a+ * `coverage.complete`, and the completion re-checks the pending set (a page renamed onto a slug the cursor already+ * passed is baselined before the watermark). A slug no page key can name, or whose baseline appended nothing, is left+ * out and listed in the completion (`unkeyable_slugs`, `unbaselined_slugs`).+ */export async function enableBeliefLedger(engine: BrainEngine, sourceId: string): Promise<CoverageRun> {- const latest = await latestCoverage(engine, sourceId);- const resumed = latest?.type === 'coverage.started' && !!latest.run;- const runId = resumed ? latest!.run! : randomUUID();- if (latest?.type === 'coverage.complete' || latest?.type === 'coverage.restored') {- return { runId: latest.run ?? '', resumed: true, pages: 0, dbOnlySubjects: 0, complete: true, certified: await readManagedMode(engine) };- }- if (!resumed) await appendCoverage(engine, sourceId, 'coverage.started', { run: runId });+ const start = await appendCoverage(engine, sourceId, async latest =>+ latest?.type === 'coverage.started' || latest?.type === 'coverage.complete' ? null : { eventType: 'coverage.started', cause: { run: randomUUID() } });+ const certified = await readManagedMode(engine);+ if (start.latest?.type === 'coverage.complete') return { runId: start.latest.run ?? '', resumed: true, pages: 0, complete: true, certified, unkeyable: [] };+ const runId = start.appended ? String(start.appended.run) : start.latest!.run!;+ const unkeyable: string[] = [];+ const unbaselined: string[] = [];+ const attempted = new Set<string>();let pages = 0;- let after = '';- for (;;) {- const slugs = await pendingSlugs(engine, sourceId, runId, after);- if (!slugs.length) break;- for (const slug of slugs) if (await baselinePage(engine, sourceId, slug, runId)) pages++;- after = slugs[slugs.length - 1]!;+ for (let walk = 0; ; walk++) {+ const skip = () => walk ? [...unkeyable, ...attempted] : unkeyable;+ for (let after = '', slugs = await pendingSlugs(engine, sourceId, runId, after, skip()); slugs.length; slugs = await pendingSlugs(engine, sourceId, runId, after, skip())) {+ for (const slug of slugs) {+ try { validateSlug(slug); } catch { unkeyable.push(slug); continue; }+ attempted.add(slug);+ const outcome = await baselinePage(engine, sourceId, slug, runId);+ if (outcome === 'baselined') pages++;+ if (outcome === 'dropped') unbaselined.push(slug);+ }+ after = slugs[slugs.length - 1]!;+ const latest = await latestCoverage(engine, sourceId);+ if (latest?.type !== 'coverage.started' || latest.run !== runId) break;+ }+ const end = await appendCoverage(engine, sourceId, async (latest, tx) => {+ if (latest?.type !== 'coverage.started' || latest.run !== runId) return null;+ if ((await pendingSlugs(tx, sourceId, runId, '', [...unkeyable, ...attempted])).length) return null;+ const [done] = await tx.executeRaw<{ n: number }>(`SELECT count(DISTINCT slug)::int AS n FROM belief_events WHERE source_id = $1 AND event_type = 'baseline' AND cause->>'run' = $2`,+ [sourceId, runId]);+ return { eventType: 'coverage.complete', cause: { run: runId, certified, pages: Number(done?.n ?? 0), ...(unkeyable.length ? { unkeyable_slugs: unkeyable } : {}),+ ...(unbaselined.length ? { unbaselined_slugs: unbaselined } : {}) } };+ });+ const complete = !!end.appended || (end.latest?.type === 'coverage.complete' && end.latest.run === runId);+ if (complete || end.latest?.type !== 'coverage.started' || end.latest.run !== runId) {+ return { runId, resumed: !start.appended, pages, complete, certified: complete && certified, unkeyable };+ }}- const certified = await readManagedMode(engine);- await appendCoverage(engine, sourceId, 'coverage.complete', { run: runId, certified });- return { runId, resumed, pages, dbOnlySubjects: 0, complete: true, certified };}export async function disableBeliefLedger(engine: BrainEngine, sourceId: string): Promise<boolean> {- const latest = await latestCoverage(engine, sourceId);- if (!latest || latest.type === 'coverage.stopped') return false;- await appendCoverage(engine, sourceId, 'coverage.stopped', { run: latest.run });- return true;+ const out = await appendCoverage(engine, sourceId, async latest => !latest || latest.type === 'coverage.stopped' ? null : { eventType: 'coverage.stopped', cause: { run: latest.run } });+ return !!out.appended;}diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.tsindex 33da404c48..916f4ac770 100644--- a/src/core/belief/ledger.ts+++ b/src/core/belief/ledger.ts@@ -77,11 +77,11 @@ export function beliefBatchCovers(sourceId: string, slugs: readonly string[]): b/** True inside any belief batch: a nested writer's own publication commits with the enclosing transaction, not before it. */export const insideBeliefBatch = (): boolean => !!store.getStore();-/** Coverage and purge probes for one source, in one read. */+/** Coverage and purge probes for one source, in one read. `coverage` is the newest coverage event other than `coverage.restored`. */export async function readLedgerSource(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<{ incarnation: string; purgeEpoch: number; coverage: string | null; purgesPossible: boolean } | null> {const [row] = await tx.executeRaw<Record<string, unknown>>(`SELECT s.incarnation::text AS incarnation, s.purge_epoch,(SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2- AND e.source_incarnation = s.incarnation ORDER BY e.id DESC LIMIT 1) AS coverage,+ AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage,(s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id)OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purgesFROM sources s WHERE s.id = $1`, [sourceId, COVERAGE_KEY]);@@ -391,15 +391,25 @@ function contestedDraft(d: DiffContext, note: Extract<BeliefNote, { kind: 'conte}/** The current belief-set hash of one stream, for the doctor drift check and reconcile. */-export async function currentStateHash(tx: BrainEngine, sourceId: string, incarnation: string, slug: string): Promise<{ hash: string; state: RawState; lifetimes: Map<number, string> }> {+export async function currentStateHash(tx: BrainEngine, sourceId: string, incarnation: string, slug: string,+ opts: { readOnly?: boolean } = {}): Promise<{ hash: string; state: RawState; lifetimes: Map<number, string> }> {const state = await readBeliefState(tx, sourceId, [slug]);- const lifetimes = await resolveLifetimes(tx, pageNeeds(sourceId, incarnation, state));+ const lifetimes = opts.readOnly ? await peekLifetimes(tx, pageNeeds(sourceId, incarnation, state)) : await resolveLifetimes(tx, pageNeeds(sourceId, incarnation, state));const page = state.pages.find(p => p.slug === slug) ?? null;const ctx: KeyContext = { incarnation, lifetimes, pagesBySlug: new Map(page ? [[slug, page]] : []) };const subjects = keyedSubjects(ctx, state, id => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world').filter(s => s.stream === slug);return { hash: stateHashOf(page, page ? lifetimes.get(page.id)! : null, subjects), state, lifetimes };}+/** resolveLifetimes without writes (a read-only drift scan): a page with no fitting open lifetime gets a placeholder, so its hash cannot match a recorded one. */+async function peekLifetimes(tx: BrainEngine, needs: ReturnType<typeof pageNeeds>): Promise<Map<number, string>> {+ const open = await readOpenLifetimes(tx, needs);+ return new Map(needs.map(n => {+ const row = open.get(`${n.incarnation}\u0000${n.slug}`);+ return [n.pageId, row && (row.page_id == null || row.page_id === n.pageId) ? row.page_lifetime : `unminted:${n.pageId}`];+ }));+}+export { stateHashOf };/** The batch options of one journaled page publication (single or group member). */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c64a77d8d9..2e57542959 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -71,7 +71,7 @@ export const CODES = {budget_below_recent_runtime: { class: 'unavailable', summary: "The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend.", why: 'An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed.', docs: 'docs/guides/dream-patterns.md#budget-sizing', suggestion: 'Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`.' },backup_dump_failed: { class: 'host_only', summary: "`gbrain backup create` could not dump the PGLite data dir: an entry PGLite cannot read (a socket, FIFO or symlink that is not a dead gbrain socket) is still inside it.", why: "The backup removes only gbrain's own IPC sockets, and only when nothing listens on them; a live gbrain socket, a foreign socket or FIFO, or a symlink is left in place and named in the message, because the database lock proves no other PGLite owner, not who owns an arbitrary endpoint.", docs: 'docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database', suggestion: 'Stop the process that uses each named entry (or move the entry out of the data dir), then rerun the same `gbrain backup create` command. Do not delete an entry something is still listening on.', fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: "Read-only: reports the brain's lock holders and storage state so the user can see what still runs against the data dir.", requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } },belief_coverage_required: { class: 'caller', summary: "The belief ledger is not enabled on this source, so it has no coverage start to work from.", why: "The history backfill seeds events before the source's coverage start; with no coverage there is no cut to backfill before.", docs: 'docs/designs/BELIEF_LEDGER.md#72-the-marked-history-backfill', suggestion: 'Ask the user, then run `gbrain beliefs enable --source <id>` first.' },- belief_preparation_stale: { class: 'retryable', summary: "A purge ran in the source after a belief ledger payload was prepared, so the append was refused.", why: "A payload prepared outside its appending transaction records the source's purge epoch; appending it after a purge could write the purged text back into history.", docs: 'docs/designs/BELIEF_LEDGER.md#65-purge-removal-from-active-memory-never-a-physical-erasure-promise', suggestion: 'Run the same command again; it prepares the payload from the current, redacted state.' },+ belief_stale_preparation: { class: 'retryable', summary: "A purge ran in the source after a belief ledger payload was prepared, so the append was refused.", why: "A payload prepared outside its appending transaction records the source's purge epoch; appending it after a purge could write the purged text back into history.", docs: 'docs/designs/BELIEF_LEDGER.md#65-purge-removal-from-active-memory-never-a-physical-erasure-promise', suggestion: 'Run the same command again; it prepares the payload from the current, redacted state.' },benchmark_duplicate_task_id: { class: 'caller', summary: "Benchmark duplicate task id." },benchmark_empty: { class: 'caller', summary: "The benchmark file has no tasks." },benchmark_exists: { class: 'caller', summary: "A benchmark already exists at the target path." },diff --git a/test/belief-ledger-coverage.test.ts b/test/belief-ledger-coverage.test.tsindex 0e27b385e8..2db0f0bdc1 100644--- a/test/belief-ledger-coverage.test.ts+++ b/test/belief-ledger-coverage.test.ts@@ -9,13 +9,17 @@import { afterEach, describe, expect, test } from 'bun:test';import { rmSync } from 'node:fs';import { join } from 'node:path';-import { __setBeliefEmitterFaultForTests, appendBeliefEvents, markBeliefCommits, type BeliefEventDraft } from '../src/core/belief/append.ts';+import { __setBeliefEmitterFaultForTests, markBeliefCommits, type BeliefEventDraft } from '../src/core/belief/append.ts';import { currentStateHash, readLedgerSource, withBeliefBatch } from '../src/core/belief/ledger.ts';import { deleteSourceRow } from '../src/core/source-delete.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';-import { enableBeliefLedger, disableBeliefLedger } from '../src/core/belief/coverage.ts';+import { enableBeliefLedger, disableBeliefLedger, latestCoverage } from '../src/core/belief/coverage.ts';+import { renamePageOntoSlug } from '../src/commands/sync/rename-collision.ts';+import { runBeliefs } from '../src/commands/beliefs.ts';+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';+import { withEnv } from './helpers/with-env.ts';import {- beliefEventVisibility, coverageAt, coverageIntervals, fillCommitMarks, orphanLifetimes, reconcileBeliefDrift, scanBeliefDrift, unmarkedPublications,+ DRIFT_SAMPLE_PAGES, UNMARKED_WINDOW_DAYS, beliefEventVisibility, coverageAt, coverageIntervals, fillCommitMarks, orphanLifetimes, reconcileBeliefDrift, scanBeliefDrift, unmarkedPublications,} from '../src/core/belief/coverage-report.ts';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../src/core/engine.ts';@@ -35,7 +39,7 @@ import { backfillBeliefHistory } from '../src/core/belief/backfill.ts';import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';import type { DoctorContext } from '../src/commands/doctor/context.ts';import type { Check } from '../src/commands/doctor.ts';-import { COVERAGE_KEY } from '../src/core/belief/keys.ts';+import { replayPurgesInRestore, type PurgeMirrorLine } from '../src/core/belief/purge-mirror.ts';import { beliefBrain, beliefEngineCase, beliefPage, shape, type BeliefBrain } from './helpers/belief-ledger.ts';afterEach(() => { __setBeliefEmitterFaultForTests(null); });@@ -59,6 +63,23 @@ async function bypassLink(b: BeliefBrain, target: string) {WHERE a.source_id = $1 AND a.slug = 'companies/acme-example' AND p.source_id = $1 AND p.slug = $2`, [b.sourceId, target]);}+/** The engine with `before` run (on the real engine, outside any transaction) ahead of its `nth` top-level transaction. */+function interceptTransactions(engine: BrainEngine, nth: number, before: () => Promise<void>, opts: { after?: boolean } = {}): BrainEngine {+ let calls = 0;+ return new Proxy(engine, { get(target, prop, receiver) {+ if (prop === 'transaction') return async (fn: (tx: BrainEngine) => Promise<unknown>) => {+ calls++;+ if (calls === nth && !opts.after) await before();+ const result = await target.transaction(fn as never);+ if (calls === nth && opts.after) await before();+ return result;+ };+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+}+const lifetimeCount = async (b: BeliefBrain) => Number((await b.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM belief_page_lifetimes WHERE source_id = $1', [b.sourceId]))[0]!.n);+async function seeded(b: BeliefBrain) {await b.put('people/alice-example', beliefPage({ type: 'person', title: 'Alice Example' }));await b.put('companies/acme-example', page());@@ -285,6 +306,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {const baselines = (await b.events()).filter(e => e.event_type === 'baseline' && e.subject_kind === 'page');expect(baselines.map(e => e.slug)).not.toContain('companies/gamma-example');expect(await coverageAt(b.engine, b.sourceId, await dbNow(b), 'companies/gamma-example')).toMatchObject({ ok: false, code: 'coverage_from', from: null });+ expect((await b.events()).find(e => e.event_type === 'coverage.complete')!.cause).toMatchObject({ unbaselined_slugs: ['companies/gamma-example'] });}, { enable: false });}, 180_000);@@ -380,20 +402,24 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {__setBeliefEmitterFaultForTests(null);expect((await doctor(b, { doFix: true })).status).toBe('ok');const source = (await readLedgerSource(b.engine, b.sourceId))!;- const restore = async (purgeReplay: string) => {- const publicationId = randomUUID();- await b.engine.transaction(tx => appendBeliefEvents(tx, [{ sourceId: b.sourceId, incarnation: source.incarnation, lifetime: null, slug: '', subjectKind: 'coverage',- subjectKey: COVERAGE_KEY, eventType: 'coverage.restored', trustTier: 'unknown', tierBasis: 'unknown', visibility: 'world', value: null, stateHash: '',- cause: { op: 'coverage.restored', archive_created_at: '2026-10-01T00:00:00.000Z', purge_replay: purgeReplay, purge_requests: ['purge-1'] } }],- { publicationId, origin: 'live', purgesPossible: false }));- await markBeliefCommits(b.engine, [publicationId]);+ await pause();+ const archivedAt = await dbNow(b);+ await pause();+ const inGap = await dbNow(b);+ const restore = async (lines: PurgeMirrorLine[] | null) => {+ await b.engine.transaction(tx => replayPurgesInRestore(tx, { lines, archivedAt, restoreId: randomUUID() }));+ await fillCommitMarks(b.engine, b.sourceId);};- await restore('complete');+ await restore([]);expect((await doctor(b)).status).toBe('ok');- await restore('partial');+ expect(await coverageAt(b.engine, b.sourceId, inGap)).toMatchObject({ ok: false, code: 'coverage_gap', reason: 'restore', from: archivedAt });+ await restore([{ kind: 'intent', request: 'purge-1', request_id: 'req-purge-1', source_id: b.sourceId, source_incarnation: source.incarnation, scope: 'fact',+ recorded_at: new Date(Date.parse(archivedAt) + 1).toISOString(), purge_epoch: 1, facts: [], takes: [], lifetimes: [] }]);const asked = await doctor(b);expect(asked).toMatchObject({ status: 'warn', fix: { actor: 'user', ask_user: true } });- expect(asked.message).toContain('purge replay partial for purge-1');+ expect(asked.message).toContain(`(${archivedAt}): purge replay unverified for req-purge-1`);+ await restore(null);+ expect((await doctor(b)).message).toContain('purge replay unavailable');}, { enable: false });}, 180_000);@@ -460,15 +486,152 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect(new Set(events.map(e => e.publication_id)).size).toBe(4);expect((await backfillBeliefHistory(b.engine, b.sourceId)).events).toBe(0);expect(await b.lastId()).toBe(events.at(-1)!.id);- // Forced probe: a purge on every attempt exhausts the retries and refuses with belief_preparation_stale.+ // Forced probe: a purge on every attempt exhausts the retries and refuses with belief_stale_preparation.await b.put('companies/beta-example', beliefPage({ title: 'Beta Example', facts: ['Beta ships late'] }));await b.engine.executeRaw(`UPDATE pages SET created_at = $2::timestamptz - interval '1 hour' WHERE source_id = $1 AND slug = 'companies/beta-example'`, [b.sourceId, since]);await expect(backfillBeliefHistory(b.engine, b.sourceId, { slugs: ['companies/beta-example'], prepareHook: async () => {await b.engine.executeRaw('UPDATE sources SET purge_epoch = purge_epoch + 1 WHERE id = $1', [b.sourceId]);- } })).rejects.toMatchObject({ code: 'belief_preparation_stale' });+ } })).rejects.toMatchObject({ code: 'belief_stale_preparation' });}, { enable: false });}, 180_000);+ test('#7: a disable during enable ends the run without coverage.complete, and a restore never turns a stopped ledger back on', async () => {+ await brain(async b => {+ for (let i = 0; i < 5; i++) await b.put(`notes/n-${i}-example`, beliefPage({ type: 'note', title: `N ${i}`, facts: [`Fact number ${i} holds`] }));+ const run = await enableBeliefLedger(interceptTransactions(b.engine, 3, async () => { expect(await disableBeliefLedger(b.engine, b.sourceId)).toBe(true); }), b.sourceId);+ expect(run).toMatchObject({ complete: false, certified: false });+ expect((await latestCoverage(b.engine, b.sourceId))?.type).toBe('coverage.stopped');+ expect((await coverageIntervals(b.engine, b.sourceId)).map(i => [i.watermark, !!i.stopped_at, i.baseline.complete])).toEqual([[null, true, false]]);+ const quiet = await b.lastId();+ await b.put('notes/after-disable-example', beliefPage({ type: 'note', title: 'After', facts: ['Recorded after disable'] }));+ expect(await b.events(quiet)).toEqual([]);+ await b.engine.transaction(tx => replayPurgesInRestore(tx, { lines: [], archivedAt: new Date(Date.now() - 60_000).toISOString(), restoreId: randomUUID() }));+ expect((await readLedgerSource(b.engine, b.sourceId))!.coverage).toBe('coverage.stopped');+ const restored = await b.lastId();+ await b.put('notes/after-restore-example', beliefPage({ type: 'note', title: 'After restore', facts: ['Recorded after restore'] }));+ expect(await b.events(restored)).toEqual([]);+ const again = await enableBeliefLedger(b.engine, b.sourceId);+ expect(again).toMatchObject({ resumed: false, complete: true, pages: 7 });+ expect((await coverageIntervals(b.engine, b.sourceId)).map(i => [!!i.watermark, !!i.stopped_at])).toEqual([[false, true], [true, false]]);+ // A restore of an archive taken mid-baseline: the next enable resumes that run instead of returning at once.+ await disableBeliefLedger(b.engine, b.sourceId);+ fault(drafts => { if (drafts.some(d => d.eventType === 'baseline' && d.slug === 'notes/n-3-example')) throw new Error('interrupted'); return drafts; });+ await expect(enableBeliefLedger(b.engine, b.sourceId)).rejects.toThrow('interrupted');+ __setBeliefEmitterFaultForTests(null);+ await b.engine.transaction(tx => replayPurgesInRestore(tx, { lines: [], archivedAt: new Date(Date.now() - 60_000).toISOString(), restoreId: randomUUID() }));+ const resumed = await enableBeliefLedger(b.engine, b.sourceId);+ expect(resumed).toMatchObject({ resumed: true, complete: true });+ expect(resumed.pages).toBeGreaterThan(0);+ expect((await coverageIntervals(b.engine, b.sourceId)).at(-1)).toMatchObject({ stopped_at: null, baseline: { complete: true, pages_done: 7 } });+ }, { managed: false, enable: false });+ }, 180_000);++ test('#27 and #16: concurrent enables share one run; a page renamed onto a slug the cursor passed is baselined before the watermark', async () => {+ await brain(async b => {+ for (let i = 0; i < 12; i++) await b.put(`notes/m-${String(i).padStart(2, '0')}-example`, beliefPage({ type: 'note', title: `M ${i}`, facts: [`Other fact ${i} holds`] }));+ const runs = await Promise.all([enableBeliefLedger(b.engine, b.sourceId), enableBeliefLedger(b.engine, b.sourceId)]);+ expect(runs[0]!.runId).toBe(runs[1]!.runId);+ expect(runs.every(r => r.complete)).toBe(true);+ const intervals = await coverageIntervals(b.engine, b.sourceId);+ expect(intervals.map(i => [i.run, !!i.watermark, i.baseline.pages_done])).toEqual([[runs[0]!.runId, true, 12]]);+ const baselines = (await b.events()).filter(e => e.event_type === 'baseline' && e.subject_kind === 'page').map(e => e.slug);+ expect(baselines.length).toBe(new Set(baselines).size);+ }, { managed: false, enable: false });+ await brain(async b => {+ for (const slug of ['notes/a-example', 'notes/m-example', 'notes/z-example']) await b.put(slug, beliefPage({ type: 'note', title: slug, facts: [`${slug} claim one`] }));+ const run = await enableBeliefLedger(interceptTransactions(b.engine, 3, async () => {+ await renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'notes/z-example', newSlug: 'notes/b-example', to: 'notes/b-example.md' });+ }, { after: true }), b.sourceId);+ expect(run).toMatchObject({ complete: true });+ const baselined = (await b.events()).filter(e => e.event_type === 'baseline' && e.subject_kind === 'page').map(e => e.slug).sort();+ expect(baselined).toEqual(['notes/a-example', 'notes/b-example', 'notes/m-example']);+ const [interval] = await coverageIntervals(b.engine, b.sourceId);+ const baselineB = (await b.events()).find(e => e.event_type === 'baseline' && e.slug === 'notes/b-example')!;+ expect(Date.parse(baselineB.recorded_at)).toBeLessThanOrEqual(Date.parse(interval!.watermark!));+ }, { managed: false, enable: false });+ }, 180_000);++ test('#17: a slug no page key can name is left out of the baseline and listed, and enable completes instead of wedging', async () => {+ await brain(async b => {+ await b.put('notes/ok-example', beliefPage({ type: 'note', title: 'Ok', facts: ['Fine fact'] }));+ await b.engine.executeRaw(`INSERT INTO facts(source_id, entity_slug, fact, kind, visibility, source) VALUES ($1, $2, 'A db-only fact', 'fact', 'world', 'manual')`, [b.sourceId, 'people\\bad']);+ const run = await enableBeliefLedger(b.engine, b.sourceId);+ expect(run).toMatchObject({ complete: true, unkeyable: ['people\\bad'] });+ const complete = (await b.events()).find(e => e.event_type === 'coverage.complete')!;+ expect(complete.cause).toMatchObject({ unkeyable_slugs: ['people\\bad'], pages: 1 });+ expect(await enableBeliefLedger(b.engine, b.sourceId)).toMatchObject({ complete: true, resumed: true, pages: 0 });+ }, { managed: false, enable: false });+ }, 120_000);++ test('#15: a backfill does not read as drift, so neither the cycle nor doctor reconciles it', async () => {+ await brain(async b => {+ await b.put('companies/hist-example', beliefPage({ title: 'Hist Example', facts: ['Hist example sells widgets'] }));+ await b.put('companies/hist-example', beliefPage({ title: 'Hist Example', facts: ['Hist example sells widgets', 'Hist example has two staff'] }));+ await b.enable();+ expect((await backfillBeliefHistory(b.engine, b.sourceId)).events).toBeGreaterThan(0);+ expect((await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).drifted).toEqual([]);+ const mark = await b.lastId();+ expect((await reconcileBeliefDrift(b.engine, b.sourceId, { op: 'cycle_extract', limit: DRIFT_SAMPLE_PAGES })).events).toBe(0);+ expect(await b.lastId()).toBe(mark);+ expect((await coverageIntervals(b.engine, b.sourceId))[0]!.drift).toEqual([]);+ // A real change after the backfill still drifts and reconciles.+ await b.engine.executeRaw(`UPDATE facts SET confidence = 0.4 WHERE source_id = $1 AND fact = 'Hist example has two staff'`, [b.sourceId]);+ expect((await scanBeliefDrift(b.engine, b.sourceId, { deep: true })).drifted.map(d => d.slug)).toEqual(['companies/hist-example']);+ }, { managed: false, enable: false });+ }, 120_000);++ test('#24: a read-only doctor run mints and ends no page lifetime; --fix does', async () => {+ await brain(async b => {+ await seeded(b);+ await b.engine.putPage('notes/untracked-example', { type: 'note', title: 'Untracked', compiled_truth: 'Written outside every projection point.' }, { sourceId: b.sourceId });+ const before = await lifetimeCount(b);+ const report = await doctor(b);+ expect(report.status).toBe('warn');+ expect(report.message).toContain('notes/untracked-example');+ expect(await lifetimeCount(b)).toBe(before);+ // Forced probe: the --fix reconcile does mint the page's lifetime, so the count would have caught a read-only scan minting one.+ expect((await doctor(b, { doFix: true })).status).toBe('ok');+ expect(await lifetimeCount(b)).toBe(before + 1);+ }, { managed: false });+ }, 120_000);++ test('#41: a renamed page keeps its cut: coverageAt on the new slug answers from the baseline under its lifetime', async () => {+ await brain(async b => {+ await b.put('notes/old-example', beliefPage({ type: 'note', title: 'Old', facts: ['A renamed claim'] }));+ await b.enable();+ await pause();+ const between = await dbNow(b);+ await pause();+ await renamePageOntoSlug(b.engine, { sourceId: b.sourceId, oldSlug: 'notes/old-example', newSlug: 'notes/new-example', to: 'notes/new-example.md' });+ expect(await coverageAt(b.engine, b.sourceId, between, 'notes/new-example')).toMatchObject({ ok: true, certified: false, uncertified_reason: 'unmanaged' });+ expect(await coverageAt(b.engine, b.sourceId, between, 'notes/never-example')).toMatchObject({ ok: false, code: 'coverage_from' });+ }, { managed: false, enable: false });+ }, 120_000);++ test('#28: the routine unmarked-publication scan reads only the recent window; deep reads the whole source', async () => {+ await brain(async b => {+ await seeded(b);+ const [old] = await b.events();+ await b.engine.executeRaw('DELETE FROM belief_commit_marks WHERE publication_id = $1::uuid', [old!.publication_id]);+ await b.engine.executeRaw(`UPDATE belief_events SET recorded_at = recorded_at - make_interval(days => ${UNMARKED_WINDOW_DAYS + 1}) WHERE publication_id = $1::uuid`, [old!.publication_id]);+ expect(await unmarkedPublications(b.engine, b.sourceId)).toEqual([]);+ expect(await unmarkedPublications(b.engine, b.sourceId, 1000, { deep: true })).toEqual([old!.publication_id]);+ expect(await fillCommitMarks(b.engine, b.sourceId, { deep: true })).toBe(1);+ });+ }, 120_000);++ test('#37: gbrain beliefs resolves the source through the ambient chain, and a bare --source is refused', async () => {+ await brain(async b => {+ await withEnv({ GBRAIN_SOURCE: b.sourceId }, () => runBeliefs(b.engine, ['enable']));+ expect((await latestCoverage(b.engine, b.sourceId))?.type).toBe('coverage.complete');+ expect(await latestCoverage(b.engine, 'default')).toBeNull();+ await runBeliefs(b.engine, ['disable', '--source']);+ expect(currentExitCode()).toBe(2);+ setCliExitVerdict(0);+ expect((await latestCoverage(b.engine, b.sourceId))?.type).toBe('coverage.complete');+ }, { managed: false, enable: false });+ }, 120_000);+test('probe 9: graduation PGLite -> ' + engineCase.name + ' carries an identical ledger: equal event_key sets, digests and replay', async () => {await beliefBrain(async b => {await seeded(b);diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 533e9d4283..1fd61e81ec 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6322,7 +6322,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"cache_quota_exceeded\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"page_body_segmented\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",