Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W1 lane C: gbrain beliefs CLI (enable, disable, status, reconcile, backfill), page_versions backfill, error codes
garrytan771c436912d9
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex fe73682f63..6a40be7741 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -178,6 +178,26 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cMore: [docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database](../../docs/guides/in-agent-setup.md#6-back-up-the-complete-local-database)+### belief_coverage_required++<a id="belief_coverage_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The belief ledger is not enabled on this source, so it has no coverage start to work from. | The history backfill seeds events before the source's coverage start; with no coverage there is no cut to backfill before. | Ask the user, then run `gbrain beliefs enable --source <id>` first. | agent | `repeat the read that failed` | 1 | no |++More: [docs/designs/BELIEF_LEDGER.md#72-the-marked-history-backfill](../../docs/designs/BELIEF_LEDGER.md#72-the-marked-history-backfill)++### belief_preparation_stale++<a id="belief_preparation_stale"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A purge ran in the source after a belief ledger payload was prepared, so the append was refused. | 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. | Run the same command again; it prepares the payload from the current, redacted state. | agent | `repeat the read that failed` | 1 | yes |++More: [docs/designs/BELIEF_LEDGER.md#65-purge-removal-from-active-memory-never-a-physical-erasure-promise](../../docs/designs/BELIEF_LEDGER.md#65-purge-removal-from-active-memory-never-a-physical-erasure-promise)+### benchmark_duplicate_task_id<a id="benchmark_duplicate_task_id"></a>@@ -748,6 +768,26 @@ More: [docs/guides/core-memory.md#remote-edits](../../docs/guides/core-memory.md|---|---|---|---|---|---|---|| Cost preview requires yes. | The step needs the user's decision before it runs. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |+### coverage_from++<a id="coverage_from"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark. | Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty. | Ask about a time at or after the `from` time, or run `gbrain beliefs backfill --source <id>` for best-effort history before it. | agent | `repeat the read that failed` | 1 | no |++More: [docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark](../../docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark)++### coverage_gap++<a id="coverage_gap"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore. | The request itself was wrong or no longer matches the brain; nothing was changed. | Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps. | agent | `repeat the read that failed` | 1 | no |++More: [docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark](../../docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark)+### cursor_incarnation_retired<a id="cursor_incarnation_retired"></a>diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 21f8b004da..66f9ebf9cb 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -394,6 +394,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// selfHelp: #6259 router (list, clear, scan); its usage prints before any engine is opened.{ name: 'quarantine', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/quarantine.ts') },// #5575: memory trust. Observational startup: `trust backfill --dry-run` runs with no migrations and no writes.+ // W1 belief ledger coverage: enable, disable, status, reconcile, backfill (docs/designs/BELIEF_LEDGER.md section 7).+ { name: 'beliefs', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/beliefs.ts') },{ name: 'trust', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', skipStartupHooks: true, startup: 'observational', load: () => import('./commands/trust.ts') },// selfHelp: v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).// thin client: v0.43 (#2095): watch streams against a LOCAL engine; thin clients get thediff --git a/src/cli/commands/beliefs.ts b/src/cli/commands/beliefs.tsnew file mode 100644index 0000000000..e629cdfa8c--- /dev/null+++ b/src/cli/commands/beliefs.ts@@ -0,0 +1,10 @@+/**+ * `gbrain beliefs`: post-connect dispatch for the belief ledger's coverage+ * tooling; the behavior lives in src/commands/beliefs.ts.+ */+import type { BrainEngine } from '../../core/engine.ts';++export async function run(engine: BrainEngine, args: string[]): Promise<void> {+ const { runBeliefs } = await import('../../commands/beliefs.ts');+ await runBeliefs(engine, args);+}diff --git a/src/cli/top-help.ts b/src/cli/top-help.tsindex ef10921145..336cb11dc5 100644--- a/src/cli/top-help.ts+++ b/src/cli/top-help.ts@@ -110,6 +110,7 @@ TOOLSlint <dir|file> [--fix] Catch LLM artifacts, placeholder dates, bad frontmatterbackfill <kind|list> v0.30.1: run a registered backfill (effective-date, ...)orphans [--json] [--count] Find pages with no inbound wikilinks+ beliefs <enable|status|...> Belief ledger coverage: enable, disable, status, reconcile, backfillsalience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salienceanomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain ratediff --git a/src/commands/beliefs.ts b/src/commands/beliefs.tsnew file mode 100644index 0000000000..efbe2c0a0e--- /dev/null+++ b/src/commands/beliefs.ts@@ -0,0 +1,115 @@+/**+ * `gbrain beliefs`: the belief ledger's coverage (docs/designs/BELIEF_LEDGER.md+ * section 7). `enable` runs the resumable baseline and starts a coverage+ * interval; `disable` stops it; `status` prints each source's intervals,+ * watermark, certified status, baseline progress, restore gaps, drift marks+ * and unmarked publications; `reconcile` appends `reconcile` events for drifted+ * slugs and fills missing commit marks; `backfill` seeds best-effort history+ * before the coverage start from retained page versions.+ */+import type { BrainEngine } from '../core/engine.ts';+import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';+import { OperationError, opError } from '../core/ops/contract.ts';+import { writeCliError } from '../cli/cli-error.ts';+import { disableBeliefLedger, enableBeliefLedger } from '../core/belief/coverage.ts';+import { coverageIntervals, coveredSources, fillCommitMarks, orphanLifetimes, reconcileBeliefDrift, unmarkedPublications, type CoverageInterval } from '../core/belief/coverage-report.ts';+import { backfillBeliefHistory } from '../core/belief/backfill.ts';+import { readLedgerSource } from '../core/belief/ledger.ts';++export const BELIEFS_USAGE = [+ 'Usage: gbrain beliefs <enable|disable|status|reconcile|backfill> [--source <id>] [--json]',+ ' enable Start recording the belief ledger on a source: baselines every page (resumable) and sets the watermark.',+ ' Only a managed source\'s coverage is certified; an unmanaged source is recorded but uncertified.',+ ' disable Stop recording (appends coverage.stopped); enabling again starts a new interval with a new baseline.',+ ' status Coverage intervals per source: watermark, certified or uncertified, baseline progress, restore gaps, drift.',+ ' 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).',+].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 unknownSource = (sourceId: string) => opError('invalid_params', `Source ${sourceId} does not exist.`, 'Run gbrain sources list to see the source ids.');++async function sourceStatus(engine: BrainEngine, sourceId: string) {+ const source = await readLedgerSource(engine, sourceId);+ if (!source) throw unknownSource(sourceId);+ const intervals = await coverageIntervals(engine, sourceId);+ return { source_id: sourceId, managed: source.managed, active: source.coverage != null && source.coverage !== 'coverage.stopped', intervals,+ unmarked_publications: (await unmarkedPublications(engine, sourceId)).length, orphans: await orphanLifetimes(engine, sourceId, 5) };+}++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'}`);+ 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;+}++async function report(args: string[], value: unknown, text: string): Promise<void> {+ if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(value, null, 2)}\n`);+ else console.log(text);+}++export async function runBeliefs(engine: BrainEngine, args: string[]): Promise<void> {+ const [sub] = args;+ if (args.includes('--help') || args.includes('-h') || !sub) { console.log(BELIEFS_USAGE); return; }+ try {+ if (!(SUBCOMMANDS as readonly string[]).includes(sub)) {+ throw opError('invalid_params', `Unknown beliefs subcommand '${sub}'.`, 'gbrain beliefs --help lists enable, disable, status, reconcile and backfill.');+ }+ const named = sourceArg(args);+ if (named !== undefined && !await readLedgerSource(engine, named)) throw unknownSource(named);+ if (sub === 'enable') {+ const sourceId = named ?? 'default';+ 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)'}.`);+ return;+ }+ if (sub === 'disable') {+ const sourceId = named ?? 'default';+ 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 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)`+ + `${incomplete.length ? `; ${incomplete.length} page(s) incomplete (${[...new Set(incomplete.flatMap(p => p.reasons))].join(', ')})` : ''}.`);+ return;+ }+ const sources = named ? [named] : await coveredSources(engine);+ if (sub === 'status') {+ const statuses = [];+ for (const sourceId of sources) statuses.push(await sourceStatus(engine, sourceId));+ const text = statuses.length ? statuses.flatMap(s => [`${s.source_id} (${s.managed ? 'managed' : 'unmanaged'}, ${s.active ? 'recording' : 'not recording'})`,+ ...(s.intervals.length ? s.intervals.flatMap(renderInterval) : [' never enabled (gbrain beliefs enable --source ' + s.source_id + ')']),+ ...(s.unmarked_publications ? [` ${s.unmarked_publications} committed publication(s) without a commit mark (gbrain beliefs reconcile fills them)`] : []),+ ...(s.orphans.count ? [` ${s.orphans.count} orphan lifetime(s) (gbrain beliefs reconcile ends them)`] : [])]).join('\n')+ : 'The belief ledger is not enabled on any source. Enable it with gbrain beliefs enable --source <id>.';+ await report(args, { sources: statuses }, text);+ return;+ }+ const 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) });+ }+ 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.');+ } catch (error) {+ if (error instanceof OperationError) { setCliExitVerdict(writeCliError(error, 'beliefs', { json: jsonRequested(args) })); return; }+ throw error;+ }+}diff --git a/src/core/belief/backfill.ts b/src/core/belief/backfill.tsnew file mode 100644index 0000000000..0617898f26--- /dev/null+++ b/src/core/belief/backfill.ts@@ -0,0 +1,202 @@+/**+ * The marked history backfill (docs/designs/BELIEF_LEDGER.md section 7.2):+ * seeds history before a source's first coverage start from `page_versions`.+ * Git is not read (its history is outside purge's reach and would double this+ * pass; a later version can add it). Every row is `origin = 'backfill'`,+ * recorded at the run's time, with the historical time only in `source_time`,+ * and never certified.+ *+ * Per page, the retained version bodies before the coverage start are parsed+ * (facts and takes fences) and diffed in order; each version's transitions+ * are one publication (`page.published` plus the fact and take events), and+ * the last one closes on the body at the coverage start. A summary event+ * (`backfill`) carries `backfill_complete` and the reasons it is not.+ *+ * The payload is prepared outside the appending transaction and carries the+ * `purge_epoch` it read; the append runs under the page key, refuses when the+ * epoch moved (the page is prepared again from current, redacted versions),+ * and rechecks tombstones through `appendBeliefEvents`. Events of a key a+ * purge hid through derivation (`derived.hidden`) are appended hidden.+ * Publication ids are derived from the page lifetime and version, so a rerun+ * appends nothing twice.+ */+import type { BrainEngine } from '../engine.ts';+import { parseFactsFence } from '../facts-fence.ts';+import { parseTakesFence, TAKE_RESERVATION_SOURCE } from '../takes-fence.ts';+import { opError } from '../ops/contract.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { factKey, lifetimeRef, pageKey, sha256Hex, takeClaimHash, takeKey, valueHash } from './keys.ts';+import { appendBeliefEvents, markBeliefCommits, type BeliefEventDraft } from './append.ts';+import { readLedgerSource } from './ledger.ts';+import { resolveLifetimes } from './lifetimes.ts';+import { factValue, takeValue } from './subjects.ts';+import { coverageIntervals } from './coverage-report.ts';++export interface BackfillPageResult { slug: string; versions: number; events: number; complete: boolean; reasons: string[] }+export interface BackfillReport { source_id: string; since: string | null; pages: BackfillPageResult[]; events: number; retried: number }++interface Body { revision: string | null; source_time: string; text: string | null }+interface Keyed { kind: 'fact' | 'take'; key: string; value: Record<string, unknown>; vhash: string; visibility: string; claimFp: string; validFrom: string | null; validUntil: string | null }+interface Prepared { epoch: number; incarnation: string; lifetime: string; pageId: number; versions: Body[]; drafts: BeliefEventDraft[][]; summary: BeliefEventDraft; complete: boolean; reasons: string[] }++const MAX_EPOCH_RETRIES = 3;+const toUuid = (hex: string) => `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;+const iso = (v: unknown) => v == null ? null : new Date(v as string).toISOString();+const dateIso = (d?: string) => d ? iso(/^\d{4}-\d{2}-\d{2}$/.test(d) ? `${d}T00:00:00Z` : d) : null;++/** Keyed fence subjects of one body: active fence facts by (page, fp, visibility) and takes by (page, claim hash, ordinal). */+async function bodySubjects(engine: BrainEngine, lifetime: string, text: string, pageVisibility: string): Promise<{ subjects: Keyed[]; warnings: string[] }> {+ const facts = parseFactsFence(text);+ const takes = parseTakesFence(text);+ const active = facts.facts.filter(f => f.active);+ const fps = active.length ? await engine.executeRaw<{ fp: string }>('SELECT gbrain_fact_fingerprint(c) AS fp FROM unnest($1::text[]) WITH ORDINALITY AS t(c, n) ORDER BY n',+ [active.map(f => f.claim)]) : [];+ const subject = lifetimeRef(lifetime);+ const groups = new Map<string, { raw: Parameters<typeof factValue>[0]; count: number }>();+ for (const [i, f] of active.entries()) {+ const fp = fps[i]!.fp;+ const key = factKey(subject, fp, f.visibility);+ const existing = groups.get(key);+ if (existing) { existing.count++; continue; }+ groups.set(key, { count: 1, raw: { id: 0, entity_slug: null, sms: '', entity_page_id: null, fact: f.claim, fp, kind: f.kind, visibility: f.visibility,+ notability: f.notability, context: f.context ?? null, confidence: f.confidence, valid_from: dateIso(f.validFrom), valid_until: dateIso(f.validUntil),+ claim_metric: null, claim_value: null, claim_unit: null, claim_period: null, event_type: null, dimension: null, value: null, value_hash: null, row_num: f.rowNum, tier: '' } });+ }+ const subjects: Keyed[] = [...groups].map(([key, { raw, count }]) => {+ const value = factValue(raw, subject, count);+ return { kind: 'fact', key, value, vhash: valueHash(value), visibility: raw.visibility, claimFp: raw.fp, validFrom: raw.valid_from, validUntil: raw.valid_until };+ });+ const rows = takes.takes.filter(t => t.source !== TAKE_RESERVATION_SOURCE);+ const takeFps = rows.length ? await engine.executeRaw<{ fp: string }>('SELECT gbrain_fact_fingerprint(c) AS fp FROM unnest($1::text[]) WITH ORDINALITY AS t(c, n) ORDER BY n',+ [rows.map(t => t.claim)]) : [];+ const byClaim = new Map<string, Array<{ t: typeof rows[number]; fp: string }>>();+ rows.forEach((t, i) => { const h = takeClaimHash(t.claim, t.kind, t.holder); byClaim.set(h, [...byClaim.get(h) ?? [], { t, fp: takeFps[i]!.fp }]); });+ for (const [hash, group] of byClaim) {+ group.sort((a, b) => (a.t.sinceDate ?? '').localeCompare(b.t.sinceDate ?? '') || a.t.rowNum - b.t.rowNum);+ group.forEach(({ t, fp }, ordinal) => {+ const value = takeValue({ id: 0, page_id: 0, row_num: t.rowNum, claim: t.claim, claim_fp: fp, kind: t.kind, holder: t.holder, weight: t.weight,+ since_date: t.sinceDate ?? null, until_date: t.untilDate ?? null, source: t.source ?? null, active: t.active, resolved_at: dateIso(t.resolvedAt),+ resolved_outcome: t.resolvedOutcome ?? null, resolved_value: t.resolvedValue ?? null, resolved_unit: t.resolvedUnit ?? null,+ resolved_source: t.resolvedEvidence ?? null, resolved_by: t.resolvedBy ?? null, resolved_quality: t.resolvedQuality ?? null, tier: '' });+ subjects.push({ kind: 'take', key: takeKey(lifetime, hash, ordinal), value, vhash: valueHash(value), visibility: pageVisibility, claimFp: fp, validFrom: null, validUntil: null });+ });+ }+ return { subjects, warnings: [...facts.warnings, ...takes.warnings] };+}++/** 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> {+ 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,+ p.body_storage = 'segmented' AS large, p.compiled_truth, p.timeline, (${privatePagesFilterFragment('p')}) AS visible+ FROM pages p WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);+ if (!page) return null;+ const lifetime = (await resolveLifetimes(engine, [{ sourceId, incarnation: source.incarnation, slug, pageId: Number(page.id) }])).get(Number(page.id))!;+ const versions = await engine.executeRaw<{ id: number; snapshot_at: string; revision: string | null; compiled_truth: string | null; timeline: string | null; segmented: boolean }>(`SELECT v.id,+ v.snapshot_at, v.knowledge_revision::text AS revision, v.compiled_truth, v.timeline, v.body_storage = 'segmented' AS segmented+ FROM page_versions v WHERE v.page_id = $1 ORDER BY v.snapshot_at, v.id`, [page.id]);+ if (new Date(page.created_at).getTime() > Date.parse(since)) return null;+ const before = versions.filter(v => new Date(v.snapshot_at).getTime() <= Date.parse(since));+ const reasons: string[] = [];+ if (page.large || versions.some(v => v.segmented)) reasons.push('large_page_versions_pruned');+ const closing = versions.find(v => new Date(v.snapshot_at).getTime() > Date.parse(since));+ const text = (v: { segmented: boolean; compiled_truth: string | null; timeline: string | null }) => v.segmented || v.compiled_truth == null ? null : `${v.compiled_truth}\n${v.timeline ?? ''}`;+ const bodies: Body[] = before.map((v, i) => ({ revision: v.revision, source_time: i === 0 ? iso(page.created_at)! : iso(before[i - 1]!.snapshot_at)!, text: text(v) }));+ 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.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;+ const stateHash = sha256Hex(`backfill:${lifetime}`);+ const visibility = page.visible === true ? 'world' : 'private';+ const base = { sourceId, incarnation: source.incarnation, lifetime, slug, stream: slug, stateHash, tierBasis: 'unknown' as const, trustTier: 'unknown' };+ for (const [i, body] of chain.entries()) {+ if (body.text == null) { reasons.push('segmented_version_body'); priorRevision = body.revision; continue; }+ const { subjects, warnings } = await bodySubjects(engine, lifetime, body.text, visibility);+ if (warnings.length) reasons.push('fence_parse_warnings');+ const cause = { op: 'backfill', version: i < bodies.length ? Number(before[i]!.id) : closing ? Number(closing.id) : null, at_coverage_start: i === bodies.length };+ const out: BeliefEventDraft[] = [{ ...base, subjectKind: 'page', subjectKey: pageKey(lifetime), eventType: 'page.published', visibility,+ value: { revision_before: priorRevision, revision_after: body.revision, ...(i === 0 ? { snapshot: false } : {}) }, sourceTime: body.source_time, cause }];+ const priorMap = new Map(prior.map(s => [s.key, s]));+ const nowMap = new Map(subjects.map(s => [s.key, s]));+ const draft = (s: Keyed, eventType: string, value: Record<string, unknown> | null, priorHash: string | null) => out.push({ ...base, subjectKind: s.kind,+ subjectKey: s.key, eventType, visibility: s.visibility, value, priorHash, claimFp: s.claimFp, validFrom: s.validFrom, validUntil: s.validUntil,+ sourceTime: body.source_time, cause, ...(hidden.has(s.key) ? { purged: true } : {}) });+ for (const [key, s] of priorMap) if (!nowMap.has(key)) draft(s, `${s.kind}.retracted`, null, s.vhash);+ for (const [key, s] of nowMap) {+ const was = priorMap.get(key);+ if (!was) draft(s, `${s.kind}.asserted`, s.value, null);+ else if (was.vhash !== s.vhash) draft(s, `${s.kind}.revised`, s.value, was.vhash);+ }+ drafts.push(out);+ prior = subjects;+ priorRevision = body.revision;+ }+ const complete = reasons.length === 0;+ const summary: BeliefEventDraft = { ...base, subjectKind: 'page', subjectKey: pageKey(lifetime), eventType: 'backfill', visibility,+ value: { backfill_complete: complete, versions: before.length, reasons: [...new Set(reasons)].sort(), coverage_start: since }, sourceTime: bodies[0]?.source_time ?? null,+ cause: { op: 'backfill', purge_epoch: source.purgeEpoch } };+ 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. */+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 => {+ await tx.lockPageKeys([{ sourceId, slug }]);+ const 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.`,+ 'The backfill prepares the page again from the current, redacted versions; rerun gbrain beliefs backfill if it gave up.');+ }+ let n = 0;+ for (const [i, group] of [...prepared.drafts, [prepared.summary]].entries()) {+ const publicationId = toUuid(sha256Hex(`backfill\u0000${prepared.lifetime}\u0000${i === prepared.drafts.length ? 'summary' : i}`));+ const appended = await appendBeliefEvents(tx, group, { publicationId, origin: 'backfill', purgesPossible: source.purgesPossible });+ if (appended) publications.push(publicationId);+ n += appended;+ }+ return n;+ });+ return { events, publications };+}++/**+ * Backfills history before the source's first coverage start. Requires an+ * enabled source (the coverage start is the cut). `slugs` limits the pages;+ * `prepareHook` (tests) runs between preparation and append.+ */+export async function backfillBeliefHistory(engine: BrainEngine, sourceId: string,+ opts: { slugs?: string[]; prepareHook?: (slug: string, attempt: number) => Promise<void> } = {}): Promise<BackfillReport> {+ const [first] = await coverageIntervals(engine, sourceId);+ if (!first) {+ throw opError('belief_coverage_required', `The belief ledger is not enabled on source ${sourceId}, so there is no coverage start to backfill before.`,+ `Ask the user, then run gbrain beliefs enable --source ${sourceId} first.`);+ }+ const 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 };+ for (const slug of slugs) {+ for (let attempt = 0; ; attempt++) {+ const prepared = await preparePage(engine, sourceId, slug, since);+ if (!prepared) break;+ await opts.prepareHook?.(slug, attempt);+ try {+ const { events, publications } = await appendPrepared(engine, sourceId, slug, prepared);+ if (publications.length) await markBeliefCommits(engine, publications);+ report.pages.push({ slug, versions: prepared.versions.length, events, complete: prepared.complete, reasons: prepared.reasons });+ report.events += events;+ break;+ } catch (error) {+ if ((error as { code?: string }).code !== 'belief_preparation_stale' || attempt + 1 >= MAX_EPOCH_RETRIES) throw error;+ report.retried++;+ }+ }+ }+ return report;+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 3f4f5581c7..38667613c7 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -22,6 +22,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],+ 'beliefs': ['--brain', '--help', '--json', '--source'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],@@ -151,6 +152,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {'autopilot': ['--brain'],'backfill': ['--brain'],'backup': ['--brain'],+ 'beliefs': ['--brain', '--source'],'book-mirror': ['--brain'],'brainstorm': ['--brain'],'calibration': ['--brain', '--source'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 88603df695..342c09dcbd 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -64,6 +64,8 @@ export const CODES = {body_staging_expired: { class: 'retryable', summary: "The staged body of a large-page write expired before it was published, so nothing was published.", why: "A segmented write stages its segments first and publishes them in one flip; a staging idle past its deadline is collected by maintenance, and publishing without its segments would leave the page missing text.", suggestion: 'Send the same write again; it stages a fresh copy.' },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.' },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." },@@ -84,6 +86,8 @@ export const CODES = {bridge_ownership_conflict: { class: 'caller', summary: "The private local CLI registration is invalid." },bucket_not_found: { class: 'unavailable', summary: "The configured storage bucket does not exist." },budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },+ coverage_from: { class: 'caller', summary: "The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark.", why: "Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty.", docs: 'docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark', suggestion: 'Ask about a time at or after the `from` time, or run `gbrain beliefs backfill --source <id>` for best-effort history before it.' },+ coverage_gap: { class: 'caller', summary: "The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore.", docs: 'docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark', suggestion: 'Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps.' },cache_quota_exceeded: { class: 'caller', summary: "Retained shared-skill revisions reached this installation's local cache quota.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },capacity_paused: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'],