Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation G1: inventory, canonical digests and verify

garrytan329bbd0e82f1
diff --git a/src/core/persistence/engine-graduation.types.ts b/src/core/persistence/engine-graduation.types.ts
index bf90114460..d94e795418 100644
--- a/src/core/persistence/engine-graduation.types.ts
+++ b/src/core/persistence/engine-graduation.types.ts
@@ -84,6 +84,8 @@ export interface ColumnTransform {
column: string;
/** Human-readable rule, also printed by --plan (e.g. "cleared", "active -> waiting"). */
rule: string;
+ /** SQL expression over the source row's columns that yields the target value; the copier selects it and verify digests it. */
+ expression?: string;
}
export interface InventoryEntry {
@@ -94,9 +96,24 @@ export interface InventoryEntry {
lossKind: LossKind;
/** The only differences verify tolerates between source snapshot and target. */
transforms: readonly ColumnTransform[];
+ /** SQL predicate selecting the rows that belong to the copy; rows outside it stay engine-local on both sides (copy and digest). */
+ rowFilter?: string;
reason: string;
}
+/** One column as both the column contract and the canonical digest read it from the catalog. */
+export interface ColumnMeta {
+ name: string;
+ /** format_type(atttypid, atttypmod), e.g. 'vector(1024)', 'timestamp with time zone', 'text[]'. */
+ type: string;
+ /** pg_type.typcategory of the column type ('A' array, 'S' string, 'D' date/time, 'U' user-defined, ...). */
+ category: string;
+ /** The type has a collation, so ORDER BY and keyset predicates need COLLATE "C". */
+ collatable: boolean;
+ /** GENERATED ALWAYS ... STORED: never inserted, but digested. */
+ generated: boolean;
+}
+
export interface Inventory {
version: number;
entries: readonly InventoryEntry[];
@@ -226,7 +243,7 @@ export interface GraduationPlan {
export type ReplayProbeResult =
| { status: 'passed'; requestId: string }
- | { status: 'not_available'; reason: 'no_caller_input' | 'archived_source' | 'revoked_principal' | 'no_uncompacted_request' }
+ | { status: 'not_available'; reason: 'no_caller_input' | 'archived_source' | 'revoked_principal' | 'no_uncompacted_request' | 'source_changed' }
| { status: 'failed'; requestId: string; detail: string };
export interface VerifyFailure {
diff --git a/src/core/persistence/graduation-digest.ts b/src/core/persistence/graduation-digest.ts
new file mode 100644
index 0000000000..6089c645d0
--- /dev/null
+++ b/src/core/persistence/graduation-digest.ts
@@ -0,0 +1,179 @@
+/**
+ * Canonical, engine-independent table digests for engine graduation. Every
+ * value is read as text under fixed session settings, ordered by primary key
+ * with COLLATE "C", read in keyset batches and hashed client-side (sha256 per
+ * batch plus a root over every row, independent of batch size), so identical
+ * content on PGLite and on a Postgres database with another collation gives
+ * identical digests.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import type { BatchDigest, ColumnMeta, InventoryEntry, TableReceipt } from './engine-graduation.types.ts';
+
+export const DEFAULT_DIGEST_BATCH_ROWS = 1000;
+
+export const DIGEST_SESSION_SETTINGS = "SELECT set_config('TimeZone','UTC',true), set_config('DateStyle','ISO',true), "
+ + "set_config('extra_float_digits','3',true), set_config('bytea_output','hex',true), set_config('IntervalStyle','postgres',true)";
+
+/** Always-quoted identifier; names come from the catalog. Equivalent to format('%I') for every name. */
+export function quoteIdent(name: string): string {
+ return `"${name.replace(/"/g, '""')}"`;
+}
+
+const TIMESTAMP_TZ = 'timestamp with time zone';
+const ISO_TS = /^(\d{4,})-(\d\d)-(\d\d)[ T](\d\d):(\d\d):(\d\d)(?:\.(\d+))?(Z|[+-]\d\d(?::?\d\d)?)?( BC)?$/;
+
+function isoTimestamp(text: string): string {
+ const m = ISO_TS.exec(text);
+ if (!m) return text;
+ const [, y, mo, d, h, mi, s, frac = '', zone = 'Z', bc = ''] = m;
+ if (zone !== 'Z' && !/^[+-]00(?::?00)?$/.test(zone)) {
+ const parsed = new Date(text.replace(' ', 'T'));
+ return Number.isNaN(parsed.getTime()) ? text : isoTimestamp(parsed.toISOString());
+ }
+ const fraction = frac.replace(/0+$/, '');
+ return `${y}-${mo}-${d}T${h}:${mi}:${s}${fraction ? `.${fraction}` : ''}Z${bc}`;
+}
+
+function jsonbKeyOrder(a: string, b: string): number {
+ const la = Buffer.byteLength(a), lb = Buffer.byteLength(b);
+ return la !== lb ? la - lb : Buffer.compare(Buffer.from(a), Buffer.from(b));
+}
+
+/** jsonb's own text output for a parsed value: keys by byte length then bytes, ", " and ": " separators. */
+export function jsonbText(value: unknown): string {
+ if (value === null || value === undefined) return 'null';
+ if (Array.isArray(value)) return `[${value.map(jsonbText).join(', ')}]`;
+ if (typeof value === 'object') {
+ const obj = value as Record<string, unknown>;
+ return `{${Object.keys(obj).sort(jsonbKeyOrder).map(k => `${JSON.stringify(k)}: ${jsonbText(obj[k])}`).join(', ')}}`;
+ }
+ return typeof value === 'bigint' ? String(value) : JSON.stringify(value);
+}
+
+function arrayElement(value: unknown): string {
+ if (value === null || value === undefined) return 'NULL';
+ const text = value instanceof Date ? isoTimestamp(value.toISOString()) : String(value);
+ return text === '' || /^null$/i.test(text) || /[{}",\\\s]/.test(text) ? `"${text.replace(/[\\"]/g, c => `\\${c}`)}"` : text;
+}
+
+function canonicalValue(value: unknown, column: ColumnMeta): string | null {
+ if (value === null || value === undefined) return null;
+ if (typeof value === 'string') return column.type === TIMESTAMP_TZ ? isoTimestamp(value) : value;
+ if (value instanceof Date) return isoTimestamp(value.toISOString());
+ if (value instanceof Uint8Array) return `\\x${Buffer.from(value).toString('hex')}`;
+ if (typeof value === 'boolean') return value ? 't' : 'f';
+ if (typeof value === 'number' || typeof value === 'bigint') return String(value);
+ if (column.type === 'jsonb' || column.type === 'json') return jsonbText(value);
+ if (Array.isArray(value)) return `{${value.map(arrayElement).join(',')}}`;
+ return jsonbText(value);
+}
+
+/** One row as canonical text: a JSON array of each column's canonical rendering, in the given column order. */
+export function canonicalRowText(row: Record<string, unknown>, columns: readonly ColumnMeta[]): string {
+ return JSON.stringify(columns.map(c => canonicalValue(row[c.name], c)));
+}
+
+const COLUMN_META_SQL = `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, t.typcategory::text AS category,
+ (t.typcollation <> 0) AS collatable, (a.attgenerated::text = 's') AS generated
+ FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_type t ON t.oid=a.atttypid
+ WHERE n.nspname=current_schema() AND c.relname=$1 AND a.attnum>0 AND NOT a.attisdropped`;
+
+function toMeta(r: { name: string; type: string; category: string; collatable: unknown; generated: unknown }): ColumnMeta {
+ return { name: r.name, type: r.type, category: r.category, collatable: r.collatable === true || r.collatable === 't', generated: r.generated === true || r.generated === 't' };
+}
+
+/** Every column of the relation, sorted by name (C order), so physical column order never changes a digest. */
+export async function tableColumns(engine: BrainEngine, relation: string): Promise<readonly ColumnMeta[]> {
+ const rows = await engine.executeRaw<Parameters<typeof toMeta>[0]>(`${COLUMN_META_SQL} ORDER BY a.attname COLLATE "C"`, [relation]);
+ return rows.map(toMeta);
+}
+
+/** Primary-key columns in index order; graduation requires one on every copied table. */
+export async function primaryKey(engine: BrainEngine, relation: string): Promise<readonly ColumnMeta[]> {
+ const rows = await engine.executeRaw<Parameters<typeof toMeta>[0]>(`${COLUMN_META_SQL}
+ AND a.attnum = ANY((SELECT i.indkey::int2[] FROM pg_index i WHERE i.indrelid=c.oid AND i.indisprimary))
+ ORDER BY array_position((SELECT i.indkey::int2[] FROM pg_index i WHERE i.indrelid=c.oid AND i.indisprimary), a.attnum)`, [relation]);
+ if (!rows.length) throw new Error(`Table ${relation} has no primary key; graduation digests and copies need one.`);
+ return rows.map(toMeta);
+}
+
+export interface DigestPlan {
+ relation: string;
+ columns: readonly ColumnMeta[];
+ key: readonly ColumnMeta[];
+ /** SELECT list and FROM; `filter` is the inventory row filter (empty when none). */
+ select: string;
+ filter: string;
+}
+
+/** The ordered, keyset-paged SELECT shared by digests and verify's first-difference search. */
+export async function digestPlan(engine: BrainEngine, entry: InventoryEntry, applyTransforms: boolean): Promise<DigestPlan> {
+ const [columns, key] = await Promise.all([tableColumns(engine, entry.relation), primaryKey(engine, entry.relation)]);
+ const transforms = new Map(applyTransforms ? entry.transforms.map(t => {
+ if (!t.expression) throw new Error(`Transform on ${entry.relation}.${t.column} has no SQL expression.`);
+ return [t.column, t.expression] as const;
+ }) : []);
+ for (const column of transforms.keys()) {
+ if (!columns.some(c => c.name === column)) throw new Error(`Transform names ${entry.relation}.${column}, which does not exist.`);
+ if (key.some(k => k.name === column)) throw new Error(`Transform on primary-key column ${entry.relation}.${column} is not permitted.`);
+ }
+ const keyCols = key.map((k, i) => `${quoteIdent(k.name)}::text AS ${quoteIdent(`k${i}`)}`);
+ const valueCols = columns.map((c, i) => `(${transforms.get(c.name) ?? quoteIdent(c.name)})::text AS ${quoteIdent(`c${i}`)}`);
+ return { relation: entry.relation, columns, key, select: `SELECT ${[...keyCols, ...valueCols].join(', ')} FROM ${quoteIdent(entry.relation)}`, filter: entry.rowFilter ?? '' };
+}
+
+export interface DigestRow { key: readonly string[]; text: string }
+
+const collate = (c: ColumnMeta, expr: string) => c.collatable ? `${expr} COLLATE "C"` : expr;
+
+/** Up to `limit` rows strictly after `afterKey` (raw key texts), in COLLATE "C" primary-key order. Run inside a digest transaction. */
+export async function readDigestRows(tx: BrainEngine, plan: DigestPlan, afterKey: readonly string[] | null, limit: number): Promise<DigestRow[]> {
+ const order = plan.key.map(k => collate(k, quoteIdent(k.name))).join(', ');
+ const where = [
+ plan.filter ? `(${plan.filter})` : '',
+ afterKey ? `(${order}) > (${plan.key.map((k, i) => collate(k, `$${i + 1}::${k.type}`)).join(', ')})` : '',
+ ].filter(Boolean);
+ const rows = await tx.executeRaw<Record<string, string | null>>(
+ `${plan.select}${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY ${order} LIMIT ${Math.max(1, Math.floor(limit))}`, afterKey ? [...afterKey] : []);
+ return rows.map(r => {
+ const values: Record<string, unknown> = {};
+ plan.columns.forEach((c, i) => { values[c.name] = r[`c${i}`]; });
+ return { key: plan.key.map((_, i) => r[`k${i}`] as string), text: canonicalRowText(values, plan.columns) };
+ });
+}
+
+/** Runs fn inside one transaction with the fixed digest session settings. */
+export async function withDigestSession<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ return engine.transaction(async tx => {
+ await tx.executeRaw(DIGEST_SESSION_SETTINGS);
+ return fn(tx);
+ });
+}
+
+export function digestHeader(plan: DigestPlan): string {
+ return `${JSON.stringify(plan.columns.map(c => c.name))}\n`;
+}
+
+export async function digestTable(engine: BrainEngine, entry: InventoryEntry,
+ opts: { batchRows?: number; applyTransforms?: boolean } = {}): Promise<TableReceipt> {
+ const batchRows = opts.batchRows ?? DEFAULT_DIGEST_BATCH_ROWS;
+ const plan = await digestPlan(engine, entry, opts.applyTransforms === true);
+ return withDigestSession(engine, async tx => {
+ const root = createHash('sha256').update(digestHeader(plan));
+ const batches: BatchDigest[] = [];
+ let after: readonly string[] | null = null;
+ let total = 0;
+ for (;;) {
+ const rows = await readDigestRows(tx, plan, after, batchRows);
+ if (!rows.length) break;
+ const batch = createHash('sha256');
+ for (const row of rows) { batch.update(`${row.text}\n`); root.update(`${row.text}\n`); }
+ after = rows[rows.length - 1]!.key;
+ total += rows.length;
+ batches.push({ lastKey: JSON.stringify(after), rows: rows.length, sha256: batch.digest('hex') });
+ if (rows.length < batchRows) break;
+ }
+ return { relation: entry.relation, rows: total, rootSha256: root.digest('hex'), batches };
+ });
+}
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
new file mode 100644
index 0000000000..8b25be1152
--- /dev/null
+++ b/src/core/persistence/graduation-inventory.ts
@@ -0,0 +1,277 @@
+/**
+ * Engine graduation state inventory: every relation of the public schema on
+ * either engine maps to exactly one class (deny by default). The relation set,
+ * the copy order and the FK closure are read from the live catalog, never
+ * hand-maintained; test/graduation-inventory.test.ts fails when a migration
+ * adds a relation without a row here.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+import type { RegistryCode } from '../error-registry.ts';
+import { LATEST_VERSION } from '../migrate.ts';
+import type { ColumnTransform, Inventory, InventoryClass, InventoryEntry, LossKind } from './engine-graduation.types.ts';
+
+type EngineKind = 'pglite' | 'postgres';
+
+const BOTH = { pglite: true, postgres: true } as const;
+
+function entry(relation: string, cls: InventoryClass, lossKind: LossKind, reason: string,
+ extra: { kind?: 'table' | 'view'; engines?: { pglite: boolean; postgres: boolean }; transforms?: ColumnTransform[]; rowFilter?: string } = {}): InventoryEntry {
+ return {
+ relation, kind: extra.kind ?? 'table', class: cls, engines: extra.engines ?? BOTH, lossKind,
+ transforms: extra.transforms ?? [], ...(extra.rowFilter ? { rowFilter: extra.rowFilter } : {}), reason,
+ };
+}
+const carry = (relation: string, lossKind: LossKind, reason: string, extra?: Parameters<typeof entry>[4]) => entry(relation, 'carry', lossKind, reason, extra);
+
+const ACTIVE_JOB = "status = 'active'";
+const ORPHAN_EFFECT = "state IN ('queued','running','failed')";
+
+export const GRADUATION_INVENTORY: Inventory = {
+ version: 1,
+ entries: [
+ carry('access_tokens', 'security', 'Legacy bearer tokens and their unified grant columns; token hashes keep authorizing on the target.'),
+ carry('budget_ledger', 'operational', 'Daily resolver spend totals; admission keeps counting today\'s spend.'),
+ carry('calibration_profiles', 'user_data', 'Published calibration profiles per holder.'),
+ carry('chat_usage_log', 'operational', 'Chat model usage and cost log.'),
+ carry('chronicle_judge_reservations', 'operational', 'Rolling 24-hour paid judge-call counter; dropping it would reopen the daily cap.'),
+ carry('chronicle_page_state', 'user_data', 'Chronicle extraction ledger: paid work already done per page revision.'),
+ carry('code_edges_chunk', 'user_data', 'Code graph edges between chunks (keyed by chunk id, which carries).'),
+ carry('code_edges_symbol', 'user_data', 'Code graph edges to unresolved symbols.'),
+ carry('config', 'user_data', 'Brain settings, including the embedding column registry; the engine name and schema version stay each engine\'s own.',
+ { rowFilter: "key NOT IN ('engine','version')" }),
+ carry('content_chunks', 'user_data', 'Chunks with embeddings (paid work), vectors carried as text at the source typmod.'),
+ carry('context_volunteer_events', 'operational', 'Push-context telemetry.'),
+ carry('conversation_parser_llm_cache', 'operational', 'Paid LLM parse cache; rebuilding spends money.'),
+ carry('decide_calibrations', 'user_data', 'System One slot qualifications (paid calibration results).'),
+ carry('decide_proposals', 'user_data', 'Supersession proposals and the user\'s decisions on them.'),
+ carry('decide_spend', 'operational', 'System One spend log.'),
+ carry('decide_state', 'operational', 'System One sweep cursors and slot state.'),
+ carry('decide_sweep_deferred', 'operational', 'Deferred System One sweep work with its schedule.'),
+ carry('decision_receipts', 'user_data', 'Durable System One decision receipts.'),
+ carry('dream_synthesis_completions', 'user_data', 'Dream synthesis idempotency ledger.'),
+ carry('dream_verdicts', 'operational', 'Paid dream triage verdict cache.'),
+ carry('drift_decisions', 'user_data', 'Take drift decisions and when they were applied.'),
+ carry('entity_identities', 'user_data', 'Established entity identities.'),
+ carry('eval_candidates', 'operational', 'Captured retrieval eval candidates.'),
+ carry('eval_capture_failures', 'operational', 'Eval capture failure log.'),
+ carry('eval_contradictions_cache', 'operational', 'Paid contradiction judge cache; rebuilding spends money.'),
+ carry('eval_contradictions_runs', 'operational', 'Contradiction eval run history.'),
+ carry('eval_takes_quality_runs', 'operational', 'Takes quality eval run history.'),
+ carry('extract_atoms_page_state', 'user_data', 'Atom extraction ledger per page.'),
+ carry('extract_atoms_transcript_state', 'user_data', 'Atom extraction ledger per transcript file.'),
+ carry('extract_rollup_7d', 'operational', 'Seven-day extraction rollup counters.'),
+ carry('fact_relink_attempts', 'operational', 'Fact relink attempt log.'),
+ carry('fact_withdrawals', 'user_data', 'Fact withdrawal ledger (forget); must never be lost.'),
+ carry('facts', 'user_data', 'Facts with attribution columns and the superseded_by self-FK.'),
+ carry('files', 'user_data', 'File metadata; object bytes stay in the storage backend.'),
+ carry('ingest_log', 'operational', 'Ingestion log.'),
+ carry('links', 'user_data', 'Page graph links.'),
+ carry('loop_suppressions', 'user_data', 'Open-loop mutes the user chose.'),
+ carry('mcp_request_log', 'operational', 'MCP request log.'),
+ carry('mcp_spend_log', 'operational', 'MCP spend log.'),
+ carry('mcp_spend_reservations', 'operational', 'Pending and unresolved MCP charges; admission counts them and late settlement needs them.'),
+ carry('migration_impact_log', 'operational', 'Remediation impact log.'),
+ carry('minion_attachments', 'operational', 'Job attachments.'),
+ carry('minion_budget_log', 'operational', 'Job budget events.'),
+ carry('minion_inbox', 'operational', 'Job inbox messages.'),
+ carry('minion_jobs', 'operational', 'Job queue; orphaned leases reset under the kernel lock so the target worker runs each job once.', {
+ transforms: [
+ { column: 'status', rule: "active -> waiting", expression: `CASE WHEN ${ACTIVE_JOB} THEN 'waiting' ELSE status END` },
+ { column: 'lock_token', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE lock_token END` },
+ { column: 'lock_until', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE lock_until END` },
+ { column: 'timeout_at', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE timeout_at END` },
+ { column: 'started_at', rule: 'cleared on active jobs', expression: `CASE WHEN ${ACTIVE_JOB} THEN NULL ELSE started_at END` },
+ ],
+ }),
+ carry('minion_lease_pressure_log', 'operational', 'Lease pressure log.'),
+ carry('minion_self_fix_log', 'operational', 'Self-fix log.'),
+ carry('oauth_clients', 'security', 'OAuth clients and their grants; client secrets stay valid.'),
+ carry('oauth_grant_audit', 'security', 'OAuth grant change audit trail.'),
+ carry('oauth_tokens', 'security', 'Issued OAuth access and refresh token hashes.'),
+ carry('op_checkpoint_paths', 'operational', 'Resumable operation checkpoints.'),
+ carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),
+ carry('open_loops', 'user_data', 'Open loops and their status.'),
+ carry('page_aliases', 'user_data', 'Page aliases.'),
+ carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),
+ carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),
+ carry('page_versions', 'user_data', 'Page revision history with attribution.'),
+ carry('page_write_guards', 'user_data', 'Page write guards per source incarnation and slug.'),
+ carry('pages', 'user_data', 'Pages with ids, knowledge_revision, revision attribution and timestamps.'),
+ carry('persistence_counters', 'operational', 'Request admission counters; carried and recomputable from the carried requests.'),
+ carry('persistence_effects', 'operational', 'Postcommit outbox; orphaned claims reset so the target worker can claim them, delayed effects keep next_attempt_at.', {
+ transforms: [
+ { column: 'state', rule: 'running -> queued', expression: "CASE WHEN state = 'running' THEN 'queued' ELSE state END" },
+ { column: 'execution_token', rule: 'cleared on queued, running and failed effects', expression: `CASE WHEN ${ORPHAN_EFFECT} THEN NULL ELSE execution_token END` },
+ { column: 'claim_expires_at', rule: 'cleared on queued, running and failed effects', expression: `CASE WHEN ${ORPHAN_EFFECT} THEN NULL ELSE claim_expires_at END` },
+ ],
+ }),
+ carry('persistence_local_writers', 'security', 'Local writer credentials (cli/stdio) and revocations.'),
+ carry('persistence_requests', 'user_data', 'Write requests: idempotency records and outcomes, so replays return the stored outcome.'),
+ carry('persistence_source_bindings', 'user_data', 'Source to worktree bindings.'),
+ carry('persistence_topology_changes', 'user_data', 'Topology change journal.'),
+ carry('persistence_worktree_refreshes', 'user_data', 'Worktree refresh journal.'),
+ carry('persistence_worktrees', 'user_data', 'Managed worktrees; heartbeats reset.', {
+ transforms: [{ column: 'heartbeat_at', rule: 'cleared', expression: 'NULL' }],
+ }),
+ carry('persistence_writer_protocols', 'operational', 'Writer protocol registrations per worktree owner.'),
+ carry('raw_data', 'user_data', 'Raw source payloads per page.'),
+ carry('search_telemetry', 'operational', 'Search telemetry rollups.'),
+ carry('session_context_state', 'operational', 'Ambient recall session state.'),
+ carry('shared_skill_delivery_batches', 'operational', 'Shared-skill delivery batches and acknowledgments.'),
+ carry('shared_skill_heads', 'user_data', 'Shared-skill heads.'),
+ carry('shared_skill_members', 'user_data', 'Shared-skill installations.'),
+ carry('shared_skill_packs', 'user_data', 'Shared-skill packs.'),
+ carry('shared_skill_policies', 'user_data', 'Shared-skill policies.'),
+ carry('shared_skill_policy_audit', 'user_data', 'Shared-skill policy audit trail.'),
+ carry('shared_skill_revision_leases', 'user_data', 'User pins and delivery retention promises with their expiries (not process leases).'),
+ carry('shared_skill_revisions', 'user_data', 'Shared-skill revisions; stored_bytes is generated and never inserted.'),
+ carry('shared_skill_state', 'security', 'Shared-skill serving epoch and delivery token secret.'),
+ carry('slug_aliases', 'user_data', 'Slug aliases.'),
+ carry('source_ingestion_receipts', 'user_data', 'Source ingestion receipts.'),
+ carry('sources', 'user_data', 'Sources with incarnations and archive state.'),
+ carry('subagent_messages', 'operational', 'Subagent job transcripts.'),
+ carry('subagent_tool_executions', 'operational', 'Subagent tool execution log.'),
+ carry('synthesis_evidence', 'user_data', 'Synthesis citations.'),
+ carry('tags', 'user_data', 'Page tags.'),
+ carry('take_domain_assignments', 'user_data', 'Take domain assignments.'),
+ carry('take_grade_cache', 'operational', 'Paid take grading cache; rebuilding spends money.'),
+ carry('take_nudge_log', 'operational', 'Take nudge log.'),
+ carry('take_proposals', 'user_data', 'Take proposals and their status.'),
+ carry('takes', 'user_data', 'Takes with attribution and supersession.'),
+ carry('think_ab_results', 'operational', 'Think A/B eval results.'),
+ carry('timeline_entries', 'user_data', 'Timeline entries with attribution.'),
+
+ entry('persistence_brain', 'rebind', 'user_data', 'Brain identity and flags carry (brain_id keeps every identity file valid); enabled is set on the target only at cutover.', {
+ transforms: [{ column: 'enabled', rule: 'false until cutover', expression: 'false' }],
+ }),
+ entry('persistence_host_bindings', 'rebind', 'user_data', 'Host bindings carry only when host_id is this host and local_path passes the physical-root check.'),
+
+ entry('query_cache', 'rebuild', 'operational', 'Query result cache; regenerated on the target.'),
+ entry('code_traversal_cache', 'rebuild', 'operational', 'Code traversal cache; regenerated on the target.'),
+
+ entry('planner_stats_deltas', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),
+ entry('planner_stats_state', 'discard', 'operational', 'PGLite-only planner accounting.', { engines: { pglite: true, postgres: false } }),
+ entry('gbrain_cycle_locks', 'discard', 'operational', 'TTL run locks; every row is an orphan under the kernel lock.'),
+ entry('budget_reservations', 'discard', 'operational', 'No runtime reader or writer; only migrations reference it.'),
+ entry('subagent_rate_leases', 'discard', 'operational', 'Job-owned concurrency leases that expire.'),
+ entry('oauth_codes', 'discard', 'security', 'One-time authorization codes; an in-flight OAuth handshake restarts.'),
+
+ entry('page_links', 'schema_owned', 'operational', 'View over links; each engine\'s schema defines it.', { kind: 'view' }),
+ entry('file_migration_ledger', 'schema_owned', 'operational', 'Postgres-only file storage migration ledger written by the target initSchema.', { engines: { pglite: false, postgres: true } }),
+ ],
+};
+
+export function expectedRelations(engine: EngineKind, inv: Inventory = GRADUATION_INVENTORY): readonly string[] {
+ return inv.entries.filter(e => e.engines[engine]).map(e => e.relation).sort();
+}
+
+/** Tables, partitioned tables, views, materialized views and foreign tables in the current schema. */
+export async function listRelations(engine: BrainEngine): Promise<readonly { relation: string; kind: 'table' | 'view' }[]> {
+ const rows = await engine.executeRaw<{ relname: string; relkind: string }>(`SELECT c.relname, c.relkind::text AS relkind FROM pg_class c
+ JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND c.relkind IN ('r','p','v','m','f') AND NOT c.relispartition
+ ORDER BY c.relname COLLATE "C"`);
+ return rows.map(r => ({ relation: r.relname, kind: r.relkind === 'v' || r.relkind === 'm' ? 'view' : 'table' }));
+}
+
+async function schemaVersion(engine: BrainEngine): Promise<number | null> {
+ try {
+ const [row] = await engine.executeRaw<{ value: string }>("SELECT value FROM config WHERE key='version'");
+ return row ? Number(row.value) : null;
+ } catch { return null; }
+}
+
+/** Throws graduation_unclassified_table when the live relation set differs from the inventory for this engine. */
+export async function assertRelationSet(engine: BrainEngine, kind: EngineKind, inv: Inventory = GRADUATION_INVENTORY): Promise<void> {
+ const live = await listRelations(engine);
+ const expected = new Map(inv.entries.filter(e => e.engines[kind]).map(e => [e.relation, e]));
+ const liveNames = new Set(live.map(r => r.relation));
+ const unclassified = live.filter(r => !expected.has(r.relation)).map(r => r.relation);
+ const missing = [...expected.keys()].filter(name => !liveNames.has(name)).sort();
+ const wrongKind = live.filter(r => expected.has(r.relation) && expected.get(r.relation)!.kind !== r.kind).map(r => r.relation);
+ if (!unclassified.length && !missing.length && !wrongKind.length) return;
+ const version = await schemaVersion(engine);
+ const newer = version !== null && version > LATEST_VERSION;
+ const parts = [
+ unclassified.length ? `unclassified: ${unclassified.join(', ')}` : '',
+ missing.length ? `missing: ${missing.join(', ')}` : '',
+ wrongKind.length ? `wrong kind: ${wrongKind.join(', ')}` : '',
+ ].filter(Boolean).join('; ');
+ const verify = { argv: ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--url-env', 'GBRAIN_TARGET_URL', '--json'] };
+ throw opError('graduation_unclassified_table' as RegistryCode,
+ `The ${kind} schema does not match this gbrain's graduation inventory (${parts}).`,
+ newer
+ ? `The ${kind} brain is at schema v${version}, newer than this gbrain (v${LATEST_VERSION}). Ask the user to upgrade gbrain on this machine (gbrain upgrade), then plan the move again. --force never bypasses this.`
+ : 'A relation this gbrain\'s own migrations create has no graduation inventory row, so nothing was copied. Report this as a gbrain bug with the relation names; --force never bypasses this.',
+ {
+ why: newer
+ ? 'Graduation copies only relations it knows how to classify; a newer schema may hold state this binary would silently drop.'
+ : 'Every relation must be classified carry, rebind, rebuild, discard or schema-owned before a copy, so no state is lost by omission.',
+ fix: newer
+ ? { argv: ['gbrain', 'upgrade'], consent: [], actor: 'user', why: 'A newer gbrain knows the newer schema\'s relations.', requires_exclusive: false,
+ user_message: 'This brain was written by a newer gbrain. Please run `gbrain upgrade` on this machine, then I can plan the move again.', verify }
+ : { consent: [], actor: 'agent', why: 'An inventory row is missing in this gbrain release; a maintainer must add it.', requires_exclusive: false, verify },
+ reason: newer ? 'newer_schema' : 'missing_inventory_row',
+ });
+}
+
+interface ForeignKey { name: string; child: string; parent: string; childColumns: string[]; parentColumns: string[] }
+
+/** Every FK constraint in the current schema, read from pg_constraint. */
+export async function foreignKeys(engine: BrainEngine): Promise<readonly ForeignKey[]> {
+ const rows = await engine.executeRaw<{ name: string; child: string; parent: string; child_cols: string; parent_cols: string }>(`SELECT c.conname AS name,
+ ch.relname AS child, pa.relname AS parent,
+ (SELECT json_agg(a.attname ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY k(n,ord) JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=k.n)::text AS child_cols,
+ (SELECT json_agg(a.attname ORDER BY k.ord) FROM unnest(c.confkey) WITH ORDINALITY k(n,ord) JOIN pg_attribute a ON a.attrelid=c.confrelid AND a.attnum=k.n)::text AS parent_cols
+ FROM pg_constraint c JOIN pg_class ch ON ch.oid=c.conrelid JOIN pg_class pa ON pa.oid=c.confrelid
+ JOIN pg_namespace n ON n.oid=c.connamespace
+ WHERE c.contype='f' AND n.nspname=current_schema()
+ ORDER BY ch.relname COLLATE "C", c.conname COLLATE "C"`);
+ return rows.map(r => ({ name: r.name, child: r.child, parent: r.parent, childColumns: JSON.parse(r.child_cols), parentColumns: JSON.parse(r.parent_cols) }));
+}
+
+/** Kahn's algorithm over parent -> child edges (self-FKs ignored), ties broken by name; throws on a cycle. */
+export function topologicalOrder(nodes: readonly string[], edges: readonly { parent: string; child: string }[]): string[] {
+ const set = new Set(nodes);
+ const indegree = new Map(nodes.map(n => [n, 0]));
+ const children = new Map<string, Set<string>>(nodes.map(n => [n, new Set()]));
+ for (const { parent, child } of edges) {
+ if (parent === child || !set.has(parent) || !set.has(child) || children.get(parent)!.has(child)) continue;
+ children.get(parent)!.add(child);
+ indegree.set(child, indegree.get(child)! + 1);
+ }
+ const ready = nodes.filter(n => indegree.get(n) === 0).sort();
+ const order: string[] = [];
+ while (ready.length) {
+ const next = ready.shift()!;
+ order.push(next);
+ for (const child of children.get(next)!) {
+ indegree.set(child, indegree.get(child)! - 1);
+ if (indegree.get(child) === 0) { ready.push(child); ready.sort(); }
+ }
+ }
+ if (order.length !== nodes.length) {
+ const cyclic = nodes.filter(n => !order.includes(n)).sort();
+ throw new Error(`Foreign-key cycle among ${cyclic.join(', ')}: graduation needs an acyclic FK graph apart from self-references.`);
+ }
+ return order;
+}
+
+/** Carry and rebind entries present on this engine, parents before children. */
+export async function copyOrder(engine: BrainEngine, inv: Inventory = GRADUATION_INVENTORY): Promise<readonly InventoryEntry[]> {
+ const live = new Set((await listRelations(engine)).map(r => r.relation));
+ const copied = inv.entries.filter(e => (e.class === 'carry' || e.class === 'rebind') && live.has(e.relation));
+ const byName = new Map(copied.map(e => [e.relation, e]));
+ return topologicalOrder([...byName.keys()], await foreignKeys(engine)).map(name => byName.get(name)!);
+}
+
+/** The relation and every table that references it transitively, in topological order (the re-copy closure). */
+export async function fkClosure(engine: BrainEngine, relation: string): Promise<readonly string[]> {
+ const fks = await foreignKeys(engine);
+ const closure = new Set([relation]);
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const fk of fks) if (closure.has(fk.parent) && !closure.has(fk.child)) { closure.add(fk.child); grew = true; }
+ }
+ return topologicalOrder([...closure], fks);
+}
diff --git a/src/core/persistence/graduation-verify.ts b/src/core/persistence/graduation-verify.ts
new file mode 100644
index 0000000000..ca9f895953
--- /dev/null
+++ b/src/core/persistence/graduation-verify.ts
@@ -0,0 +1,316 @@
+/**
+ * Graduation verify: the gate for cutover. With both engines open and the
+ * target still fenced it compares relation sets, column contracts, row counts
+ * and canonical digests (source side transformed by the inventory's permitted
+ * transforms), sequence positions, every FK, trigger state, the target doctor
+ * and a replay probe that resubmits a carried request through admission
+ * inside a rolled-back transaction.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { admitWriteInTransaction, type WriteAdmission } from './journal.ts';
+import type { Principal, WriteAuthority } from './model.ts';
+import type {
+ GraduationEngines, Inventory, InventoryEntry, ReplayProbeResult, TableReceipt, VerifyFailure, VerifyResult,
+} from './engine-graduation.types.ts';
+import { assertRelationSet, copyOrder, foreignKeys } from './graduation-inventory.ts';
+import {
+ DEFAULT_DIGEST_BATCH_ROWS, digestPlan, digestTable, quoteIdent, readDigestRows, tableColumns, withDigestSession,
+} from './graduation-digest.ts';
+
+export const GRADUATION_FENCE_TRIGGER = 'gbrain_graduation_fence';
+/** Derived side tables the copy must reproduce exactly (they are carried, so the digest covers them). */
+export const DERIVED_SIDE_TABLES = ['page_projection_jobs', 'page_generation_clock'] as const;
+
+export interface VerifyContext {
+ inventory: Inventory;
+ /** Copy-time source snapshot: digestTable(source, entry, { applyTransforms: true }) per carried relation. */
+ sourceReceipts: readonly TableReceipt[];
+ replayRequestId?: string;
+ /** The original caller input of the replay request (persistence_requests stores only the normalized intent). */
+ replayCallerIntent?: Record<string, unknown>;
+ /** The graduation run id; the replay probe sets gbrain.graduation_run to it so the target fence admits its rolled-back writes. */
+ runId?: string;
+ /** Verify runs before cutover, so the gbrain_graduation_fence triggers must be present and ENABLE ALWAYS (default true). */
+ expectFence?: boolean;
+ batchRows?: number;
+ runDoctor: () => Promise<readonly string[]>;
+}
+
+function message(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+async function firstDifference(e: GraduationEngines, entry: InventoryEntry, source: TableReceipt, target: TableReceipt, batchRows: number)
+ : Promise<{ firstKey?: string; column?: string }> {
+ let index = source.batches.findIndex((b, i) => b.sha256 !== target.batches[i]?.sha256 || b.lastKey !== target.batches[i]?.lastKey);
+ if (index < 0) index = source.batches.length;
+ const after = index > 0 ? JSON.parse(source.batches[index - 1]!.lastKey) as string[] : null;
+ const limit = Math.max(batchRows, source.batches[index]?.rows ?? 0, target.batches[index]?.rows ?? 0);
+ const [srcPlan, dstPlan] = await Promise.all([digestPlan(e.source, entry, true), digestPlan(e.target, entry, false)]);
+ const [srcRows, dstRows] = await Promise.all([
+ withDigestSession(e.source, tx => readDigestRows(tx, srcPlan, after, limit)),
+ withDigestSession(e.target, tx => readDigestRows(tx, dstPlan, after, limit)),
+ ]);
+ for (let i = 0; i < Math.max(srcRows.length, dstRows.length); i++) {
+ const s = srcRows[i], d = dstRows[i];
+ if (s && d && s.text === d.text && JSON.stringify(s.key) === JSON.stringify(d.key)) continue;
+ if (!s || !d || JSON.stringify(s.key) !== JSON.stringify(d.key)) return { firstKey: JSON.stringify((s ?? d)!.key) };
+ const sv = JSON.parse(s.text) as unknown[], dv = JSON.parse(d.text) as unknown[];
+ const col = srcPlan.columns.findIndex((_, j) => sv[j] !== dv[j]);
+ return { firstKey: JSON.stringify(s.key), ...(col >= 0 ? { column: srcPlan.columns[col]!.name } : {}) };
+ }
+ return {};
+}
+
+async function verifyTable(e: GraduationEngines, entry: InventoryEntry, recorded: TableReceipt | undefined, batchRows: number,
+ failures: VerifyFailure[]): Promise<TableReceipt | null> {
+ const relation = entry.relation;
+ const [srcCols, dstCols] = await Promise.all([tableColumns(e.source, relation), tableColumns(e.target, relation)]);
+ const dstByName = new Map(dstCols.map(c => [c.name, c]));
+ const contract = [
+ ...srcCols.filter(c => !dstByName.has(c.name)).map(c => ({ column: c.name, detail: `missing on the target (${c.type})` })),
+ ...dstCols.filter(c => !srcCols.some(s => s.name === c.name)).map(c => ({ column: c.name, detail: `exists only on the target (${c.type})` })),
+ ...srcCols.filter(c => dstByName.has(c.name) && (dstByName.get(c.name)!.type !== c.type || dstByName.get(c.name)!.generated !== c.generated))
+ .map(c => ({ column: c.name, detail: `source ${c.type}${c.generated ? ' generated' : ''}, target ${dstByName.get(c.name)!.type}${dstByName.get(c.name)!.generated ? ' generated' : ''}` })),
+ ];
+ if (contract.length) {
+ for (const c of contract) failures.push({ relation, kind: 'digest', column: c.column, detail: `Column contract: ${c.column} ${c.detail}.` });
+ return null;
+ }
+ const [source, target] = await Promise.all([
+ digestTable(e.source, entry, { batchRows, applyTransforms: true }),
+ digestTable(e.target, entry, { batchRows }),
+ ]);
+ if (!recorded) failures.push({ relation, kind: 'digest', detail: 'No copy-time source receipt was recorded for this table.' });
+ else if (recorded.rootSha256 !== source.rootSha256 || recorded.rows !== source.rows) {
+ failures.push({ relation, kind: 'digest', detail: `The source changed since the copy (rows ${recorded.rows} -> ${source.rows}); re-copy this table and its FK closure.` });
+ }
+ if (source.rows !== target.rows) failures.push({ relation, kind: 'count', detail: `Source has ${source.rows} rows, target has ${target.rows}.` });
+ if (source.rootSha256 !== target.rootSha256) {
+ const diff = await firstDifference(e, entry, source, target, batchRows);
+ failures.push({ relation, kind: 'digest', ...diff, detail: `Canonical content differs${diff.firstKey ? ` first at key ${diff.firstKey}` : ''}${diff.column ? ` in column ${diff.column}` : ''}.` });
+ }
+ return target;
+}
+
+interface SequenceRow { seq: string; tbl: string | null; col: string | null }
+
+async function sequences(engine: BrainEngine): Promise<Map<string, SequenceRow>> {
+ const rows = await engine.executeRaw<SequenceRow>(`SELECT s.relname AS seq, t.relname AS tbl, a.attname AS col
+ FROM pg_class s JOIN pg_namespace n ON n.oid=s.relnamespace
+ LEFT JOIN pg_depend d ON d.objid=s.oid AND d.classid='pg_class'::regclass AND d.refclassid='pg_class'::regclass AND d.deptype IN ('a','i')
+ LEFT JOIN pg_class t ON t.oid=d.refobjid
+ LEFT JOIN pg_attribute a ON a.attrelid=t.oid AND a.attnum=d.refobjsubid
+ WHERE s.relkind='S' AND n.nspname=current_schema() ORDER BY s.relname COLLATE "C"`);
+ return new Map(rows.map(r => [r.seq, r]));
+}
+
+/** The highest value the sequence has handed out (or would hand out first, minus one). */
+async function sequencePosition(engine: BrainEngine, seq: string): Promise<bigint> {
+ const [row] = await engine.executeRaw<{ last_value: string; is_called: unknown }>(`SELECT last_value::text AS last_value, is_called FROM ${quoteIdent(seq)}`);
+ const called = row!.is_called === true || row!.is_called === 't';
+ return BigInt(row!.last_value) - (called ? 0n : 1n);
+}
+
+async function verifySequences(e: GraduationEngines, inventory: Inventory, failures: VerifyFailure[]): Promise<void> {
+ const copied = new Set(inventory.entries.filter(x => x.class === 'carry' || x.class === 'rebind').map(x => x.relation));
+ const [src, dst] = await Promise.all([sequences(e.source), sequences(e.target)]);
+ for (const [name, row] of src) {
+ if (row.tbl !== null && !copied.has(row.tbl)) continue;
+ if (!dst.has(name)) { failures.push({ relation: name, kind: 'sequence', detail: 'Sequence is missing on the target.' }); continue; }
+ const [sp, tp] = await Promise.all([sequencePosition(e.source, name), sequencePosition(e.target, name)]);
+ if (tp < sp) failures.push({ relation: name, kind: 'sequence', detail: `Target position ${tp} is below the source position ${sp}.` });
+ if (row.tbl && row.col) {
+ const [max] = await e.target.executeRaw<{ m: string | null }>(`SELECT max(${quoteIdent(row.col)})::text AS m FROM ${quoteIdent(row.tbl)}`);
+ if (max?.m != null && tp < BigInt(max.m)) failures.push({ relation: name, kind: 'sequence', detail: `Target position ${tp} is below ${row.tbl}.${row.col} maximum ${max.m}.` });
+ }
+ }
+}
+
+async function verifyForeignKeys(target: BrainEngine, failures: VerifyFailure[]): Promise<void> {
+ for (const fk of await foreignKeys(target)) {
+ const notNull = fk.childColumns.map(c => `c.${quoteIdent(c)} IS NOT NULL`).join(' AND ');
+ const match = fk.childColumns.map((c, i) => `p.${quoteIdent(fk.parentColumns[i]!)} = c.${quoteIdent(c)}`).join(' AND ');
+ const rows = await target.executeRaw<Record<string, string>>(`SELECT ${fk.childColumns.map((c, i) => `c.${quoteIdent(c)}::text AS ${quoteIdent(`v${i}`)}`).join(', ')}
+ FROM ${quoteIdent(fk.child)} c WHERE ${notNull} AND NOT EXISTS (SELECT 1 FROM ${quoteIdent(fk.parent)} p WHERE ${match}) LIMIT 1`);
+ if (rows.length) {
+ const key = JSON.stringify(fk.childColumns.map((_, i) => rows[0]![`v${i}`]));
+ failures.push({ relation: fk.child, kind: 'fk', firstKey: key, column: fk.childColumns.join(','),
+ detail: `${fk.name}: ${fk.child}(${fk.childColumns.join(',')}) = ${key} has no row in ${fk.parent}.` });
+ }
+ }
+}
+
+async function verifyTriggers(target: BrainEngine, inventory: Inventory, expectFence: boolean, failures: VerifyFailure[]): Promise<void> {
+ const rows = await target.executeRaw<{ rel: string; name: string; enabled: string; internal: unknown }>(`SELECT c.relname AS rel, t.tgname AS name,
+ t.tgenabled::text AS enabled, t.tgisinternal AS internal
+ FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace
+ WHERE n.nspname=current_schema() ORDER BY c.relname COLLATE "C", t.tgname COLLATE "C"`);
+ const fenced = new Set<string>();
+ for (const t of rows) {
+ if (t.name === GRADUATION_FENCE_TRIGGER) {
+ if (!expectFence) failures.push({ relation: t.rel, kind: 'trigger', detail: `${t.name} is still installed after cutover.` });
+ else if (t.enabled !== 'A') failures.push({ relation: t.rel, kind: 'trigger', detail: `${t.name} is '${t.enabled}', expected ENABLE ALWAYS ('A').` });
+ else fenced.add(t.rel);
+ continue;
+ }
+ if (t.enabled !== 'O') failures.push({ relation: t.rel, kind: 'trigger', detail: `Trigger ${t.name} is '${t.enabled}', expected enabled ('O').` });
+ }
+ if (!expectFence) return;
+ const live = new Set(rows.map(r => r.rel));
+ const tables = new Set((await target.executeRaw<{ relname: string }>(`SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
+ WHERE n.nspname=current_schema() AND c.relkind IN ('r','p')`)).map(r => r.relname));
+ for (const entry of inventory.entries) {
+ if ((entry.class === 'carry' || entry.class === 'rebind') && entry.engines.postgres && tables.has(entry.relation) && !fenced.has(entry.relation)) {
+ failures.push({ relation: entry.relation, kind: 'trigger', detail: `${GRADUATION_FENCE_TRIGGER} is missing${live.has(entry.relation) ? '' : ' (no triggers at all)'}; the target is not fenced.` });
+ }
+ }
+}
+
+interface StoredRequest {
+ id: string; principal_kind: Principal['kind']; principal_id: string; request_id: string; operation: string; source_id: string;
+ source_incarnation: string; page_id: number | null; slug: string; worktree_id: string | null; topology_generation: string | number | null;
+ intent: unknown; authority: unknown; state: string; outcome: unknown; compacted: unknown; target_kind: string | null;
+ protocol_version: number | null; terminal_reservation: string | number;
+}
+
+function parsedJson(value: unknown): unknown {
+ return typeof value === 'string' ? JSON.parse(value) : value;
+}
+
+function stable(value: unknown): string {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
+ const obj = value as Record<string, unknown>;
+ return `{${Object.keys(obj).sort().map(k => `${JSON.stringify(k)}:${stable(obj[k])}`).join(',')}}`;
+}
+
+class ReplayRollback extends Error {
+ constructor(readonly result: ReplayProbeResult) { super('replay probe rollback'); }
+}
+
+const TERMINAL_STATES = ['committed', 'conflict', 'failed', 'cancelled'];
+
+/**
+ * Resubmits a carried request through admitWriteInTransaction on the target
+ * inside a transaction that is always rolled back, with persistence_brain.enabled
+ * set to the source value so the managed admission path runs. Passes when the
+ * stored id and outcome come back with no new request row and unchanged counters.
+ */
+export async function replayProbe(target: BrainEngine, requestId: string, callerIntent?: unknown,
+ opts: { sourceEnabled?: boolean; runId?: string } = {}): Promise<ReplayProbeResult> {
+ const stored = await target.executeRaw<StoredRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ if (!stored.length) return { status: 'failed', requestId, detail: 'The request is not on the target; it was not carried.' };
+ if (stored.length > 1) return { status: 'failed', requestId, detail: `${stored.length} principals hold this request id; the probe needs one.` };
+ const row = stored[0]!;
+ if (row.compacted === true || row.compacted === 't' || row.intent == null) return { status: 'not_available', reason: 'no_uncompacted_request' };
+ if (callerIntent === undefined || callerIntent === null || typeof callerIntent !== 'object') return { status: 'not_available', reason: 'no_caller_input' };
+ const [source] = await target.executeRaw<{ incarnation: string; archived: unknown }>('SELECT incarnation, archived FROM sources WHERE id=$1', [row.source_id]);
+ if (!source || source.archived === true || source.archived === 't' || source.incarnation !== row.source_incarnation) {
+ return { status: 'not_available', reason: 'archived_source' };
+ }
+ const admission: WriteAdmission = {
+ principal: { kind: row.principal_kind, id: row.principal_id },
+ operation: row.operation,
+ targetKind: (row.target_kind ?? 'page') as WriteAdmission['targetKind'],
+ protocolVersion: (row.protocol_version ?? 1) as WriteAdmission['protocolVersion'],
+ sourceId: row.source_id,
+ sourceIncarnation: row.source_incarnation,
+ slug: row.slug,
+ pageId: row.page_id,
+ worktreeId: row.worktree_id,
+ topologyGeneration: row.topology_generation,
+ requestId: row.request_id,
+ callerIntent: callerIntent as Record<string, unknown>,
+ intent: parsedJson(row.intent) as Record<string, unknown>,
+ authority: parsedJson(row.authority) as WriteAuthority,
+ terminalReservation: Number(row.terminal_reservation),
+ };
+ try {
+ await target.transaction(async tx => {
+ if (opts.runId) await tx.executeRaw("SELECT set_config('gbrain.graduation_run', $1, true)", [opts.runId]);
+ if (opts.sourceEnabled !== undefined) await tx.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [opts.sourceEnabled]);
+ const snapshot = async () => {
+ const [count] = await tx.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM persistence_requests');
+ const counters = await tx.executeRaw<Record<string, unknown>>('SELECT row_to_json(c)::text AS r FROM persistence_counters c ORDER BY key COLLATE "C"');
+ return `${count!.n}|${counters.map(c => c.r).join('\n')}`;
+ };
+ const before = await snapshot();
+ const replayed = await admitWriteInTransaction(tx, admission);
+ const after = await snapshot();
+ const problems = [
+ String(replayed.id) !== String(row.id) ? `returned row ${replayed.id}, stored ${row.id}` : '',
+ stable(parsedJson(replayed.outcome)) !== stable(parsedJson(row.outcome)) ? 'returned outcome differs from the stored outcome' : '',
+ before !== after ? 'request rows or counters changed' : '',
+ TERMINAL_STATES.includes(row.state) ? '' : `stored request is ${row.state}, not terminal`,
+ ].filter(Boolean);
+ throw new ReplayRollback(problems.length ? { status: 'failed', requestId, detail: problems.join('; ') } : { status: 'passed', requestId });
+ });
+ } catch (error) {
+ if (error instanceof ReplayRollback) return error.result;
+ if (error instanceof OperationError && error.code === 'permission_denied') return { status: 'not_available', reason: 'revoked_principal' };
+ if (error instanceof OperationError && error.code === 'source_changed') return { status: 'not_available', reason: 'source_changed' };
+ return { status: 'failed', requestId, detail: `Admission refused the replay: ${message(error)}` };
+ }
+ return { status: 'failed', requestId, detail: 'The probe transaction committed; it must always roll back.' };
+}
+
+async function chooseReplay(e: GraduationEngines, ctx: VerifyContext): Promise<ReplayProbeResult> {
+ let requestId = ctx.replayRequestId;
+ if (!requestId) {
+ const [newest] = await e.target.executeRaw<{ request_id: string }>(`SELECT request_id FROM persistence_requests
+ WHERE NOT compacted AND intent IS NOT NULL AND state = ANY($1::text[]) ORDER BY sequence DESC LIMIT 1`, [TERMINAL_STATES]);
+ if (!newest) return { status: 'not_available', reason: 'no_uncompacted_request' };
+ if (!ctx.replayCallerIntent) return { status: 'not_available', reason: 'no_caller_input' };
+ requestId = newest.request_id;
+ }
+ const [brain] = await e.source.executeRaw<{ enabled: unknown }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ const sourceEnabled = brain ? brain.enabled === true || brain.enabled === 't' : undefined;
+ return replayProbe(e.target, requestId, ctx.replayCallerIntent, { sourceEnabled, runId: ctx.runId });
+}
+
+export async function verifyGraduation(e: GraduationEngines, ctx: VerifyContext): Promise<VerifyResult> {
+ const failures: VerifyFailure[] = [];
+ const batchRows = ctx.batchRows ?? DEFAULT_DIGEST_BATCH_ROWS;
+ for (const [engine, kind] of [[e.source, e.source.kind], [e.target, e.target.kind]] as const) {
+ try { await assertRelationSet(engine, kind, ctx.inventory); }
+ catch (error) { failures.push({ relation: `(${kind} schema)`, kind: 'relation_set', detail: message(error) }); }
+ }
+ const carried = new Set(ctx.inventory.entries.filter(x => x.class === 'carry').map(x => x.relation));
+ for (const side of DERIVED_SIDE_TABLES) {
+ if (!carried.has(side)) failures.push({ relation: side, kind: 'digest', detail: 'Derived side table is not carried, so verify cannot prove it equals the source.' });
+ }
+ const recorded = new Map(ctx.sourceReceipts.map(r => [r.relation, r]));
+ const targetTables = new Set((await copyOrder(e.target, ctx.inventory)).map(x => x.relation));
+ const tables: TableReceipt[] = [];
+ for (const entry of await copyOrder(e.source, ctx.inventory)) {
+ if (!targetTables.has(entry.relation)) {
+ failures.push({ relation: entry.relation, kind: 'relation_set', detail: 'Copied relation is missing on the target.' });
+ continue;
+ }
+ try {
+ const receipt = await verifyTable(e, entry, recorded.get(entry.relation), batchRows, failures);
+ if (receipt) tables.push(receipt);
+ } catch (error) {
+ failures.push({ relation: entry.relation, kind: 'digest', detail: `Digest failed: ${message(error)}` });
+ }
+ }
+ const checks: Array<[VerifyFailure['kind'], () => Promise<void>]> = [
+ ['sequence', () => verifySequences(e, ctx.inventory, failures)],
+ ['fk', () => verifyForeignKeys(e.target, failures)],
+ ['trigger', () => verifyTriggers(e.target, ctx.inventory, ctx.expectFence ?? true, failures)],
+ ];
+ for (const [kind, run] of checks) {
+ try { await run(); } catch (error) { failures.push({ relation: '(target)', kind, detail: `Check failed: ${message(error)}` }); }
+ }
+ let replay: ReplayProbeResult;
+ try { replay = await chooseReplay(e, ctx); }
+ catch (error) { replay = { status: 'failed', requestId: ctx.replayRequestId ?? '', detail: message(error) }; }
+ if (replay.status === 'failed') failures.push({ relation: 'persistence_requests', kind: 'replay', firstKey: replay.requestId, detail: replay.detail });
+ let doctorFailingChecks: readonly string[] = [];
+ try { doctorFailingChecks = await ctx.runDoctor(); }
+ catch (error) { doctorFailingChecks = [`doctor_unavailable: ${message(error)}`]; }
+ for (const check of doctorFailingChecks) failures.push({ relation: '(target doctor)', kind: 'doctor', detail: `Doctor check ${check} fails on the target.` });
+ return { ok: failures.length === 0, tables, failures, replay, doctorFailingChecks };
+}