Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
graduation(g2a): custody, schema migration, fence, orchestrator, connect/admission checks
garrytan574c7b3fa423
diff --git a/src/cli.ts b/src/cli.tsindex ad39bb129f..2675755f17 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2804,6 +2804,9 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEnginprocess.env.GBRAIN_NO_RETRY_CONNECT === '1';const { connectWithRetry } = await import('./core/db.ts');await exitOnRepairFailed(() => connectWithRetry(engine, toEngineConfig(config), { noRetry }));+ // Engine graduation: a fenced target or a cut-over source refuses every connect but the run's own.+ try { await (await import('./core/persistence/graduation-custody.ts')).assertGraduationConnectAllowed(engine); }+ catch (error) { await engine.disconnect().catch(() => {}); throw error; }// v0.30.1 (Codex X1 / C2): probeOnly skips both hasPendingMigrations() probe// AND initSchema(). Used by `get_health` MCP op + `gbrain upgrade --status`diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.tsnew file mode 100644index 0000000000..a07e311fd2--- /dev/null+++ b/src/core/persistence/engine-graduation.ts@@ -0,0 +1,1337 @@+/**+ * Engine graduation orchestrator (PGLite -> Postgres): plan, run, status,+ * resume, rollback and reconciliation over one custody protocol.+ *+ * The kernel lock on the source is held from step 1 to the end of step 8+ * (quiesce, record, drain, fence target, copy, verify, fence both then grant+ * authority, flip routing). Exactly one engine accepts writes at every+ * instant: before step 7 only the source (the target is fenced in the+ * database from step 4), during step 7 neither, after it only the target.+ * Every state change is driven by the transition tables in+ * engine-graduation.types.ts and recorded in the 0600 manifest+ * (`<GBRAIN_HOME>/graduation-manifest.json`), the sibling intent marker and+ * the `persistence_graduation` rows; restart reconciliation continues from the+ * first incomplete step using the recorded identities, never current routing.+ *+ * Graduation is CLI-only: no operations.ts entry, no remote caller.+ */+import { createHash, randomUUID } from 'node:crypto';+import { existsSync, readFileSync, renameSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import type { Action } from '../agent-output.ts';+import type { BrainEngine } from '../engine.ts';+import type { EngineConfig } from '../types.ts';+import { configDir, loadConfigFileOnly, saveConfig, type GBrainConfig } from '../config.ts';+import { exclusiveFix, liveServeOwner } from '../exclusive-fix.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { acquireKernelLockOnly, PgliteBusyError, peekLock, releaseLock, type LockHandle } from '../pglite-lock.ts';+import { localHostId } from './identity.ts';+import { quiesceAutopilot } from '../../commands/migrate-engine.ts';+import { LATEST_VERSION } from '../migrate.ts';+import {+ assertTransition, GRADUATION_MANIFEST_VERSION, MANIFEST_TRANSITIONS,+ type GraduationBlocker, type GraduationErrorCode, type GraduationManifest, type GraduationPathState, type GraduationPlan,+ type GraduationReceipt, type GraduationStatusDoc, type IntentMarker, type Inventory, type InventoryEntry, type LossKind,+ type ManifestState, type TableCheckpoint, type TableReceipt, type TargetIdentity, type TargetRoutes, type TriggerBypass,+} from './engine-graduation.types.ts';+import {+ currentProcessIdentity, fsyncParent, graduatedPath, graduationDataDir, graduationError, graduationInProgressError,+ graduationInterruptedError, graduationSplitBrainError, inspectGraduationPath, markerLiveness, moveAsideHeld,+ readIntentMarker, readTombstone, registerGraduationRunInProcess, removeIntentMarker, removeTombstone, targetDisplayUrl,+ TERMINAL_STATES, TombstonePathOccupiedError, writeFileDurably, writeIntentMarker, writeTombstone,+} from './graduation-custody.ts';+import {+ dropGraduationFence, graduationFenceStatus, installGraduationFence, readGraduationRow, setSourceState, setTargetState,+ withGraduationRun,+} from './graduation-schema.ts';+import { moveHeldPglite } from './maintenance.ts';+import { assertRelationSet, copyOrder, fkClosure, GRADUATION_INVENTORY } from './graduation-inventory.ts';+import { digestTable } from './graduation-digest.ts';+import { verifyGraduation } from './graduation-verify.ts';+import { crossCheckRoutes, probeTarget, resolveTargetRoutes, targetIdentity, type TargetProbe } from './graduation-target.ts';+import { drainForGraduation, freezeSource, graduationBlockers } from './graduation-drain.ts';+import { buildDeferredIndexes, copySequences, copyTable, deferIndexes, detectTriggerBypass, reenableTriggers } from './graduation-copy.ts';++const DEFAULT_DRAIN_TIMEOUT_MS = 60_000;+const HANDOFF_TIMEOUT_MS = 30_000;+const DOCS = 'docs/guides/move-to-postgres.md';+const STATUS_ARGV = ['gbrain', 'migrate', '--status', '--json'];+/** Usage-tracking columns that change on every authorized call; not a security change. */+const SECURITY_VOLATILE_COLUMNS = new Set(['last_used_at']);+const SECURITY_TABLES = ['access_tokens', 'oauth_clients', 'oauth_tokens', 'oauth_grant_audit', 'persistence_local_writers', 'fact_withdrawals'] as const;++const STATE_RANK: Readonly<Record<ManifestState, number>> = {+ planned: 0, quiesced: 1, draining: 2, copying: 3, verifying: 4, verify_failed: 4, verified: 5, cutover: 6, tombstoned: 7,+ authoritative: 8, graduated: 9, rollback_fenced: 10, rollback_approved: 11, source_restoring: 12, rolled_back: 13, abandoned: 13,+};++// ── dependencies ───────────────────────────────────────────────────────────++export interface GraduationSourceEngine extends BrainEngine {+ closeRetainingLock(): Promise<LockHandle>;+ connectWithHeldLock(config: EngineConfig, lock: LockHandle): Promise<void>;+}++type Routes = TargetRoutes & { mainUrl: string; ddlUrl: string };++/** Everything the orchestrator calls outside custody; tests replace any part. */+export interface GraduationDeps {+ inventory: Inventory;+ assertRelationSet: typeof assertRelationSet;+ copyOrder: typeof copyOrder;+ fkClosure: typeof fkClosure;+ digestTable: typeof digestTable;+ verifyGraduation: typeof verifyGraduation;+ resolveTargetRoutes: typeof resolveTargetRoutes;+ targetIdentity: typeof targetIdentity;+ probeTarget: typeof probeTarget;+ crossCheckRoutes: typeof crossCheckRoutes;+ graduationBlockers: typeof graduationBlockers;+ drainForGraduation: typeof drainForGraduation;+ freezeSource: typeof freezeSource;+ detectTriggerBypass: typeof detectTriggerBypass;+ copyTable: typeof copyTable;+ copySequences: typeof copySequences;+ deferIndexes: typeof deferIndexes;+ buildDeferredIndexes: typeof buildDeferredIndexes;+ reenableTriggers: typeof reenableTriggers;+ /** Open the PGLite source (full connect; `migrate` applies pending migrations). */+ openSource(dataDir: string, opts: { migrate: boolean }): Promise<GraduationSourceEngine>;+ /** A fresh, unconnected PGLite engine for a held-lock open. */+ newSourceEngine(): Promise<GraduationSourceEngine>;+ openTarget(url: string): Promise<BrainEngine>;+ /** Target schema bootstrap, sized from the source's embedding layout. */+ initTargetSchema(target: BrainEngine, source: BrainEngine): Promise<void>;+ claimAutopilotPause(): Promise<(() => void) | null>;+ /** Failing check names of `gbrain doctor --no-migrate --json` against the fenced target. */+ runTargetDoctor(runId: string, mainUrl: string): Promise<readonly string[]>;+ /** Failing source checks, measured with the source open under the run's lock. */+ runSourceDoctor(source: BrainEngine): Promise<readonly string[]>;+ hostId(): string;+ mountsPath(): string;+}++export function defaultGraduationDeps(): GraduationDeps {+ return {+ inventory: GRADUATION_INVENTORY,+ assertRelationSet, copyOrder, fkClosure, digestTable, verifyGraduation,+ resolveTargetRoutes, targetIdentity, probeTarget, crossCheckRoutes,+ graduationBlockers, drainForGraduation, freezeSource,+ detectTriggerBypass, copyTable, copySequences, deferIndexes, buildDeferredIndexes, reenableTriggers,+ async openSource(dataDir, opts) {+ const engine = await this.newSourceEngine();+ await engine.connect({ engine: 'pglite', database_path: dataDir });+ if (opts.migrate) {+ try {+ const { hasPendingMigrations } = await import('../migrate.ts');+ if (await hasPendingMigrations(engine)) await engine.initSchema();+ } catch (error) { await engine.disconnect(); throw error; }+ }+ return engine;+ },+ async newSourceEngine() {+ const { createEngine } = await import('../engine-factory.ts');+ return await createEngine({ engine: 'pglite' }) as GraduationSourceEngine;+ },+ async openTarget(url) {+ const { createEngine } = await import('../engine-factory.ts');+ const engine = await createEngine({ engine: 'postgres' });+ try { await engine.connect({ engine: 'postgres', database_url: url }); }+ catch (error) { throw mapTargetConnectError(error); }+ return engine;+ },+ async initTargetSchema(target) { await target.initSchema(); },+ claimAutopilotPause: () => withStdoutOnStderr(() => quiesceAutopilot()),+ async runTargetDoctor(runId, mainUrl) { return spawnTargetDoctor(runId, mainUrl); },+ async runSourceDoctor() { return []; },+ hostId: () => localHostId(),+ mountsPath: () => process.env.GBRAIN_MOUNTS_PATH || join(homedir(), '.gbrain', 'mounts.json'),+ };+}++async function withStdoutOnStderr<T>(fn: () => Promise<T>): Promise<T> {+ const log = console.log;+ console.log = (...args: unknown[]) => console.error(...args);+ try { return await fn(); } finally { console.log = log; }+}++function spawnTargetDoctor(runId: string, mainUrl: string): readonly string[] {+ const script = process.argv[1] && /\.(ts|js|mjs)$/.test(process.argv[1]) ? [process.argv[1]] : [];+ const child = spawnSync(process.execPath, [...script, 'doctor', '--no-migrate', '--json'], {+ env: { ...process.env, GBRAIN_DATABASE_URL: mainUrl, GBRAIN_GRADUATION_RUN: runId },+ encoding: 'utf8', timeout: 600_000, maxBuffer: 64 * 1024 * 1024,+ });+ try {+ const doc = JSON.parse(child.stdout) as { checks?: Array<{ name?: string; status?: string }> };+ if (!Array.isArray(doc.checks)) return ['doctor_output_unreadable'];+ return doc.checks.filter(c => c.status === 'fail').map(c => String(c.name ?? 'unnamed'));+ } catch { return ['doctor_unavailable']; }+}++function mapTargetConnectError(error: unknown): unknown {+ const e = error as { code?: string; message?: string };+ if (e?.code === '28P01' || /password authentication failed/i.test(e?.message ?? '')) {+ return graduationError('graduation_target_auth_failed', 'The target database refused the recorded credentials.',+ 'Ask the user for the current URL of the same database, put it in an environment variable, and rerun with `--url-env <VAR>`; the host, port, database and user must match the recorded target.',+ 'The password changed since the run started; the manifest identity excludes the password so the same database is recognised.',+ { argv: ['gbrain', 'migrate', '--resume', '--url-env', 'GBRAIN_TARGET_URL'], consent: ['credentials'], actor: 'agent', requires_exclusive: true,+ why: 'Reconnects to the same target with the new password and continues the run.', verify: { argv: STATUS_ARGV } });+ }+ return error;+}++// ── manifest v3 ────────────────────────────────────────────────────────────++export function graduationManifestPath(): string { return join(configDir(), 'graduation-manifest.json'); }++export function readGraduationManifest(path = graduationManifestPath()): GraduationManifest | null {+ let raw: string;+ try { raw = readFileSync(path, 'utf8'); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }+ const parsed = JSON.parse(raw) as GraduationManifest;+ if (parsed?.version !== GRADUATION_MANIFEST_VERSION) throw new Error(`Unsupported graduation manifest at ${path} (version ${String(parsed?.version)}).`);+ return parsed;+}++/** Atomic write + fsync, mode 0600 (it holds the full target URLs). */+export function writeGraduationManifest(manifest: GraduationManifest, path = graduationManifestPath()): void {+ writeFileDurably(path, `${JSON.stringify(manifest, null, 2)}\n`);+}++/** Apply a manifest transition from MANIFEST_TRANSITIONS; an illegal one throws. */+export function transitionManifest(manifest: GraduationManifest, to: ManifestState): void {+ if (manifest.state !== to) assertTransition(MANIFEST_TRANSITIONS, manifest.state, to);+ manifest.state = to;+ manifest.updatedAt = new Date().toISOString();+}++export function redactManifest(manifest: GraduationManifest): Omit<GraduationManifest, 'targetUrls'> {+ const { targetUrls: _secret, ...rest } = manifest;+ return rest;+}++// ── options ────────────────────────────────────────────────────────────────++export interface GraduationProgressEvent {+ phase: string;+ state?: ManifestState;+ relation?: string;+ rows?: number;+ done?: number;+ total?: number;+ message?: string;+}++interface CommonOptions {+ env?: NodeJS.ProcessEnv;+ manifestPath?: string;+ deps?: Partial<GraduationDeps>;+ onProgress?: (event: GraduationProgressEvent) => void;+ /** Crash-test seam; defaults to GBRAIN_GRADUATION_PAUSE_AT. */+ pauseAt?: string;+ /** In-process tests: awaited at the pause seam instead of blocking. */+ pauseHook?: (step: string) => Promise<void>;+ handoffTimeoutMs?: number;+}++export interface GraduationPlanOptions extends CommonOptions {+ config: GBrainConfig;+ url?: string;+ urlEnv?: string;+ invokedAs?: 'postgres' | 'supabase';+ force?: boolean;+ triggerBypass?: TriggerBypass;+ batchBytes?: number;+}++export interface GraduationRunOptions extends GraduationPlanOptions {+ /** The plan hash the user approved (`--yes --expect <plan_hash>`). */+ expect: string;+ drainTimeoutMs?: number;+}++export interface GraduationResumeOptions extends CommonOptions {+ url?: string;+ urlEnv?: string;+ drainTimeoutMs?: number;+ batchBytes?: number;+}++export interface GraduationRollbackOptions extends CommonOptions {+ yes?: boolean;+ expect?: string;+ url?: string;+ urlEnv?: string;+}++// ── run context ────────────────────────────────────────────────────────────++interface Run {+ m: GraduationManifest;+ path: string;+ deps: GraduationDeps;+ opts: CommonOptions & { drainTimeoutMs?: number; batchBytes?: number; config?: GBrainConfig };+ dataDir: string;+ source: GraduationSourceEngine | null;+ lock: LockHandle | null;+ main: BrainEngine | null;+ ddl: BrainEngine | null;+ resumePause: (() => void) | null;+ unregister: () => void;+}++function newRun(m: GraduationManifest, path: string, opts: Run['opts']): Run {+ return {+ m, path, opts, deps: { ...defaultGraduationDeps(), ...opts.deps }, dataDir: m.source.dataDir,+ source: null, lock: null, main: null, ddl: null, resumePause: null, unregister: registerGraduationRunInProcess(m.runId),+ };+}++function progress(run: Pick<Run, 'opts'>, event: GraduationProgressEvent): void { run.opts.onProgress?.(event); }++function markerFor(run: Run): IntentMarker {+ return { runId: run.m.runId, state: run.m.state, ...currentProcessIdentity(), target: run.m.target, updatedAt: new Date().toISOString() };+}++/** Persist a manifest transition and mirror it into the intent marker (terminal states remove the marker). */+function advance(run: Run, to: ManifestState, patch: Partial<GraduationManifest> = {}): void {+ transitionManifest(run.m, to);+ Object.assign(run.m, patch);+ writeGraduationManifest(run.m, run.path);+ if (to === 'rolled_back' || to === 'abandoned') removeIntentMarker(run.dataDir);+ else writeIntentMarker(run.dataDir, markerFor(run));+ progress(run, { phase: 'state', state: to });+}++function save(run: Run): void {+ run.m.updatedAt = new Date().toISOString();+ writeGraduationManifest(run.m, run.path);+}++async function pauseSeam(run: Pick<Run, 'opts'>, step: string): Promise<void> {+ const env = run.opts.env ?? process.env;+ if ((run.opts.pauseAt ?? env.GBRAIN_GRADUATION_PAUSE_AT) !== step) return;+ progress(run, { phase: 'paused', message: step });+ if (run.opts.pauseHook) { await run.opts.pauseHook(step); return; }+ process.stderr.write(`[graduation] paused at ${step} (GBRAIN_GRADUATION_PAUSE_AT)\n`);+ const release = env.GBRAIN_GRADUATION_PAUSE_RELEASE;+ for (;;) {+ if (release && existsSync(release)) return;+ await new Promise(resolve => setTimeout(resolve, 100));+ }+}++async function cleanup(run: Run): Promise<void> {+ const errors: unknown[] = [];+ const attempt = async (fn: () => Promise<void> | void) => { try { await fn(); } catch (error) { errors.push(error); } };+ if (run.source) { const source = run.source; run.source = null; await attempt(() => source.disconnect()); }+ if (run.lock) { const lock = run.lock; run.lock = null; await attempt(() => releaseLock(lock)); }+ const targets = new Set([run.main, run.ddl].filter((e): e is BrainEngine => !!e));+ run.main = null; run.ddl = null;+ for (const engine of targets) await attempt(() => engine.disconnect());+ if (run.resumePause) { const resume = run.resumePause; run.resumePause = null; await attempt(resume); }+ run.unregister();+ if (errors.length) process.stderr.write(`[graduation] cleanup: ${errors.map(String).join('; ')}\n`);+}++function invokedAs(run: { m: GraduationManifest }): 'postgres' | 'supabase' { return run.m.invokedAs ?? 'postgres'; }+function urlEnvName(routes: TargetRoutes): string { return routes.urlEnv ?? 'GBRAIN_TARGET_URL'; }++function runArgv(spelling: 'postgres' | 'supabase', routes: TargetRoutes, planHash: string): string[] {+ return ['gbrain', 'migrate', '--to', spelling, '--url-env', urlEnvName(routes), '--yes', '--expect', planHash];+}++// ── plan ───────────────────────────────────────────────────────────────────++interface PlanInputs {+ config: GBrainConfig;+ env: NodeJS.ProcessEnv;+ routes: Routes;+ target: TargetIdentity;+ invokedAs: 'postgres' | 'supabase';+ force: boolean;+ triggerBypassOverride?: TriggerBypass;+ batchBytes?: number;+}++function sourceDataDir(config: GBrainConfig): string {+ if (config.engine !== 'pglite' || !config.database_path) {+ throw opError('invalid_params', 'Engine graduation moves a PGLite brain; this brain is not configured as PGLite.',+ 'Run graduation only from a PGLite brain (`gbrain engine status --json` shows the configured engine).',+ { why: 'Graduation copies a PGLite datastore into Postgres; other directions use the legacy copier.',+ fix: { argv: ['gbrain', 'engine', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the configured engine and datastore.' } });+ }+ return graduationDataDir(config.database_path);+}++function planHashOf(input: Record<string, unknown>): string {+ const canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical)+ : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value as object).sort().map(k => [k, canonical((value as Record<string, unknown>)[k])]))+ : value;+ return createHash('sha256').update(JSON.stringify(canonical(input))).digest('hex').slice(0, 16);+}++function probeTargetEmpty(probe: TargetProbe): boolean { return probe.empty; }++async function countTables(source: BrainEngine, inventory: Inventory): Promise<GraduationPlan['tables']> {+ const relations = inventory.entries.filter(e => e.kind === 'table' && e.engines.pglite).map(e => e.relation);+ const present = await source.executeRaw<{ relname: string; q: string; bytes: string }>(+ `SELECT c.relname, quote_ident(c.relname) AS q, pg_total_relation_size(c.oid)::text AS bytes FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relkind IN ('r','p') AND c.relname = ANY($1::text[])`, [relations]);+ const byName = new Map(present.map(r => [r.relname, r]));+ const rows: GraduationPlan['tables'][number][] = [];+ for (const entry of inventory.entries) {+ const found = byName.get(entry.relation);+ if (!found) continue;+ const [count] = await source.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM ${found.q}`);+ rows.push({ relation: entry.relation, class: entry.class, rows: Number(count?.n ?? 0), bytes: Number(found.bytes) });+ }+ return rows;+}++function envOverrideBlockers(env: NodeJS.ProcessEnv, routes: Routes): GraduationBlocker[] {+ return (['GBRAIN_DATABASE_URL', 'DATABASE_URL'] as const)+ .filter(name => env[name] && env[name] !== routes.mainUrl)+ .map(name => ({ kind: 'env_override' as const, id: name, needsUser: true,+ detail: `${name} is set in this environment and would override the routing flip; unset it (or point it at the target) before graduating.` }));+}++/** Read-only plan assembly over an open source (or none when a live serve holds it) and a target session. */+async function assemblePlan(deps: GraduationDeps, input: PlanInputs, source: BrainEngine | null, main: BrainEngine | null, targetOurs: boolean): Promise<GraduationPlan> {+ const dataDir = sourceDataDir(input.config);+ const hostId = deps.hostId();+ const blockers: GraduationBlocker[] = [...envOverrideBlockers(input.env, input.routes)];+ if (process.platform === 'win32') {+ blockers.push({ kind: 'unsupported_platform', id: 'win32', needsUser: true, detail: 'Engine graduation is unavailable on Windows until its tombstone and crash tests run there.' });+ }+ let brainId = '';+ let tables: GraduationPlan['tables'] = [];+ if (source) {+ try { await deps.assertRelationSet(source, 'pglite', deps.inventory); }+ catch (error) { blockers.push({ kind: 'unclassified_relation', id: 'source', needsUser: false, detail: (error as Error).message }); }+ blockers.push(...await deps.graduationBlockers(source, hostId));+ for (const failing of await deps.runSourceDoctor(source)) {+ blockers.push({ kind: 'source_doctor', id: failing, needsUser: true, detail: `Doctor check ${failing} fails on the source; fix it before graduating.`, argv: ['gbrain', 'doctor', '--json'] });+ }+ const [brain] = await source.executeRaw<{ brain_id: string }>('SELECT brain_id::text AS brain_id FROM persistence_brain WHERE singleton = 1');+ brainId = brain?.brain_id ?? '';+ tables = await countTables(source, deps.inventory);+ }+ const probe = await deps.probeTarget(input.routes);+ const targetAcceptable = targetOurs || probeTargetEmpty(probe);+ if (!targetAcceptable && !input.force) {+ blockers.push({ kind: 'target_not_empty', id: input.target.id, needsUser: true, detail: 'The target database already holds gbrain data that this run did not write.' });+ }+ const triggerBypass = input.triggerBypassOverride ?? (main ? await deps.detectTriggerBypass(main) : null);+ if (!triggerBypass) blockers.push({ kind: 'target_unsupported', id: 'trigger_bypass', needsUser: true, detail: 'The target role can neither SET session_replication_role nor disable user triggers on the gbrain tables.' });+ let forceSnapshot: Array<[string, string]> | null = null;+ if (input.force && !targetAcceptable && main) {+ forceSnapshot = [];+ for (const entry of deps.inventory.entries.filter(e => e.lossKind === 'user_data' && e.engines.postgres && e.kind === 'table')) {+ const [present] = await main.executeRaw<{ ok: boolean }>('SELECT to_regclass($1) IS NOT NULL AS ok', [entry.relation]);+ if (present?.ok) forceSnapshot.push([entry.relation, (await deps.digestTable(main, entry)).rootSha256]);+ }+ }+ const planHash = planHashOf({+ v: 1, source: { dataDir, hostId }, target: input.target.id, inventory: deps.inventory.version, schema: LATEST_VERSION,+ classes: deps.inventory.entries.map(e => `${e.relation}:${e.class}`).sort(),+ blockers: blockers.filter(b => b.needsUser).map(b => `${b.kind}:${b.id}`).sort(),+ triggerBypass, targetAcceptable, force: input.force, forceSnapshot, batchBytes: input.batchBytes ?? null,+ });+ const rows = tables.filter(t => t.class === 'carry' || t.class === 'rebind').reduce((sum, t) => sum + t.rows, 0);+ const bytes = tables.filter(t => t.class === 'carry' || t.class === 'rebind').reduce((sum, t) => sum + t.bytes, 0);+ const copy = Math.ceil(rows / 5_000 + bytes / 20_000_000);+ const verify = Math.ceil(copy * 0.6);+ const doctor = 30;+ return {+ planHash, source: { dataDir, brainId, hostId }, target: input.target, routes: { main: input.routes.main, ddl: input.routes.ddl, ...(input.routes.urlEnv ? { urlEnv: input.routes.urlEnv } : {}) },+ triggerBypass, tables, blockers, estimateSeconds: { copy, verify, doctor, total: copy + verify + doctor },+ sourceMeasured: source ? 'now' : 'at_run_start',+ nextArgv: runArgv(input.invokedAs, input.routes, planHash),+ };+}++function planInputs(deps: GraduationDeps, opts: GraduationPlanOptions): PlanInputs {+ const env = opts.env ?? process.env;+ const routes = deps.resolveTargetRoutes({ url: opts.url, urlEnv: opts.urlEnv, env });+ return { config: opts.config, env, routes, target: deps.targetIdentity(routes.mainUrl), invokedAs: opts.invokedAs ?? 'postgres',+ force: !!opts.force, triggerBypassOverride: opts.triggerBypass, batchBytes: opts.batchBytes };+}++function refuseOnPathState(state: GraduationPathState): void {+ if (state.kind === 'graduated') throw graduationAlreadyGraduated(state);+ if (state.kind === 'split_brain') throw graduationSplitBrainError(state);+ if (state.kind === 'in_progress' && state.marker) throw graduationInProgressError({ runId: state.marker.runId, state: state.marker.state, where: 'source' });+}++function graduationAlreadyGraduated(state: GraduationPathState): OperationError {+ return graduationError('engine_graduated', `This PGLite datastore already moved to Postgres (run ${state.tombstone?.runId ?? 'unknown'}).`,+ 'Run `gbrain migrate --resume` to finish any pending routing flip on this host; `gbrain migrate --status --json` shows the recorded run.',+ 'The datastore path holds a graduation tombstone, so there is nothing left to move.',+ { argv: ['gbrain', 'migrate', '--resume'], consent: [], actor: 'agent', requires_exclusive: true, why: 'Finishes the recorded graduation.', verify: { argv: STATUS_ARGV } });+}++/**+ * The read-only plan: zero mutations on either engine (no schema migration,+ * no target DDL, no marker). The source opens through a probe-only connect+ * under a short kernel-lock hold; a live serve holding it marks counts+ * `measured at run start`.+ */+export async function planGraduation(opts: GraduationPlanOptions): Promise<GraduationPlan> {+ const deps = { ...defaultGraduationDeps(), ...opts.deps };+ const input = planInputs(deps, opts);+ const dataDir = sourceDataDir(opts.config);+ refuseOnPathState(inspectGraduationPath(dataDir));+ let source: GraduationSourceEngine | null = null;+ let main: BrainEngine | null = null;+ try {+ try { source = await deps.openSource(dataDir, { migrate: false }); }+ catch (error) { if (!(error instanceof PgliteBusyError)) throw error; }+ main = await deps.openTarget(input.routes.mainUrl);+ return await assemblePlan(deps, input, source, main, false);+ } finally {+ if (source) await source.disconnect();+ if (main) await main.disconnect();+ }+}++// ── run ────────────────────────────────────────────────────────────────────++function blockerRefusal(blocker: GraduationBlocker, run: { m: GraduationManifest }): OperationError {+ const codeByKind: Partial<Record<GraduationBlocker['kind'], GraduationErrorCode>> = {+ foreign_host_binding: 'graduation_foreign_host_binding', target_not_empty: 'graduation_target_not_empty',+ unsupported_platform: 'graduation_unsupported_platform', unclassified_relation: 'graduation_unclassified_table',+ embedding_dimension: 'graduation_embedding_dimension_mismatch', target_unsupported: 'graduation_target_unsupported',+ writer_held: 'graduation_source_writer_held', env_override: 'graduation_target_unsupported', source_doctor: 'graduation_verify_failed',+ };+ const code = codeByKind[blocker.kind] ?? 'graduation_drain_timeout';+ const fix: Action = blocker.argv?.length+ ? { argv: [...blocker.argv], consent: blocker.needsUser ? ['destructive'] : [], actor: 'agent', requires_exclusive: false, why: blocker.detail, verify: { argv: planArgv(run) } }+ : blocker.needsUser+ ? { argv: planArgv(run), consent: ['egress'], actor: 'agent', requires_exclusive: false, why: `${blocker.detail} Ask the user to resolve it, then show the plan again.`, user_message: blocker.detail }+ : { consent: [], actor: 'agent', requires_exclusive: false, why: blocker.detail };+ return graduationError(code, `Graduation is blocked: ${blocker.detail}`,+ blocker.needsUser ? 'Relay the blocker to the user; nothing was changed and the source stays authoritative.' : 'Follow the fix; nothing was changed and the source stays authoritative.',+ `Blocker ${blocker.kind} (${blocker.id}) must clear before any copy starts.`, fix, `${blocker.kind}:${blocker.id}`);+}++function planArgv(run: { m: GraduationManifest }): string[] {+ return ['gbrain', 'migrate', '--to', invokedAs(run), '--url-env', urlEnvName(run.m.routes), '--plan', '--json'];+}++function writerHeldError(run: Run, error: unknown): OperationError {+ const peek = peekLock(run.dataDir);+ const owner = liveServeOwner(error) ?? (peek.held && peek.pid ? { pid: peek.pid, transport: peek.http ? 'http' as const : 'stdio' as const, is_self: false } : null);+ const rerun: Action = { argv: runArgv(invokedAs(run), run.m.routes, run.m.planHash), consent: [], actor: 'agent', requires_exclusive: true,+ why: 'Reruns the approved graduation once the datastore is free.', verify: { argv: STATUS_ARGV } };+ const fix = owner ? exclusiveFix(rerun, owner)+ : { ...rerun, actor: 'user' as const, user_message: 'Another gbrain process holds this brain; please stop it, then I will rerun the move.' };+ return graduationError('graduation_source_writer_held',+ `Another process holds this PGLite datastore${owner ? ` (PID ${owner.pid}, ${owner.transport})` : ''} and did not hand it off within ${Math.round((run.opts.handoffTimeoutMs ?? HANDOFF_TIMEOUT_MS) / 1000)} s.`,+ 'Stop the named server or daemon, then rerun the same command; the plan approval still holds.',+ 'Graduation needs the kernel lock on the source for the whole move; a holder that keeps writing would race the copy.', fix);+}++async function openSourceUnderLock(run: Run): Promise<void> {+ const deadline = Date.now() + (run.opts.handoffTimeoutMs ?? HANDOFF_TIMEOUT_MS);+ for (;;) {+ try { run.source = await run.deps.openSource(run.dataDir, { migrate: true }); return; }+ catch (error) {+ if (!(error instanceof PgliteBusyError)) throw error;+ if (Date.now() >= deadline) throw writerHeldError(run, error);+ progress(run, { phase: 'handoff', message: 'waiting for the live serve to hand off the datastore' });+ await new Promise(resolve => setTimeout(resolve, 250));+ }+ }+}++async function claimPause(run: Run): Promise<void> {+ if (run.resumePause) return;+ const resume = await run.deps.claimAutopilotPause();+ if (!resume) {+ throw graduationError('graduation_in_progress', 'Another migration or an operator hold owns the autopilot pause marker.',+ 'Wait for the other migration to finish, then retry; `gbrain migrate --status --json` shows a graduation run.',+ 'The autopilot pause marker is the migration mutex; running without it would let two moves race.',+ { argv: STATUS_ARGV, consent: [], actor: 'provider', requires_exclusive: false, why: 'Shows whether a graduation run holds the machine.', verify: { argv: STATUS_ARGV } });+ }+ run.resumePause = resume;+}++async function openTargets(run: Run): Promise<void> {+ const urls = run.m.targetUrls;+ if (!urls) throw new Error('The graduation manifest has no target URLs.');+ if (!run.main) run.main = await run.deps.openTarget(urls.main);+ if (!run.ddl) run.ddl = urls.ddl === urls.main ? run.main : await run.deps.openTarget(urls.ddl);+}++/** Step 1 (fresh run): marker before the lock, pause marker, source under the lock, in-run plan bound to the approval. */+async function quiesceFresh(run: Run, input: PlanInputs, expect: string): Promise<void> {+ writeGraduationManifest(run.m, run.path);+ writeIntentMarker(run.dataDir, markerFor(run));+ await claimPause(run);+ await openSourceUnderLock(run);+ await openTargets(run);+ const plan = await assemblePlan(run.deps, input, run.source, run.main, false);+ if (plan.planHash !== expect) {+ throw opError('preview_changed', 'The brain or target changed since the approved plan; nothing was moved.',+ 'Show the user the fresh plan (the preview command) and rerun with its plan_hash after they agree.',+ { why: 'The approval binds identities, inventory, blockers, trigger bypass and target emptiness; one of them changed.',+ fix: { argv: runArgv(input.invokedAs, input.routes, plan.planHash), consent: ['egress', 'destructive'], actor: 'agent', requires_exclusive: true,+ why: 'Runs the move against the fresh plan once the user agrees.', plan_hash: plan.planHash, preview_argv: planArgv(run), verify: { argv: STATUS_ARGV } } });+ }+ const blocker = plan.blockers.find(b => b.needsUser || b.kind === 'unclassified_relation');+ if (blocker) throw blockerRefusal(blocker, run);+ run.m.source = plan.source;+ run.m.triggerBypass = plan.triggerBypass!;+ const [pending] = await run.source!.executeRaw<{ request_id: string | null }>(+ `SELECT request_id::text AS request_id FROM persistence_requests WHERE state IN ('queued','running','recovering') ORDER BY sequence LIMIT 1`).catch(() => [{ request_id: null }]);+ run.m.replayRequestId = pending?.request_id ?? null;+ save(run);+}++/** Step 1 on resume: same custody, recorded identities; before cutover the recorded approval must still match. */+async function quiesceResume(run: Run): Promise<void> {+ writeIntentMarker(run.dataDir, markerFor(run));+ await claimPause(run);+ await openSourceUnderLock(run);+ const [brain] = await run.source!.executeRaw<{ brain_id: string }>('SELECT brain_id::text AS brain_id FROM persistence_brain WHERE singleton = 1');+ if (run.m.source.brainId && brain?.brain_id !== run.m.source.brainId) {+ throw graduationSplitBrainError({ dataDir: run.dataDir, movedTo: null, marker: readIntentMarker(run.dataDir),+ detail: `The datastore at ${run.dataDir} has brain_id ${brain?.brain_id ?? 'unknown'}, not the recorded ${run.m.source.brainId}.` });+ }+ await openTargets(run);+ if (STATE_RANK[run.m.state] < STATE_RANK.cutover) await recheckApproval(run);+}++async function recheckApproval(run: Run): Promise<void> {+ const config = loadConfigFileOnly() ?? run.opts.config ?? ({ engine: 'pglite', database_path: run.dataDir } as GBrainConfig);+ const row = await readGraduationRow(run.main!);+ const input: PlanInputs = {+ config: { ...config, engine: 'pglite', database_path: run.dataDir }, env: run.opts.env ?? process.env,+ routes: { ...run.m.routes, mainUrl: run.m.targetUrls!.main, ddlUrl: run.m.targetUrls!.ddl }, target: run.m.target,+ invokedAs: invokedAs(run), force: false, triggerBypassOverride: run.m.triggerBypass, batchBytes: run.opts.batchBytes,+ };+ const ours = row?.role === 'target' && row.run_id === run.m.runId;+ const plan = await assemblePlan(run.deps, input, run.source, run.main, ours);+ const blocker = plan.blockers.find(b => b.needsUser || b.kind === 'unclassified_relation');+ if (blocker) throw blockerRefusal(blocker, run);+ if (!run.m.force && plan.planHash !== run.m.planHash) {+ throw opError('preview_changed', 'The brain or target changed since the approved plan; the run did not continue.',+ 'Show the user the fresh plan and, after they agree, roll this run back (`gbrain migrate --rollback-to-source`) and start again with the new plan_hash.',+ { why: 'Resume reuses the recorded approval only while identities, inventory, person-needed blockers and trigger bypass are unchanged.',+ fix: { argv: planArgv(run), consent: ['egress'], actor: 'agent', requires_exclusive: false, why: 'Shows the fresh plan.', plan_hash: plan.planHash, verify: { argv: STATUS_ARGV } } });+ }+}++async function sourceReceipts(run: Run): Promise<TableReceipt[]> {+ const receipts: TableReceipt[] = [];+ for (const entry of await run.deps.copyOrder(run.source!, run.deps.inventory)) {+ receipts.push(await run.deps.digestTable(run.source!, entry, { applyTransforms: true }));+ }+ return receipts;+}++function changedRelations(before: readonly TableReceipt[], after: readonly TableReceipt[]): string[] {+ const old = new Map(before.map(r => [r.relation, r.rootSha256]));+ return after.filter(r => old.get(r.relation) !== r.rootSha256).map(r => r.relation)+ .concat(before.filter(r => !after.some(a => a.relation === r.relation)).map(r => r.relation));+}++/** Mark relations and their FK dependency closure for re-copy. */+async function markForRecopy(run: Run, relations: readonly string[]): Promise<void> {+ const closure = new Set<string>();+ for (const relation of relations) {+ closure.add(relation);+ for (const child of await run.deps.fkClosure(run.source!, relation)) closure.add(child);+ }+ run.m.tables = run.m.tables.map(t => closure.has(t.relation) ? { ...t, state: 'pending' as const, batches: 0 } : t);+}++/** Lock-gap re-check: a resumed run before the tombstone recomputes source digests; any change returns it to the drain. */+async function lockGapRecheck(run: Run): Promise<void> {+ const state = run.m.state;+ if (!run.m.sourceReceipts?.length || STATE_RANK[state] < STATE_RANK.copying || STATE_RANK[state] > STATE_RANK.cutover) return;+ const changed = changedRelations(run.m.sourceReceipts, await sourceReceipts(run));+ const failed = state === 'verify_failed' ? (run.m.verifyFailures ?? []).map(f => f.relation).filter(Boolean) : [];+ if (!changed.length && !failed.length) return;+ await markForRecopy(run, [...changed, ...failed]);+ progress(run, { phase: 'lock_gap', message: changed.length ? `source changed while unlocked: ${changed.join(', ')}` : `re-copying ${failed.join(', ')}` });+ if (state === 'cutover') await withGraduationRun(run.source!, run.m.runId, tx => setSourceState(tx, run.m.runId, 'quiesced'), { readWrite: true });+ const row = await readGraduationRow(run.main!);+ if (row?.run_id === run.m.runId && (row.state === 'verifying' || row.state === 'verified')) {+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'copying'));+ }+ advance(run, changed.length ? 'draining' : 'copying');+}++async function stepRecord(run: Run): Promise<void> {+ await withGraduationRun(run.source!, run.m.runId, tx => setSourceState(tx, run.m.runId, 'quiesced', { sourceBrainId: run.m.source.brainId || null, sourceDataDir: run.dataDir }), { readWrite: true });+ advance(run, 'quiesced');+ await pauseSeam(run, 'quiesced');+}++async function stepDrain(run: Run): Promise<void> {+ if (run.m.state !== 'draining') advance(run, 'draining');+ await pauseSeam(run, 'draining');+ const started = Date.now();+ const timeoutMs = run.opts.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;+ const { blockers } = await run.deps.drainForGraduation(run.source!, { timeoutMs, hostId: run.m.source.hostId, config: run.opts.config ?? loadConfigFileOnly() ?? ({ engine: 'pglite' } as GBrainConfig) });+ if (blockers.length) throw drainTimeoutError(run, blockers, timeoutMs);+ await run.deps.freezeSource(run.source!);+ const receipts = await sourceReceipts(run);+ if (run.m.sourceReceipts?.length) await markForRecopy(run, changedRelations(run.m.sourceReceipts, receipts));+ run.m.sourceReceipts = receipts;+ run.m.timings = { ...run.m.timings, drain_ms: Date.now() - started };+ save(run);+}++function drainTimeoutError(run: Run, blockers: readonly GraduationBlocker[], timeoutMs: number): OperationError {+ const personal = blockers.find(b => b.needsUser);+ if (personal) return blockerRefusal(personal, run);+ const doubled = String(Math.ceil((timeoutMs * 2) / 1000));+ return graduationError('graduation_drain_timeout', `The drain did not finish within ${Math.round(timeoutMs / 1000)} s; ${blockers.length} blocker(s) are still progressing.`,+ `Rerun with a longer drain: \`gbrain migrate --resume --drain-timeout ${doubled}\`. Nothing was copied yet and the source stays authoritative and writable.`,+ 'Queued and running requests must reach a terminal state before the copy, so their outcomes carry verbatim.',+ { argv: ['gbrain', 'migrate', '--resume', '--drain-timeout', doubled], consent: [], actor: 'agent', requires_exclusive: true,+ why: 'Resumes the run and drains again with twice the time.', verify: { argv: STATUS_ARGV } },+ blockers.map(b => `${b.kind}:${b.id}`).join(','));+}++/** Step 4: route cross-check, read-only emptiness, schema, target row `copying`, fence, emptiness again under the fence. */+async function stepFenceTarget(run: Run, opts: { force?: boolean }): Promise<void> {+ const { main, ddl } = run as Required<Pick<Run, 'main' | 'ddl'>>;+ await run.deps.crossCheckRoutes(main!, ddl!, run.m.runId);+ const existing = await readGraduationRow(main!);+ const ours = existing?.role === 'target' && existing.run_id === run.m.runId;+ const reuse = !!opts.force && existing?.role === 'target' && existing.state === 'abandoned';+ if (!ours) {+ const routes = { ...run.m.routes, mainUrl: run.m.targetUrls!.main, ddlUrl: run.m.targetUrls!.ddl };+ if (existing && !reuse) throw targetNotEmptyError(run, `it records graduation run ${existing.run_id} (${existing.state})`);+ if (!existing && !probeTargetEmpty(await run.deps.probeTarget(routes)) && !opts.force) throw targetNotEmptyError(run, 'it already holds gbrain data');+ await run.deps.initTargetSchema(ddl!, run.source!);+ await withGraduationRun(main!, existing?.run_id ?? run.m.runId, tx => setTargetState(tx, run.m.runId, 'copying', { sourceBrainId: run.m.source.brainId || null, sourceDataDir: run.dataDir, triggerBypass: run.m.triggerBypass }, { reuse }));+ await installGraduationFence(ddl!, run.m.runId);+ if (!opts.force && !probeTargetEmpty(await run.deps.probeTarget(routes))) throw targetNotEmptyError(run, 'rows appeared while the schema was bootstrapped');+ if (opts.force) await wipeUncopiedTables(run);+ return;+ }+ if ((await graduationFenceStatus(ddl!)).unfenced.length && existing!.state !== 'authoritative') await installGraduationFence(ddl!, run.m.runId);+}++/** `--force`: clear the tables the copy does not replace (rebuild and discard classes); carried tables are replaced by the copy. */+async function wipeUncopiedTables(run: Run): Promise<void> {+ const relations = run.deps.inventory.entries.filter(e => (e.class === 'rebuild' || e.class === 'discard') && e.engines.postgres && e.kind === 'table').map(e => e.relation);+ await withGraduationRun(run.main!, run.m.runId, async tx => {+ const present = await tx.executeRaw<{ q: string }>(`SELECT quote_ident(c.relname) AS q FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relkind = 'r' AND c.relname = ANY($1::text[])`, [relations]);+ if (present.length) await tx.executeRaw(`TRUNCATE ${present.map(r => r.q).join(', ')}`);+ });+}++function targetNotEmptyError(run: Run, why: string): OperationError {+ return graduationError('graduation_target_not_empty', `The target database is not empty: ${why}.`,+ 'Ask the user to pick an empty database, or to approve `--force` after the plan lists what it deletes.',+ 'Graduation copies into an empty database (or one only this run wrote) so nothing foreign is merged into the brain.',+ { argv: [...planArgv(run), '--force'], consent: ['destructive'], actor: 'agent', requires_exclusive: false,+ why: 'Shows what a forced run would delete from the target, so the user can decide.', verify: { argv: planArgv(run) } });+}++/** Step 5: per-table copy with manifest checkpoints, then sequences, deferred indexes and trigger re-enable. */+async function stepCopy(run: Run): Promise<void> {+ if (run.m.state !== 'copying') advance(run, 'copying');+ const row = await readGraduationRow(run.main!);+ if (row?.state === 'verifying' || row?.state === 'verified' || row?.state === 'verify_failed') {+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'copying'));+ }+ await pauseSeam(run, 'copying');+ const started = Date.now();+ const engines = { source: run.source!, target: run.main! };+ const order = await run.deps.copyOrder(run.source!, run.deps.inventory);+ const known = new Map(run.m.tables.map(t => [t.relation, t]));+ run.m.tables = order.map(e => known.get(e.relation) ?? { relation: e.relation, state: 'pending', batches: 0, disabledTriggers: false });+ save(run);+ const pending = order.filter(e => !['copied', 'verified'].includes(known.get(e.relation)?.state ?? 'pending'));+ if (pending.length) await run.deps.deferIndexes(run.main!);+ let done = order.length - pending.length;+ for (const entry of pending) {+ setCheckpoint(run, entry.relation, { state: 'copying', batches: 0, disabledTriggers: run.m.triggerBypass === 'disable_trigger' });+ let batches = 0;+ await run.deps.copyTable(engines, entry, { bypass: run.m.triggerBypass, batchBytes: run.opts.batchBytes, runId: run.m.runId,+ onBatch: rows => { batches += 1; progress(run, { phase: 'copy', relation: entry.relation, rows, done, total: order.length }); } });+ setCheckpoint(run, entry.relation, { state: 'copied', batches });+ done += 1;+ await pauseSeam(run, 'copy_table');+ }+ await run.deps.copySequences(engines);+ if (pending.length) await run.deps.buildDeferredIndexes(run.main!);+ const disabled = run.m.tables.filter(t => t.disabledTriggers).map(t => t.relation);+ if (disabled.length) {+ await run.deps.reenableTriggers(run.main!, disabled);+ run.m.tables = run.m.tables.map(t => ({ ...t, disabledTriggers: false }));+ }+ run.m.timings = { ...run.m.timings, copy_ms: (run.m.timings.copy_ms ?? 0) + Date.now() - started };+ save(run);+}++function setCheckpoint(run: Run, relation: string, patch: Partial<TableCheckpoint>): void {+ run.m.tables = run.m.tables.map(t => t.relation === relation ? { ...t, ...patch } : t);+ save(run);+}++/** Step 6: verify with the target fenced; only a passing verify writes `verified`. */+async function stepVerify(run: Run): Promise<void> {+ const prior = run.m.verifyFailures ?? [];+ if (run.m.state !== 'verifying') advance(run, 'verifying');+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'verifying'));+ await pauseSeam(run, 'verifying');+ const started = Date.now();+ await run.deps.assertRelationSet(run.main!, 'postgres', run.deps.inventory);+ const result = await run.deps.verifyGraduation({ source: run.source!, target: run.main! }, {+ inventory: run.deps.inventory, sourceReceipts: run.m.sourceReceipts ?? [], replayRequestId: run.m.replayRequestId ?? undefined,+ runDoctor: () => run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main),+ });+ const timings = { ...run.m.timings, verify_ms: Date.now() - started };+ if (!result.ok) {+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'verify_failed', { tableReceipts: result.tables, replayProbe: result.replay, timings, doctor: { target: result.doctorFailingChecks } }));+ advance(run, 'verify_failed', { verifyFailures: result.failures, timings });+ const repeated = result.failures.some(f => prior.some(p => p.relation === f.relation && p.kind === f.kind));+ const first = result.failures[0];+ throw graduationError('graduation_verify_failed',+ `Verify failed: ${result.failures.map(f => `${f.relation} (${f.kind}${f.firstKey ? ` at ${f.firstKey}` : ''}${f.column ? `, column ${f.column}` : ''})`).join('; ')}.`,+ repeated ? 'The same mismatch repeated after a re-copy: report it with the detail below. `gbrain migrate --rollback-to-source` discards the target and keeps the source.'+ : 'Run `gbrain migrate --resume`; it re-copies the mismatched tables with their dependants and verifies again. The source stays authoritative and writable.',+ first ? `Verify sub-cause ${first.kind}: ${first.detail}` : 'Verify reported a failure.',+ repeated ? { consent: [], actor: 'agent', requires_exclusive: false, why: 'A repeated mismatch is a gbrain bug: report it with the table, first key and column; the source is untouched.' }+ : { argv: ['gbrain', 'migrate', '--resume'], consent: [], actor: 'agent', requires_exclusive: true, why: 'Re-copies the mismatched tables once and verifies again.', verify: { argv: STATUS_ARGV } },+ JSON.stringify(result.failures.slice(0, 20)));+ }+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'verified', { tableReceipts: result.tables, replayProbe: result.replay, timings, triggerBypass: run.m.triggerBypass, doctor: { target: result.doctorFailingChecks } }));+ run.m.tables = run.m.tables.map(t => ({ ...t, state: 'verified' as const }));+ advance(run, 'verified', { verifyFailures: [], timings });+ await pauseSeam(run, 'verified');+}++/** Step 7a: re-apply sequences, fence the source (`cutover`), close it keeping the lock, move aside, tombstone. */+async function stepCutover(run: Run): Promise<void> {+ await run.deps.copySequences({ source: run.source!, target: run.main! });+ const [brain] = await run.source!.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton = 1');+ const [seq] = await run.source!.executeRaw<{ s: string }>('SELECT COALESCE(max(sequence), 0)::text AS s FROM persistence_requests');+ const row = await readGraduationRow(run.source!);+ if (row?.state !== 'cutover') await withGraduationRun(run.source!, run.m.runId, tx => setSourceState(tx, run.m.runId, 'cutover', { cutoverSequence: seq?.s ?? '0' }), { readWrite: true });+ if (run.m.state !== 'cutover') advance(run, 'cutover', { sourceEnabled: brain?.enabled === true, cutoverSequence: seq?.s ?? '0' });+ await pauseSeam(run, 'cutover');+ const source = run.source!;+ run.lock = await source.closeRetainingLock();+ run.source = null;+ await source.disconnect();+ await pauseSeam(run, 'before_rename');+ moveAsideHeld(run.dataDir, run.lock, run.m.runId);+ await pauseSeam(run, 'after_rename');+ await tombstoneUnderLock(run);+}++async function tombstoneUnderLock(run: Run): Promise<void> {+ const movedTo = graduatedPath(run.dataDir, run.m.runId);+ const existing = readTombstone(run.dataDir);+ if (!(existing && existing.runId === run.m.runId)) {+ try {+ writeTombstone(run.dataDir, {+ kind: 'gbrain-engine-graduated', runId: run.m.runId, brainId: run.m.source.brainId, movedTo, target: run.m.target,+ targetDisplayUrl: targetDisplayUrl(run.m.target), graduatedAt: new Date().toISOString(),+ fixArgv: ['gbrain', 'config', 'set', 'database_url', '<GBRAIN_TARGET_URL>'],+ });+ } catch (error) {+ if (error instanceof TombstonePathOccupiedError) throw graduationSplitBrainError(inspectGraduationPath(run.dataDir));+ throw error;+ }+ }+ advance(run, 'tombstoned', { graduatedAt: run.m.graduatedAt ?? new Date().toISOString() });+ await pauseSeam(run, 'tombstoned');+}++/** Step 7b: one target transaction grants authority (persistence enabled as on the source) and drops the fence. */+async function stepAuthority(run: Run): Promise<void> {+ const state = inspectGraduationPath(run.dataDir);+ if (state.kind === 'split_brain' || readTombstone(run.dataDir)?.runId !== run.m.runId) throw graduationSplitBrainError(state);+ await openTargets(run);+ await withGraduationRun(run.main!, run.m.runId, async tx => {+ await tx.executeRaw('UPDATE persistence_brain SET enabled = $1 WHERE singleton = 1', [run.m.sourceEnabled === true]);+ await dropGraduationFence(tx);+ await setTargetState(tx, run.m.runId, 'authoritative', { cutoverSequence: run.m.cutoverSequence ?? '0', graduatedAt: 'now', timings: run.m.timings });+ });+ advance(run, 'authoritative');+ await pauseSeam(run, 'authoritative');+}++/** Step 8: routing flip, registry/mount rewrite, manifest `graduated`, then the caller releases lock and pause marker. */+async function stepFlip(run: Run): Promise<void> {+ const file = loadConfigFileOnly() ?? run.opts.config ?? ({ engine: 'pglite' } as GBrainConfig);+ const next = { ...file, engine: 'postgres' as const, database_url: run.m.targetUrls!.main };+ delete (next as { database_path?: string }).database_path;+ saveConfig(next as GBrainConfig);+ const mounts = rewriteMounts(run.deps.mountsPath(), mount => mount.engine === 'pglite' && !!mount.database_path && graduationDataDir(mount.database_path) === run.dataDir,+ mount => { const { database_path: _p, ...rest } = mount; return { ...rest, engine: 'postgres', database_url: run.m.targetUrls!.main }; });+ await pauseSeam(run, 'routing_flipped');+ advance(run, 'graduated', { rewrittenMounts: [...new Set([...(run.m.rewrittenMounts ?? []), ...mounts])] });+}++interface MountRecord { id: string; engine: string; database_path?: string; database_url?: string; [key: string]: unknown }++function rewriteMounts(path: string, match: (m: MountRecord) => boolean, rewrite: (m: MountRecord) => MountRecord): string[] {+ if (!existsSync(path)) return [];+ const file = JSON.parse(readFileSync(path, 'utf8')) as { version: number; mounts?: MountRecord[] };+ const ids: string[] = [];+ const mounts = (file.mounts ?? []).map(m => { if (!match(m)) return m; ids.push(m.id); return rewrite(m); });+ if (ids.length) writeFileDurably(path, `${JSON.stringify({ ...file, mounts }, null, 2)}\n`);+ return ids;+}++async function receiptOf(run: Run): Promise<GraduationReceipt> {+ if (!run.main) await openTargets(run);+ const row = await readGraduationRow(run.main!);+ return { runId: run.m.runId, state: (row?.state ?? 'authoritative') as GraduationReceipt['state'], tables: row?.table_receipts ?? [],+ triggerBypass: run.m.triggerBypass, replay: row?.replay_probe ?? { status: 'not_available', reason: 'no_uncompacted_request' }, timings: run.m.timings };+}++async function takeKernelLock(run: Run): Promise<void> {+ if (run.lock) return;+ const movedTo = graduatedPath(run.dataDir, run.m.runId);+ run.lock = await acquireKernelLockOnly(run.dataDir, { lockDir: join(existsSync(movedTo) ? movedTo : run.dataDir, '.gbrain-lock'), timeoutMs: run.opts.handoffTimeoutMs ?? HANDOFF_TIMEOUT_MS });+}++/** Continue a run from its recorded state to `graduated`. */+async function continueRun(run: Run, opts: { force?: boolean } = {}): Promise<GraduationReceipt> {+ if (run.m.state === 'cutover') {+ const path = inspectGraduationPath(run.dataDir);+ if (path.kind === 'split_brain') throw graduationSplitBrainError(path);+ const tombstone = readTombstone(run.dataDir);+ if (tombstone?.runId === run.m.runId || (!existsSync(run.dataDir) && path.movedTo)) {+ await claimPause(run);+ await takeKernelLock(run);+ await tombstoneUnderLock(run);+ }+ }+ if (STATE_RANK[run.m.state] < STATE_RANK.tombstoned) {+ if (run.m.state !== 'planned' || !run.source) await quiesceResume(run);+ if (run.m.state === 'planned') await stepRecord(run);+ await stepFenceTargetIfStarted(run, opts);+ await lockGapRecheck(run);+ if (run.m.state === 'quiesced' || run.m.state === 'draining') await stepDrain(run);+ else await run.deps.freezeSource(run.source!);+ if (STATE_RANK[run.m.state] <= STATE_RANK.draining) await stepFenceTarget(run, opts);+ if (STATE_RANK[run.m.state] <= STATE_RANK.copying || run.m.state === 'verify_failed') await stepCopy(run);+ if (run.m.state === 'copying' || run.m.state === 'verifying') await stepVerify(run);+ await stepCutover(run);+ }+ if (run.m.state === 'tombstoned') { await claimPause(run); await takeKernelLock(run); await stepAuthority(run); }+ if (run.m.state === 'authoritative') { await claimPause(run); await takeKernelLock(run); await stepFlip(run); }+ return receiptOf(run);+}++/** Past the fence step the target row must stay fenced; reconnect and repair before the lock-gap re-check reads it. */+async function stepFenceTargetIfStarted(run: Run, opts: { force?: boolean }): Promise<void> {+ if (STATE_RANK[run.m.state] > STATE_RANK.draining) await stepFenceTarget(run, opts);+}++function newManifest(input: PlanInputs, expect: string, runId: string): GraduationManifest {+ const now = new Date().toISOString();+ return {+ version: GRADUATION_MANIFEST_VERSION, runId, state: 'planned',+ source: { dataDir: sourceDataDir(input.config), brainId: '', hostId: '' }, target: input.target,+ routes: { main: input.routes.main, ddl: input.routes.ddl, ...(input.routes.urlEnv ? { urlEnv: input.routes.urlEnv } : {}) },+ inventoryVersion: 0, schemaVersion: LATEST_VERSION, planHash: expect, triggerBypass: input.triggerBypassOverride ?? 'session_replication_role',+ tables: [], timings: {}, startedAt: now, updatedAt: now,+ targetUrls: { main: input.routes.mainUrl, ddl: input.routes.ddlUrl }, invokedAs: input.invokedAs, force: input.force,+ };+}++/** Abandon a run that never fenced anything (refused at step 1): the source stays exactly as it was. */+function abandonUnstarted(run: Run): void {+ try { transitionManifest(run.m, 'abandoned'); writeGraduationManifest(run.m, run.path); } catch { /* best effort */ }+ try { removeIntentMarker(run.dataDir); } catch { /* best effort */ }+}++/**+ * Run the approved graduation end to end. Refusals before the fence leave+ * the source unchanged and writable; a drain timeout or verify failure is+ * resumable with `resumeGraduation`.+ */+export async function runGraduation(opts: GraduationRunOptions): Promise<GraduationReceipt> {+ const path = opts.manifestPath ?? graduationManifestPath();+ const existing = readGraduationManifest(path);+ if (existing && !TERMINAL_STATES.has(existing.state)) throw existingRunError(existing);+ const deps = { ...defaultGraduationDeps(), ...opts.deps };+ const input = planInputs(deps, opts);+ const dataDir = sourceDataDir(opts.config);+ refuseOnPathState(inspectGraduationPath(dataDir));+ if (existing) renameSync(path, `${path.replace(/\.json$/, '')}.${existing.runId}.json`);+ const manifest = newManifest(input, opts.expect, randomUUID());+ manifest.inventoryVersion = deps.inventory.version;+ const run = newRun(manifest, path, { ...opts, deps });+ try {+ try { await quiesceFresh(run, input, opts.expect); }+ catch (error) { abandonUnstarted(run); throw error; }+ return await continueRun(run, { force: opts.force });+ } finally { await cleanup(run); }+}++function existingRunError(m: GraduationManifest): OperationError {+ const marker = (() => { try { return readIntentMarker(m.source.dataDir); } catch { return null; } })();+ if (marker && markerLiveness(marker) === 'alive') return graduationInProgressError({ runId: m.runId, state: m.state, where: 'source' });+ return graduationInterruptedError({ runId: m.runId, state: m.state, detail: 'Finish it with `gbrain migrate --resume` or discard it with `gbrain migrate --rollback-to-source` before starting another.' });+}++function loadRun(opts: CommonOptions & { url?: string; urlEnv?: string }): Run {+ const path = opts.manifestPath ?? graduationManifestPath();+ const m = readGraduationManifest(path);+ if (!m) {+ throw opError('not_found', 'No graduation run is recorded on this machine.',+ 'Start one with the plan command: `gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --plan --json`.',+ { why: 'Resume, rollback and reconcile act on the run recorded in the graduation manifest.',+ fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--plan', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the read-only graduation plan.' } });+ }+ const run = newRun(m, path, opts);+ if (opts.url || opts.urlEnv) {+ const routes = run.deps.resolveTargetRoutes({ url: opts.url, urlEnv: opts.urlEnv, env: opts.env ?? process.env });+ if (run.deps.targetIdentity(routes.mainUrl).id !== m.target.id) {+ run.unregister();+ throw opError('invalid_params', 'The given target is not the database this run recorded.',+ 'Drop --url/--url-env to use the recorded target, or pass a URL for the same host, port, database and user.',+ { why: 'A run continues against the target identity recorded in its manifest.', fix: { argv: STATUS_ARGV, consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the recorded target (redacted).' } });+ }+ m.targetUrls = { main: routes.mainUrl, ddl: routes.ddlUrl };+ if (routes.urlEnv) m.routes = { ...m.routes, urlEnv: routes.urlEnv };+ writeGraduationManifest(m, path);+ }+ return run;+}++/** Continue the recorded run from its first incomplete step (reconciling first). */+export async function resumeGraduation(opts: GraduationResumeOptions = {}): Promise<GraduationReceipt> {+ const run = loadRun(opts);+ try {+ await reconcileRun(run);+ if (run.m.state === 'graduated') return await receiptOf(run);+ if (STATE_RANK[run.m.state] >= STATE_RANK.rollback_fenced) throw existingRunError(run.m);+ return await continueRun(run, { force: run.m.force });+ } finally { await cleanup(run); }+}++// ── reconciliation ─────────────────────────────────────────────────────────++export interface ReconcileResult { state: ManifestState | 'none'; actions: readonly string[]; detail: string }++async function reconcileRun(run: Run): Promise<ReconcileResult> {+ const actions: string[] = [];+ const path = inspectGraduationPath(run.dataDir);+ if (path.kind === 'split_brain') throw graduationSplitBrainError(path);+ if (run.m.state === 'rollback_fenced') {+ if (run.m.rollbackFrom === 'authoritative' || run.m.rollbackFrom === 'graduated') { await returnToAuthority(run); actions.push('returned target to authority'); }+ else { await approveAndRestore(run); actions.push('finished rollback'); }+ } else if (run.m.state === 'rollback_approved' || run.m.state === 'source_restoring') {+ await finishRollback(run);+ actions.push('finished rollback');+ } else if (STATE_RANK[run.m.state] >= STATE_RANK.copying && STATE_RANK[run.m.state] <= STATE_RANK.tombstoned && run.m.state !== 'cutover' || run.m.state === 'cutover') {+ await openTargets(run);+ const row = await readGraduationRow(run.main!);+ if (row?.role === 'target' && row.run_id === run.m.runId && row.state !== 'authoritative' && (await graduationFenceStatus(run.ddl!)).unfenced.length) {+ await installGraduationFence(run.ddl!, run.m.runId);+ actions.push('re-installed target fence');+ }+ }+ return { state: run.m.state, actions, detail: actions.join('; ') };+}++/** Repair after a crash: fence re-install, rollback roll-forward or return to authority. Never starts a move. */+export async function reconcileGraduation(opts: CommonOptions = {}): Promise<ReconcileResult> {+ const path = opts.manifestPath ?? graduationManifestPath();+ if (!readGraduationManifest(path)) return { state: 'none', actions: [], detail: '' };+ const run = loadRun(opts);+ try { return await reconcileRun(run); } finally { await cleanup(run); }+}++// ── rollback ───────────────────────────────────────────────────────────────++export interface RollbackLoss {+ relation: string;+ lossKind: LossKind;+ change: 'changed' | 'added' | 'missing' | 'requests_after_cutover';+ rows: number;+ /** Withdrawals and security changes are never confirmable (nothing is written back to the source). */+ final: boolean;+}++export interface GraduationRollbackResult { runId: string; state: 'rolled_back' | 'abandoned'; dropped: readonly RollbackLoss[] }++/**+ * Roll back to the source. Before cutover: mark the target abandoned (it keeps+ * its fence) and release the source. After cutover: fence the target+ * (`rollback_fenced`), take the kernel lock, then compare; withdrawals and+ * security changes refuse finally, other user-data loss needs+ * `--yes --expect <hash>`; a refusal returns the target to authority.+ */+export async function rollbackGraduation(opts: GraduationRollbackOptions = {}): Promise<GraduationRollbackResult> {+ const run = loadRun(opts);+ try {+ await reconcileRun(run);+ const state = run.m.state;+ if (state === 'rolled_back' || state === 'abandoned') return { runId: run.m.runId, state, dropped: [] };+ if (STATE_RANK[state] <= STATE_RANK.verified) return await rollbackBeforeCutover(run);+ return await rollbackAfterCutover(run, opts);+ } finally { await cleanup(run); }+}++async function rollbackBeforeCutover(run: Run): Promise<GraduationRollbackResult> {+ writeIntentMarker(run.dataDir, markerFor(run));+ await claimPause(run);+ await openSourceUnderLock(run);+ const sourceRow = await readGraduationRow(run.source!);+ if (sourceRow?.run_id === run.m.runId && sourceRow.state === 'quiesced') {+ await withGraduationRun(run.source!, run.m.runId, tx => setSourceState(tx, run.m.runId, 'rolled_back'), { readWrite: true });+ }+ if (STATE_RANK[run.m.state] >= STATE_RANK.draining) {+ await openTargets(run);+ const row = await readGraduationRow(run.main!);+ if (row?.role === 'target' && row.run_id === run.m.runId && row.state !== 'abandoned') {+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'abandoned'));+ await installGraduationFence(run.ddl!, run.m.runId);+ }+ }+ advance(run, 'abandoned');+ return { runId: run.m.runId, state: 'abandoned', dropped: [] };+}++async function rollbackAfterCutover(run: Run, opts: GraduationRollbackOptions): Promise<GraduationRollbackResult> {+ const from = run.m.state;+ const hadAuthority = from === 'authoritative' || from === 'graduated';+ await openTargets(run);+ if (hadAuthority) {+ const carried = run.deps.inventory.entries.filter(e => (e.class === 'carry' || e.class === 'rebind') && e.engines.postgres && e.kind === 'table').map(e => e.relation);+ await withGraduationRun(run.main!, run.m.runId, async tx => {+ await setTargetState(tx, run.m.runId, 'rollback_fenced');+ await installGraduationFence(tx, run.m.runId);+ const present = await tx.executeRaw<{ q: string }>(`SELECT quote_ident(c.relname) AS q FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relkind = 'r' AND c.relname = ANY($1::text[])`, [carried]);+ if (present.length) await tx.executeRaw(`LOCK TABLE ${present.map(r => r.q).join(', ')} IN EXCLUSIVE MODE`);+ });+ }+ advance(run, 'rollback_fenced', { rollbackFrom: from });+ await pauseSeam(run, 'rollback_fenced');+ let losses: RollbackLoss[] = [];+ try {+ await claimPause(run);+ await takeKernelLock(run);+ if (hadAuthority) losses = await detectRollbackLosses(run);+ } catch (error) {+ if (hadAuthority) await returnToAuthority(run);+ throw error;+ }+ const final = losses.filter(l => l.final);+ if (final.length) {+ await returnToAuthority(run);+ throw rollbackLostError(run, final, null);+ }+ const confirmable = losses.filter(l => l.lossKind !== 'operational');+ if (confirmable.length) {+ const hash = lossHash(run.m.runId, confirmable);+ if (!(opts.yes && opts.expect === hash)) {+ await returnToAuthority(run);+ throw rollbackLostError(run, confirmable, hash);+ }+ }+ await approveAndRestore(run);+ return { runId: run.m.runId, state: 'rolled_back', dropped: losses };+}++async function approveAndRestore(run: Run): Promise<void> {+ const row = run.main ? await readGraduationRow(run.main) : null;+ if (row?.run_id === run.m.runId && row.state === 'rollback_fenced') {+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'rollback_approved'));+ }+ advance(run, 'rollback_approved');+ await pauseSeam(run, 'rollback_approved');+ await finishRollback(run);+}++/** After approval, reconciliation only rolls forward: restore the datastore, reset the source row, flip routing back. */+async function finishRollback(run: Run): Promise<void> {+ await openTargets(run);+ await claimPause(run);+ await takeKernelLock(run);+ const row = await readGraduationRow(run.main!);+ const authorityPath = row?.run_id === run.m.runId && ['rollback_approved', 'source_restoring'].includes(row.state);+ if (authorityPath && row!.state === 'rollback_approved') await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'source_restoring'));+ if (run.m.state !== 'source_restoring') advance(run, 'source_restoring');+ await pauseSeam(run, 'source_restoring');+ const movedTo = graduatedPath(run.dataDir, run.m.runId);+ if (readTombstone(run.dataDir)) removeTombstone(run.dataDir, run.m.runId);+ if (existsSync(movedTo)) {+ if (existsSync(run.dataDir)) throw graduationSplitBrainError(inspectGraduationPath(run.dataDir));+ moveHeldPglite(movedTo, run.dataDir, run.lock!);+ }+ const source = await run.deps.newSourceEngine();+ await source.connectWithHeldLock({ engine: 'pglite', database_path: run.dataDir }, run.lock!);+ run.lock = null;+ run.source = source;+ const sourceRow = await readGraduationRow(source);+ if (sourceRow?.run_id === run.m.runId && sourceRow.state !== 'rolled_back') {+ await withGraduationRun(source, run.m.runId, tx => setSourceState(tx, run.m.runId, 'rolled_back'), { readWrite: true });+ }+ const file = loadConfigFileOnly();+ if (file && file.engine === 'postgres') {+ const next = { ...file, engine: 'pglite' as const, database_path: run.dataDir };+ delete (next as { database_url?: string }).database_url;+ saveConfig(next as GBrainConfig);+ }+ const ids = new Set(run.m.rewrittenMounts ?? []);+ rewriteMounts(run.deps.mountsPath(), mount => ids.has(mount.id) && mount.engine === 'postgres',+ mount => { const { database_url: _u, ...rest } = mount; return { ...rest, engine: 'pglite', database_path: run.dataDir }; });+ const target = await readGraduationRow(run.main!);+ if (target?.run_id === run.m.runId) {+ if (target.state === 'source_restoring') await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'rolled_back'));+ else if (target.state === 'verified' || target.state === 'verifying' || target.state === 'copying' || target.state === 'verify_failed') {+ await withGraduationRun(run.main!, run.m.runId, tx => setTargetState(tx, run.m.runId, 'abandoned'));+ }+ if ((await graduationFenceStatus(run.ddl!)).unfenced.length) await installGraduationFence(run.ddl!, run.m.runId);+ }+ advance(run, 'rolled_back');+ fsyncParent(run.dataDir);+}++/** Any refusal, decline or timeout returns the target from `rollback_fenced` to authority, dropping the fence in the same transaction. */+async function returnToAuthority(run: Run): Promise<void> {+ await openTargets(run);+ await withGraduationRun(run.main!, run.m.runId, async tx => {+ const row = await readGraduationRow(tx);+ if (row?.state === 'rollback_fenced') await setTargetState(tx, run.m.runId, 'authoritative');+ await dropGraduationFence(tx);+ });+ const back = run.m.rollbackFrom === 'graduated' ? 'graduated' : 'authoritative';+ if (run.m.state === 'rollback_fenced') advance(run, back);+ if (run.lock) { const lock = run.lock; run.lock = null; await releaseLock(lock); }+}++function lossHash(runId: string, losses: readonly RollbackLoss[]): string {+ return planHashOf({ runId, losses: losses.map(l => `${l.relation}:${l.change}:${l.rows}`).sort() });+}++function rollbackLostError(run: Run, losses: readonly RollbackLoss[], hash: string | null): OperationError {+ const list = losses.map(l => `${l.relation}: ${l.rows} ${l.change} (${l.lossKind})`).join('; ');+ if (!hash) {+ return graduationError('graduation_rollback_writes_lost',+ `Rollback refused: the target has withdrawals or security changes since cutover that the source does not have (${list}).`,+ 'Stay on Postgres: the target is authoritative again and keeps every change. Report this if the user still needs the PGLite copy; nothing is ever written back to the source.',+ 'Rolling back would resurrect withdrawn facts or revoked credentials, so it is refused even with --yes.',+ { consent: [], actor: 'agent', requires_exclusive: false, why: 'Forward recovery on the target is the only safe path; report the listed changes.' }, list);+ }+ return graduationError('graduation_rollback_writes_lost',+ `Rolling back would drop changes made on the target since cutover: ${list}.`,+ 'Ask the user whether to drop those changes; after they agree, run the command in fix. The target is authoritative again until then.',+ 'Nothing is written back to the source, so changes made on Postgres after cutover are lost by a rollback.',+ { argv: ['gbrain', 'migrate', '--rollback-to-source', '--yes', '--expect', hash], consent: ['destructive'], actor: 'agent', requires_exclusive: true,+ plan_hash: hash, why: 'Rolls back to the PGLite source and drops the listed target changes.', verify: { argv: STATUS_ARGV },+ user_message: `Rolling back to PGLite drops these changes made since the move: ${list}. Should I roll back?` }, list);+}++async function detectRollbackLosses(run: Run): Promise<RollbackLoss[]> {+ const losses: RollbackLoss[] = [];+ const row = await readGraduationRow(run.main!);+ const receipts = new Map((row?.table_receipts ?? []).map(r => [r.relation, r]));+ const securityNames = new Set<string>(SECURITY_TABLES);+ for (const entry of run.deps.inventory.entries) {+ if (!(entry.class === 'carry' || entry.class === 'rebind') || !entry.engines.postgres || securityNames.has(entry.relation)) continue;+ const before = receipts.get(entry.relation);+ if (!before) continue;+ const now = await run.deps.digestTable(run.main!, entry);+ if (now.rootSha256 !== before.rootSha256) {+ losses.push({ relation: entry.relation, lossKind: entry.lossKind, change: 'changed', rows: Math.abs(now.rows - before.rows) || now.rows, final: false });+ }+ }+ const [after] = await run.main!.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM persistence_requests WHERE sequence > $1::bigint', [run.m.cutoverSequence ?? '0']);+ if (Number(after?.n ?? 0) > 0) losses.push({ relation: 'persistence_requests', lossKind: 'user_data', change: 'requests_after_cutover', rows: Number(after!.n), final: false });+ losses.push(...await compareSecurityState(run));+ return losses;+}++async function primaryKey(engine: BrainEngine, relation: string): Promise<string[]> {+ const rows = await engine.executeRaw<{ attname: string }>(+ `SELECT a.attname FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)+ WHERE i.indrelid = to_regclass($1) AND i.indisprimary ORDER BY array_position(i.indkey::int2[], a.attnum)`, [relation]);+ return rows.map(r => r.attname);+}++async function securityRows(engine: BrainEngine, relation: string): Promise<Map<string, { content: string; row: Record<string, unknown> }> | null> {+ const [present] = await engine.executeRaw<{ q: string | null }>(`SELECT CASE WHEN to_regclass($1) IS NULL THEN NULL ELSE quote_ident($1) END AS q`, [relation]);+ if (!present?.q) return null;+ const pk = await primaryKey(engine, relation);+ const rows = await engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('TimeZone', 'UTC', true)`);+ return tx.executeRaw<{ r: unknown }>(`SELECT to_jsonb(t) AS r FROM ${present.q} t`);+ });+ const canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical)+ : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value as object).sort().map(k => [k, canonical((value as Record<string, unknown>)[k])])) : value;+ const out = new Map<string, { content: string; row: Record<string, unknown> }>();+ for (const { r } of rows) {+ const row = (typeof r === 'string' ? JSON.parse(r) : r) as Record<string, unknown>;+ const key = JSON.stringify(pk.map(c => row[c]));+ const content = JSON.stringify(canonical(Object.fromEntries(Object.entries(row).filter(([k]) => !SECURITY_VOLATILE_COLUMNS.has(k)))));+ out.set(key, { content, row });+ }+ return out;+}++/** Security state by identity and content against the retained source (revocations delete rows; timestamps cannot show them). */+async function compareSecurityState(run: Run): Promise<RollbackLoss[]> {+ const movedTo = graduatedPath(run.dataDir, run.m.runId);+ if (!existsSync(movedTo)) return [];+ const retained = await run.deps.openSource(movedTo, { migrate: false });+ const losses: RollbackLoss[] = [];+ try {+ const nowSeconds = Math.floor(Date.now() / 1000);+ for (const relation of SECURITY_TABLES) {+ const [source, target] = [await securityRows(retained, relation), await securityRows(run.main!, relation)];+ if (!source || !target) continue;+ let missing = 0, changed = 0, added = 0;+ for (const [key, value] of source) {+ const other = target.get(key);+ if (!other) {+ const expires = Number(value.row.expires_at);+ if (relation === 'oauth_tokens' && Number.isFinite(expires) && expires > 0 && expires < nowSeconds) continue;+ missing += 1;+ } else if (other.content !== value.content) changed += 1;+ }+ for (const key of target.keys()) if (!source.has(key)) added += 1;+ const withdrawal = relation === 'fact_withdrawals';+ if (missing) losses.push({ relation, lossKind: withdrawal ? 'user_data' : 'security', change: 'missing', rows: missing, final: true });+ if (changed) losses.push({ relation, lossKind: withdrawal ? 'user_data' : 'security', change: 'changed', rows: changed, final: true });+ if (added) losses.push({ relation, lossKind: withdrawal ? 'user_data' : 'security', change: 'added', rows: added, final: withdrawal });+ }+ } finally { await retained.disconnect(); }+ return losses;+}++// ── status ─────────────────────────────────────────────────────────────────++/** `gbrain migrate --status`: files only; never reconciles, migrates, repairs fences, rewrites routing or touches markers. */+export async function graduationStatus(opts: { manifestPath?: string; config?: GBrainConfig | null } = {}): Promise<GraduationStatusDoc> {+ const m = readGraduationManifest(opts.manifestPath ?? graduationManifestPath());+ const configured = opts.config === undefined ? loadConfigFileOnly() : opts.config;+ const dataDir = m?.source.dataDir ?? (configured?.engine === 'pglite' && configured.database_path ? graduationDataDir(configured.database_path) : null);+ const path = dataDir ? inspectGraduationPath(dataDir) : null;+ const live = !!path?.marker && path.liveness === 'alive';+ if (!m) {+ return { state: 'none', runId: path?.marker?.runId ?? null, manifest: null, path, targetDisplayUrl: path?.tombstone?.targetDisplayUrl ?? null, live,+ nextArgv: path?.kind === 'graduated' ? ['gbrain', 'config', 'set', 'database_url', '<GBRAIN_TARGET_URL>'] : null,+ detail: path?.detail || 'No graduation run is recorded on this machine.' };+ }+ const nextArgv = TERMINAL_STATES.has(m.state) ? null+ : path?.kind === 'split_brain' ? null+ : live ? STATUS_ARGV+ : STATE_RANK[m.state] >= STATE_RANK.rollback_fenced ? ['gbrain', 'migrate', '--rollback-to-source'] : ['gbrain', 'migrate', '--resume'];+ return { state: m.state, runId: m.runId, manifest: redactManifest(m), path, targetDisplayUrl: targetDisplayUrl(m.target), live, nextArgv,+ detail: path?.detail ?? '' };+}++export type { InventoryEntry };diff --git a/src/core/persistence/engine-graduation.types.ts b/src/core/persistence/engine-graduation.types.tsindex bf90114460..42a8d838dc 100644--- a/src/core/persistence/engine-graduation.types.ts+++ b/src/core/persistence/engine-graduation.types.ts@@ -37,11 +37,11 @@ export const MANIFEST_TRANSITIONS: Readonly<Record<ManifestState, readonly Manifplanned: ['quiesced', 'abandoned'],quiesced: ['draining', 'abandoned'],draining: ['copying', 'abandoned'],- copying: ['verifying', 'abandoned'],- verifying: ['verified', 'verify_failed', 'abandoned'],- verify_failed: ['copying', 'abandoned'],- verified: ['cutover', 'abandoned'],- cutover: ['tombstoned', 'rollback_fenced'],+ copying: ['verifying', 'abandoned', 'draining'],+ verifying: ['verified', 'verify_failed', 'abandoned', 'draining'],+ verify_failed: ['copying', 'abandoned', 'draining'],+ verified: ['cutover', 'abandoned', 'draining'],+ cutover: ['tombstoned', 'rollback_fenced', 'draining'],tombstoned: ['authoritative', 'rollback_fenced'],authoritative: ['graduated', 'rollback_fenced'],graduated: ['rollback_fenced'],@@ -54,9 +54,9 @@ export const MANIFEST_TRANSITIONS: Readonly<Record<ManifestState, readonly Manifexport const TARGET_TRANSITIONS: Readonly<Record<TargetRowState, readonly TargetRowState[]>> = {copying: ['verifying', 'abandoned'],- verifying: ['verified', 'verify_failed', 'abandoned'],+ verifying: ['verified', 'verify_failed', 'abandoned', 'copying'],verify_failed: ['copying', 'abandoned'],- verified: ['authoritative', 'abandoned'],+ verified: ['authoritative', 'abandoned', 'copying'],authoritative: ['rollback_fenced'],rollback_fenced: ['rollback_approved', 'authoritative'],rollback_approved: ['source_restoring'],@@ -67,7 +67,7 @@ export const TARGET_TRANSITIONS: Readonly<Record<TargetRowState, readonly Targetexport const SOURCE_TRANSITIONS: Readonly<Record<SourceRowState, readonly SourceRowState[]>> = {quiesced: ['cutover', 'rolled_back'],- cutover: ['rolled_back'],+ cutover: ['rolled_back', 'quiesced'],rolled_back: ['quiesced'],};@@ -166,6 +166,25 @@ export interface GraduationManifest {timings: Record<string, number>;startedAt: string;updatedAt: string;+ /** Full target URLs (main and DDL route). Only this 0600 file holds them; never printed. */+ targetUrls?: { main: string; ddl: string };+ /** The `--to` spelling the user typed; every emitted command echoes it. */+ invokedAs?: 'postgres' | 'supabase';+ /** Source snapshot receipts taken after the drain; the lock-gap re-check compares against them. */+ sourceReceipts?: readonly TableReceipt[];+ /** The request pending at run start, used by the replay probe. */+ replayRequestId?: string | null;+ /** Source persistence_brain.enabled, granted to the target in the authority transaction. */+ sourceEnabled?: boolean;+ graduatedAt?: string;+ /** Manifest state a rollback started from; reconciliation returns to it before approval. */+ rollbackFrom?: ManifestState;+ /** Failures of the last verify, re-copied (with their FK closure) by --resume. */+ verifyFailures?: readonly VerifyFailure[];+ /** The run was approved with --force (its plan hash bound the target's destructive snapshot). */+ force?: boolean;+ /** Mount ids whose database_path named the source, rewritten at the routing flip. */+ rewrittenMounts?: readonly string[];}/** Sibling intent marker `<dataDir>.gbrain-graduation.json` (mode 0600). */@@ -255,6 +274,33 @@ export interface GraduationReceipt {timings: Record<string, number>;}+/** What `inspectGraduationPath` sees at a PGLite data dir path, without opening or locking it. */+export interface GraduationPathState {+ kind: 'none' | 'in_progress' | 'interrupted' | 'graduated' | 'split_brain';+ dataDir: string;+ marker: IntentMarker | null;+ tombstone: Tombstone | null;+ /** Liveness of the marker's requesting process; null without a non-terminal marker. */+ liveness: 'alive' | 'dead' | 'unknown' | null;+ /** The `<dataDir>.graduated-<run_id>` directory when it exists. */+ movedTo: string | null;+ detail: string;+}++/** `gbrain migrate --status --json`: read-only, never reconciles. */+export interface GraduationStatusDoc {+ state: ManifestState | 'none';+ runId: string | null;+ /** The manifest without its secret URLs. */+ manifest: Omit<GraduationManifest, 'targetUrls'> | null;+ path: GraduationPathState | null;+ targetDisplayUrl: string | null;+ /** A live process owns the run (marker liveness). */+ live: boolean;+ nextArgv: readonly string[] | null;+ detail: string;+}+export interface GraduationEngines {source: BrainEngine;target: BrainEngine;diff --git a/src/core/persistence/graduation-custody.ts b/src/core/persistence/graduation-custody.tsnew file mode 100644index 0000000000..92c9884b0e--- /dev/null+++ b/src/core/persistence/graduation-custody.ts@@ -0,0 +1,421 @@+/**+ * Engine graduation filesystem custody for a PGLite data dir: the sibling+ * intent marker `<dataDir>.gbrain-graduation.json`, the regular-file+ * tombstone left at the old path after the move-aside, the lock-free path+ * inspection every opener runs, the held-lock move-aside, and the refusal+ * builders shared by the connect path and writer admission.+ *+ * Every file here is written 0600 with fsync of the file and its parent+ * directory. The marker is replaced atomically at every state change; the+ * tombstone is created once with O_CREAT|O_EXCL so an occupied path is+ * detected (`graduation_split_brain`) instead of overwritten.+ */+import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, renameSync, rmSync, unlinkSync, writeSync } from 'node:fs';+import { basename, dirname, join, resolve } from 'node:path';+import type { Action } from '../agent-output.ts';+import type { RegistryCode } from '../error-registry.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { inspectLockHolder, isProcessAlive, readBootId, readPidNs, type LockHandle } from '../pglite-lock.ts';+import { moveHeldPglite } from './maintenance.ts';+import type { BrainEngine } from '../engine.ts';+import { GRADUATION_RUN_SETTING, graduationTablePresent, readGraduationRow } from './graduation-schema.ts';+import type {+ GraduationErrorCode, GraduationPathState, IntentMarker, ManifestState, TargetIdentity, TargetRowState, Tombstone,+} from './engine-graduation.types.ts';++const MOVE_TO_POSTGRES_DOC = 'docs/guides/move-to-postgres.md';++/** Manifest states before the source is fenced; a dead run here leaves the source authoritative. */+export const PRE_CUTOVER_STATES: ReadonlySet<ManifestState> = new Set([+ 'planned', 'quiesced', 'draining', 'copying', 'verifying', 'verified', 'verify_failed',+]);+/** Terminal states: the marker no longer stops anyone. */+export const TERMINAL_STATES: ReadonlySet<ManifestState> = new Set(['graduated', 'rolled_back', 'abandoned']);++// ── paths ──────────────────────────────────────────────────────────────────++function canonical(path: string): string {+ const absolute = resolve(path);+ try { return realpathSync(absolute); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ const parent = dirname(absolute);+ if (parent === absolute) return absolute;+ return join(canonical(parent), basename(absolute));+ }+}+/** The data dir path with its parent resolved; the data dir itself may be a tombstone file or missing. */+export function graduationDataDir(dataDir: string): string {+ const absolute = resolve(dataDir);+ return join(canonical(dirname(absolute)), basename(absolute));+}+export function intentMarkerPath(dataDir: string): string {+ return `${graduationDataDir(dataDir)}.gbrain-graduation.json`;+}+export function graduatedPath(dataDir: string, runId: string): string {+ return `${graduationDataDir(dataDir)}.graduated-${runId}`;+}++// ── durable writes ─────────────────────────────────────────────────────────++function fsyncDirectory(dir: string): void {+ let fd: number | undefined;+ try { fd = openSync(dir, 'r'); fsyncSync(fd); }+ catch (error) { if (process.platform !== 'win32') throw error; }+ finally { if (fd !== undefined) closeSync(fd); }+}+export function fsyncParent(path: string): void { fsyncDirectory(dirname(path)); }++/** tmp + fsync + rename + fsync(parent), mode 0600. */+export function writeFileDurably(path: string, content: string): void {+ const tmp = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;+ const fd = openSync(tmp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);+ try {+ writeSync(fd, content);+ fsyncSync(fd);+ } finally { closeSync(fd); }+ try { renameSync(tmp, path); } catch (error) { rmSync(tmp, { force: true }); throw error; }+ fsyncParent(path);+}++// ── in-process run identity ────────────────────────────────────────────────++const inProcessRuns = new Set<string>();+/** The orchestrator registers its run so its own connects pass the marker and target-row checks. */+export function registerGraduationRunInProcess(runId: string): () => void {+ inProcessRuns.add(runId);+ return () => { inProcessRuns.delete(runId); };+}+export function isGraduationRunInProcess(runId: string): boolean { return inProcessRuns.has(runId); }++// ── process identity (marker liveness) ─────────────────────────────────────++/** Kernel start time of `pid` (Linux /proc clock ticks), or null when unknowable. */+export function processStartTime(pid: number): string | null {+ try {+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');+ return fields[19] ?? null;+ } catch { return null; }+}++export function currentProcessIdentity(): Pick<IntentMarker, 'pid' | 'bootId' | 'pidNs' | 'processStart'> {+ return { pid: process.pid, bootId: readBootId(), pidNs: readPidNs(), processStart: processStartTime(process.pid) };+}++/**+ * Whether the marker's requesting process is still running. `unknown` when+ * the marker comes from another boot or PID namespace (another host on a+ * shared filesystem, or a container); callers then treat the kernel lock as+ * the authority (an acquirable lock means the run is gone).+ */+export function markerLiveness(marker: IntentMarker): 'alive' | 'dead' | 'unknown' {+ if (marker.pid === process.pid) return isGraduationRunInProcess(marker.runId) ? 'alive' : 'dead';+ const bootId = readBootId(), pidNs = readPidNs();+ if (marker.bootId && bootId && marker.bootId !== bootId) return 'unknown';+ if (marker.pidNs && pidNs && marker.pidNs !== pidNs) return 'unknown';+ if (!isProcessAlive(marker.pid)) return 'dead';+ if (marker.processStart) {+ const start = processStartTime(marker.pid);+ if (start && start !== marker.processStart) return 'dead';+ }+ return 'alive';+}++// ── intent marker ──────────────────────────────────────────────────────────++/** Atomic replace + fsync. Written at step 1 before the kernel lock, then at every state change. */+export function writeIntentMarker(dataDir: string, marker: IntentMarker): void {+ writeFileDurably(intentMarkerPath(dataDir), `${JSON.stringify(marker, null, 2)}\n`);+}++function isMarker(value: unknown): value is IntentMarker {+ const m = value as IntentMarker | null;+ return !!m && typeof m === 'object' && typeof m.runId === 'string' && typeof m.state === 'string' && typeof m.pid === 'number';+}++/** Null when absent. An unreadable marker throws: it is never read as "no graduation". */+export function readIntentMarker(dataDir: string): IntentMarker | null {+ let raw: string;+ try { raw = readFileSync(intentMarkerPath(dataDir), 'utf8'); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }+ const parsed = JSON.parse(raw) as unknown;+ if (!isMarker(parsed)) throw new Error(`Unrecognised graduation intent marker at ${intentMarkerPath(dataDir)}`);+ return parsed;+}++export function removeIntentMarker(dataDir: string): void {+ const path = intentMarkerPath(dataDir);+ try { unlinkSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; return; }+ fsyncParent(path);+}++// ── tombstone ──────────────────────────────────────────────────────────────++export class TombstonePathOccupiedError extends Error {+ readonly code = 'graduation_split_brain';+ constructor(readonly path: string) { super(`Something already exists at ${path}; the graduation tombstone was not written.`); }+}++/**+ * Create the tombstone at the old data dir path with O_CREAT|O_EXCL (mode+ * 0600), fsync it and its parent. An occupied path throws+ * `TombstonePathOccupiedError`: a stray datastore appeared after the rename.+ */+export function writeTombstone(dataDir: string, tombstone: Tombstone): void {+ const path = graduationDataDir(dataDir);+ let fd: number;+ try { fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new TombstonePathOccupiedError(path); throw error; }+ try {+ writeSync(fd, `${JSON.stringify(tombstone, null, 2)}\n`);+ fsyncSync(fd);+ } finally { closeSync(fd); }+ fsyncParent(path);+}++/** The tombstone when the path is a regular file holding one; null otherwise (including a directory). */+export function readTombstone(dataDir: string): Tombstone | null {+ const path = graduationDataDir(dataDir);+ try {+ if (!lstatSync(path).isFile()) return null;+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Tombstone;+ return parsed?.kind === 'gbrain-engine-graduated' && typeof parsed.runId === 'string' ? parsed : null;+ } catch { return null; }+}++/** Rollback only: remove this run's tombstone (never anything else) and fsync the parent. */+export function removeTombstone(dataDir: string, runId: string): void {+ const path = graduationDataDir(dataDir);+ const tombstone = readTombstone(path);+ if (!tombstone) { if (existsSync(path)) throw new Error(`${path} is not a graduation tombstone; refusing to remove it.`); return; }+ if (tombstone.runId !== runId) throw new Error(`${path} belongs to graduation run ${tombstone.runId}, not ${runId}.`);+ unlinkSync(path);+ fsyncParent(path);+}++// ── path inspection ────────────────────────────────────────────────────────++/**+ * What a data dir path shows, without opening or locking it: `graduated`+ * (tombstone file), `split_brain` (a directory at the old path while this+ * run's moved copy exists and the marker says the rename happened),+ * `in_progress` (non-terminal marker whose run is alive or unknowable),+ * `interrupted` (non-terminal marker whose run is dead, or the moved copy+ * without its tombstone), or `none`.+ */+export function inspectGraduationPath(dataDir: string): GraduationPathState {+ const path = graduationDataDir(dataDir);+ let marker: IntentMarker | null = null;+ let markerError: string | null = null;+ try { marker = readIntentMarker(path); } catch (error) { markerError = (error as Error).message; }+ let stat: ReturnType<typeof lstatSync> | null = null;+ try { stat = lstatSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ const movedTo = marker && existsSync(graduatedPath(path, marker.runId)) ? graduatedPath(path, marker.runId) : null;+ const base = { dataDir: path, marker, movedTo };++ if (stat?.isFile()) {+ const tombstone = readTombstone(path);+ if (tombstone) {+ const moved = existsSync(tombstone.movedTo) ? tombstone.movedTo : movedTo;+ return { ...base, kind: 'graduated', tombstone, liveness: null, movedTo: moved, detail: `This datastore moved to Postgres (run ${tombstone.runId}).` };+ }+ return { ...base, kind: 'interrupted', tombstone: null, liveness: null, detail: `${path} is a file but not a readable graduation tombstone.` };+ }+ if (markerError) {+ return { ...base, kind: 'interrupted', tombstone: null, liveness: 'unknown', detail: markerError };+ }+ if (!marker || TERMINAL_STATES.has(marker.state)) {+ if (stat === null && marker?.state === 'graduated' && movedTo) {+ return { ...base, kind: 'interrupted', tombstone: null, liveness: null, detail: `The graduated datastore at ${movedTo} has no tombstone at ${path}.` };+ }+ return { ...base, kind: 'none', tombstone: null, liveness: null, detail: '' };+ }+ const liveness = markerLiveness(marker);+ const renamed = !PRE_CUTOVER_STATES.has(marker.state) && marker.state !== 'cutover';+ if (stat?.isDirectory() && movedTo && (renamed || marker.state === 'cutover')) {+ return { ...base, kind: 'split_brain', tombstone: null, liveness,+ detail: `A datastore exists at ${path} while graduation run ${marker.runId} already moved the original to ${movedTo}.` };+ }+ if (stat === null && movedTo) {+ return { ...base, kind: liveness === 'alive' ? 'in_progress' : 'interrupted', tombstone: null, liveness,+ detail: `Graduation run ${marker.runId} moved the datastore to ${movedTo}; the tombstone is not written yet.` };+ }+ if (liveness === 'dead') {+ return { ...base, kind: 'interrupted', tombstone: null, liveness, detail: `Graduation run ${marker.runId} stopped at ${marker.state} (pid ${marker.pid} is gone).` };+ }+ return { ...base, kind: 'in_progress', tombstone: null, liveness, detail: `Graduation run ${marker.runId} is at ${marker.state} (pid ${marker.pid}).` };+}++/**+ * A resident serve that owns `dataDir` calls this on its idle loop: it returns+ * the marker when a live graduation run on another process asks for the+ * datastore, so the serve finishes in-flight work, releases the lock and exits+ * with `graduation_in_progress`. A dead requester before cutover never stops+ * the serve.+ */+export function graduationHandOffRequested(dataDir: string): IntentMarker | null {+ let marker: IntentMarker | null;+ try { marker = readIntentMarker(dataDir); } catch { return null; }+ if (!marker || TERMINAL_STATES.has(marker.state) || marker.pid === process.pid) return null;+ return markerLiveness(marker) === 'alive' ? marker : null;+}++/**+ * The PGLite open-path check. `pre_lock` runs before `acquireLock`: a+ * tombstone refuses with `engine_graduated`, a stray datastore with+ * `graduation_split_brain`, a live run (or the lock holder recorded as+ * `migrate`) with `graduation_in_progress`. `locked` runs once this process+ * holds the kernel lock, which proves any other run is gone: a marker past+ * the source fence refuses with `graduation_interrupted`; one before it lets+ * the open proceed (the source is still authoritative).+ */+export function assertPgliteGraduationOpenable(dataDir: string, phase: 'pre_lock' | 'locked'): void {+ const state = inspectGraduationPath(dataDir);+ if (state.kind === 'none') return;+ const ours = !!state.marker && state.marker.pid === process.pid && isGraduationRunInProcess(state.marker.runId);+ if (state.kind === 'graduated') throw engineGraduatedError(state.tombstone!);+ if (state.kind === 'split_brain') throw graduationSplitBrainError(state);+ if (ours) return;+ if (phase === 'pre_lock') {+ if (state.kind === 'in_progress' && state.liveness === 'alive') {+ throw graduationInProgressError({ runId: state.marker!.runId, state: state.marker!.state, where: 'source' });+ }+ if (state.kind === 'in_progress') {+ const holder = inspectLockHolder(state.dataDir);+ if (holder.held && holder.subcommand === 'migrate') {+ throw graduationInProgressError({ runId: state.marker!.runId, state: state.marker!.state, where: 'source' });+ }+ }+ return;+ }+ if (!state.marker || PRE_CUTOVER_STATES.has(state.marker.state)) return;+ throw graduationInterruptedError({ runId: state.marker.runId, state: state.marker.state, detail: state.detail });+}++// ── held-lock move-aside ───────────────────────────────────────────────────++/**+ * Step 7: rename the data dir to `<dataDir>.graduated-<run_id>` under the+ * already-held kernel lock (no release, no gap) and retarget the lock+ * metadata into the moved dir. Returns the moved path.+ */+export function moveAsideHeld(dataDir: string, lock: LockHandle, runId: string): string {+ const movedTo = graduatedPath(dataDir, runId);+ moveHeldPglite(graduationDataDir(dataDir), movedTo, lock);+ return movedTo;+}++// ── refusals ───────────────────────────────────────────────────────────────++const STATUS_ARGV = ['gbrain', 'migrate', '--status', '--json'];++/** opError for a graduation code. The registry rows are added with the error-code batch. */+export function graduationError(code: GraduationErrorCode, message: string, suggestion: string, why: string, fix: Action, detail?: string): OperationError {+ return opError(code as RegistryCode, message, suggestion, { why, fix: { docs: fix.docs ?? `${MOVE_TO_POSTGRES_DOC}#${code.replace(/_/g, '-')}`, ...fix }, ...(detail ? { detail } : {}) });+}++export function graduationInProgressError(ctx: { runId: string; state: ManifestState | TargetRowState; where: 'source' | 'target' }): OperationError {+ const where = ctx.where === 'source'+ ? 'This PGLite datastore is being moved to Postgres by another gbrain process'+ : 'This Postgres database is the target of a gbrain engine graduation that has not granted it authority';+ return graduationError('graduation_in_progress', `${where} (run ${ctx.runId}, state ${ctx.state}).`,+ 'Wait for the graduation run to finish, then retry the same command; `gbrain migrate --status --json` shows its progress.',+ 'Exactly one engine accepts writes at a time during a graduation; this one is fenced until the run finishes or rolls back.',+ { argv: STATUS_ARGV, consent: [], actor: 'provider', requires_exclusive: false,+ why: 'Shows the graduation run state; retry the original command once it reports graduated, rolled_back or abandoned.',+ verify: { argv: STATUS_ARGV } });+}++export function graduationInterruptedError(ctx: { runId: string; state: ManifestState | TargetRowState; detail: string }): OperationError {+ return graduationError('graduation_interrupted', `Engine graduation run ${ctx.runId} stopped at ${ctx.state}. ${ctx.detail}`,+ 'Run `gbrain migrate --resume` on the host that started the move; it continues from the first incomplete step using the recorded identities. `gbrain migrate --rollback-to-source` is the alternative.',+ 'The run fenced this datastore before it stopped, so neither engine may be written until the run is resumed or rolled back.',+ { argv: ['gbrain', 'migrate', '--resume'], consent: [], actor: 'agent', requires_exclusive: true,+ why: 'Continues the interrupted graduation from its recorded state and ends with exactly one authoritative engine.',+ verify: { argv: STATUS_ARGV } });+}++export function engineGraduatedError(tombstone: Tombstone, opts: { onRunHost?: boolean } = {}): OperationError {+ const message = `This PGLite datastore moved to Postgres at ${tombstone.targetDisplayUrl} (run ${tombstone.runId}, ${tombstone.graduatedAt}); the original is retained at ${tombstone.movedTo}.`;+ if (opts.onRunHost) {+ return graduationError('engine_graduated', message,+ 'Run `gbrain migrate --resume` to finish pointing this machine at the new engine.',+ 'The datastore was moved aside and replaced by a tombstone; only the Postgres target accepts writes.',+ { argv: ['gbrain', 'migrate', '--resume'], consent: [], actor: 'agent', requires_exclusive: true,+ why: 'Finishes the routing flip and registry rewrites recorded in the graduation manifest.', verify: { argv: ['gbrain', 'doctor', '--no-migrate', '--json'] } });+ }+ return graduationError('engine_graduated', message,+ `Point this client at the new engine: \`gbrain config set database_url "$GBRAIN_TARGET_URL"\` with GBRAIN_TARGET_URL holding the Postgres URL for ${tombstone.targetDisplayUrl}. Rolling back is \`gbrain migrate --rollback-to-source\` on the host that ran the move and drops writes made since.`,+ 'The datastore was moved aside and replaced by a tombstone; only the Postgres target accepts writes.',+ { argv: ['gbrain', 'config', 'set', 'database_url', '<GBRAIN_TARGET_URL>'], consent: ['credentials'], actor: 'user', requires_exclusive: false,+ inputs: [{ name: 'GBRAIN_TARGET_URL', how: `The Postgres connection URL for ${tombstone.targetDisplayUrl}; the user or the brain host's operator supplies it.` }],+ why: 'Points this client at the Postgres engine that now holds the brain.',+ user_message: `This brain moved to Postgres at ${tombstone.targetDisplayUrl}. Please run \`gbrain config set database_url "$GBRAIN_TARGET_URL"\` with that database's URL.`,+ verify: { argv: ['gbrain', 'doctor', '--no-migrate', '--json'] } });+}++export function graduationSplitBrainError(state: Pick<GraduationPathState, 'dataDir' | 'movedTo' | 'marker' | 'detail'>, counts?: string): OperationError {+ const runId = state.marker?.runId ?? 'unknown';+ const stray = state.dataDir;+ return graduationError('graduation_split_brain',+ `Two datastores claim this brain: a stray one at ${stray} and graduation run ${runId}'s original at ${state.movedTo ?? 'unknown'}. ${state.detail}${counts ? ` ${counts}` : ''}`,+ 'Ask the user which copy to keep. To continue the move, move the stray datastore aside (the command in fix) and run `gbrain migrate --resume`; to keep PGLite, move it aside and run `gbrain migrate --rollback-to-source`.',+ 'A process created a new datastore at the old path after the original was moved aside; the target is withheld from authority until one copy is chosen.',+ { argv: ['mv', stray, `${stray}.stray-${runId}`], consent: ['destructive'], actor: 'agent', requires_exclusive: true,+ why: 'Moves the stray datastore out of the way without deleting it, so the graduation can finish or roll back.',+ user_message: `Two copies of this brain exist: a stray one at ${stray} and the original at ${state.movedTo ?? 'unknown'}. Should I move the stray copy aside and continue?`,+ then: { argv: ['gbrain', 'migrate', '--resume'], consent: [], actor: 'agent', requires_exclusive: true, why: 'Continues the graduation once the stray datastore is out of the way.' },+ verify: { argv: STATUS_ARGV } });+}++/** Display form of a target identity: never the password. */+export function targetDisplayUrl(target: TargetIdentity): string {+ return `postgres://${encodeURIComponent(target.user)}@${target.host}:${target.port}/${encodeURIComponent(target.database)}`;+}++// ── database connect and admission checks ──────────────────────────────────++function exemptRun(runId: string, env: NodeJS.ProcessEnv): boolean {+ return env.GBRAIN_GRADUATION_RUN === runId || isGraduationRunInProcess(runId);+}++/**+ * Connect-path check for any engine: a target that is not yet (or no longer)+ * authoritative refuses every connect except the graduation run's own+ * (in-process, or `GBRAIN_GRADUATION_RUN` naming the row's run); a source that+ * recorded `cutover` refuses with `engine_graduated` once its tombstone exists,+ * otherwise `graduation_interrupted`.+ */+export async function assertGraduationConnectAllowed(engine: BrainEngine, env: NodeJS.ProcessEnv = process.env): Promise<void> {+ const row = await readGraduationRow(engine);+ if (!row || exemptRun(row.run_id, env)) return;+ if (row.role === 'target') {+ if (row.state === 'authoritative') return;+ throw graduationInProgressError({ runId: row.run_id, state: row.state, where: 'target' });+ }+ if (row.state !== 'cutover') return;+ const tombstone = row.source_data_dir ? readTombstone(row.source_data_dir) : null;+ if (tombstone) throw engineGraduatedError(tombstone);+ throw graduationInterruptedError({ runId: row.run_id, state: 'cutover', detail: 'The source recorded cutover but its datastore was not moved aside yet.' });+}++/**+ * Writer-admission check (`admitWrite*`): the same rules inside the admitting+ * transaction, where the run's identity is the `gbrain.graduation_run` setting+ * (the verify-step replay probe sets it).+ */+export async function assertGraduationAdmission(tx: BrainEngine): Promise<void> {+ if (!await graduationTablePresent(tx)) return;+ const [row] = await tx.executeRaw<{ role: string; run_id: string; state: string; source_data_dir: string | null; run: string | null }>(+ `SELECT role, run_id::text AS run_id, state, source_data_dir, NULLIF(current_setting('${GRADUATION_RUN_SETTING}', true), '') AS run+ FROM persistence_graduation WHERE singleton = 1`);+ if (!row || row.run === row.run_id) return;+ if (row.role === 'target') {+ if (row.state === 'authoritative') return;+ throw graduationInProgressError({ runId: row.run_id, state: row.state as TargetRowState, where: 'target' });+ }+ if (row.state !== 'cutover') return;+ const tombstone = row.source_data_dir ? readTombstone(row.source_data_dir) : null;+ if (tombstone) throw engineGraduatedError(tombstone);+ throw graduationInterruptedError({ runId: row.run_id, state: 'cutover', detail: 'The source recorded cutover; writes here are refused.' });+}diff --git a/src/core/persistence/graduation-schema.ts b/src/core/persistence/graduation-schema.tsnew file mode 100644index 0000000000..e4584c434c--- /dev/null+++ b/src/core/persistence/graduation-schema.ts@@ -0,0 +1,253 @@+/**+ * Engine graduation custody state in the database: the `persistence_graduation`+ * singleton (each engine's own row: the source records `quiesced` -> `cutover`,+ * the target records `copying` -> ... -> `authoritative`) and the+ * `gbrain_graduation_fence` statement triggers that refuse every write on the+ * target except from transactions that carry the run's identity+ * (`SET LOCAL gbrain.graduation_run = '<run_id>'`, PgBouncer transaction-mode+ * safe). The GUC and `GBRAIN_GRADUATION_RUN` are safety interlocks, not+ * security boundaries.+ */+import type { BrainEngine } from '../engine.ts';+import {+ assertTransition, SOURCE_ROW_STATES, SOURCE_TRANSITIONS, TARGET_ROW_STATES, TARGET_TRANSITIONS,+ type ReplayProbeResult, type SourceRowState, type TableReceipt, type TargetRowState, type TriggerBypass,+} from './engine-graduation.types.ts';++export const GRADUATION_FENCE_TRIGGER = 'gbrain_graduation_fence';+export const GRADUATION_RUN_SETTING = 'gbrain.graduation_run';++const ROW_STATES = [...new Set<string>([...SOURCE_ROW_STATES, ...TARGET_ROW_STATES])];++/** Shared by the schema migration on both engines. Idempotent. */+export const PERSISTENCE_GRADUATION_SCHEMA_SQL = `+CREATE TABLE IF NOT EXISTS persistence_graduation (+ singleton smallint PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),+ role text NOT NULL CHECK (role IN ('source','target')),+ run_id uuid NOT NULL,+ state text NOT NULL CHECK (state IN (${ROW_STATES.map(s => `'${s}'`).join(',')})),+ source_brain_id uuid,+ source_data_dir text,+ cutover_sequence bigint,+ trigger_bypass text CHECK (trigger_bypass IS NULL OR trigger_bypass IN ('session_replication_role','disable_trigger')),+ table_receipts jsonb,+ replay_probe jsonb,+ timings jsonb NOT NULL DEFAULT '{}'::jsonb,+ doctor jsonb,+ rollback jsonb,+ graduated_at timestamptz,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now()+);+CREATE OR REPLACE FUNCTION gbrain_graduation_fence() RETURNS trigger LANGUAGE plpgsql AS $fence$+DECLARE fence_run text;+BEGIN+ SELECT run_id::text INTO fence_run FROM persistence_graduation WHERE singleton = 1;+ IF fence_run IS NULL OR fence_run IS DISTINCT FROM NULLIF(current_setting('${GRADUATION_RUN_SETTING}', true), '') THEN+ RAISE EXCEPTION 'graduation_in_progress: this database is fenced by gbrain engine graduation run %; writes are refused until the run grants it authority', COALESCE(fence_run, 'unknown')+ USING ERRCODE = '55000', HINT = 'Run: gbrain migrate --status --json';+ END IF;+ RETURN NULL;+END+$fence$;+`;++export interface GraduationRow {+ role: 'source' | 'target';+ run_id: string;+ state: SourceRowState | TargetRowState;+ source_brain_id: string | null;+ source_data_dir: string | null;+ cutover_sequence: string | null;+ trigger_bypass: TriggerBypass | null;+ table_receipts: readonly TableReceipt[] | null;+ replay_probe: ReplayProbeResult | null;+ timings: Record<string, number>;+ doctor: unknown;+ rollback: unknown;+ graduated_at: string | null;+}++function parseJson<T>(value: unknown): T | null {+ if (value === null || value === undefined) return null;+ if (typeof value === 'string') { try { return JSON.parse(value) as T; } catch { return null; } }+ return value as T;+}++export async function graduationTablePresent(engine: BrainEngine): Promise<boolean> {+ const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT to_regclass('persistence_graduation') IS NOT NULL AS present`);+ return row?.present === true;+}++/** The engine's own custody row, or null on a normal brain (or before the migration). */+export async function readGraduationRow(engine: BrainEngine, opts: { forUpdate?: boolean } = {}): Promise<GraduationRow | null> {+ if (!await graduationTablePresent(engine)) return null;+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ `SELECT role, run_id::text AS run_id, state, source_brain_id::text AS source_brain_id, source_data_dir,+ cutover_sequence::text AS cutover_sequence, trigger_bypass, table_receipts, replay_probe, timings, doctor, rollback,+ graduated_at::text AS graduated_at+ FROM persistence_graduation WHERE singleton = 1${opts.forUpdate ? ' FOR UPDATE' : ''}`);+ if (!row) return null;+ return {+ role: row.role as GraduationRow['role'],+ run_id: String(row.run_id),+ state: row.state as GraduationRow['state'],+ source_brain_id: (row.source_brain_id as string | null) ?? null,+ source_data_dir: (row.source_data_dir as string | null) ?? null,+ cutover_sequence: (row.cutover_sequence as string | null) ?? null,+ trigger_bypass: (row.trigger_bypass as TriggerBypass | null) ?? null,+ table_receipts: parseJson<TableReceipt[]>(row.table_receipts),+ replay_probe: parseJson<ReplayProbeResult>(row.replay_probe),+ timings: parseJson<Record<string, number>>(row.timings) ?? {},+ doctor: parseJson(row.doctor),+ rollback: parseJson(row.rollback),+ graduated_at: (row.graduated_at as string | null) ?? null,+ };+}++/**+ * Run `fn` in one transaction that carries the run's identity, so the fence+ * admits its writes. `readWrite` opens the transaction READ WRITE first (the+ * frozen source runs with `default_transaction_read_only`).+ */+export async function withGraduationRun<T>(engine: BrainEngine, runId: string, fn: (tx: BrainEngine) => Promise<T>, opts: { readWrite?: boolean } = {}): Promise<T> {+ return engine.transaction(async tx => {+ if (opts.readWrite) await tx.executeRaw('SET TRANSACTION READ WRITE');+ await tx.executeRaw(`SELECT set_config('${GRADUATION_RUN_SETTING}', $1, true)`, [runId]);+ return fn(tx);+ });+}++export interface GraduationRowPatch {+ sourceBrainId?: string | null;+ sourceDataDir?: string | null;+ cutoverSequence?: string | null;+ triggerBypass?: TriggerBypass | null;+ tableReceipts?: readonly TableReceipt[] | null;+ replayProbe?: ReplayProbeResult | null;+ timings?: Record<string, number>;+ doctor?: unknown;+ rollback?: unknown;+ graduatedAt?: 'now' | null;+}++async function writeRow(tx: BrainEngine, role: 'source' | 'target', runId: string, state: string, patch: GraduationRowPatch, insert: boolean): Promise<void> {+ const json = (v: unknown) => (v === undefined ? undefined : v === null ? null : JSON.stringify(v));+ const fields: Array<[string, unknown, string]> = [];+ const add = (column: string, value: unknown, cast = '') => { if (value !== undefined) fields.push([column, value, cast]); };+ add('source_brain_id', patch.sourceBrainId, '::uuid');+ add('source_data_dir', patch.sourceDataDir);+ add('cutover_sequence', patch.cutoverSequence, '::bigint');+ add('trigger_bypass', patch.triggerBypass);+ add('table_receipts', json(patch.tableReceipts), '::text::jsonb');+ add('replay_probe', json(patch.replayProbe), '::text::jsonb');+ add('timings', json(patch.timings), '::text::jsonb');+ add('doctor', json(patch.doctor), '::text::jsonb');+ add('rollback', json(patch.rollback), '::text::jsonb');+ const params: unknown[] = [role, runId, state, ...fields.map(f => f[1])];+ const graduatedAt = patch.graduatedAt === 'now' ? 'now()' : patch.graduatedAt === null ? 'NULL' : undefined;+ if (insert) {+ const cols = ['role', 'run_id', 'state', ...fields.map(f => f[0]), ...(graduatedAt ? ['graduated_at'] : [])];+ const vals = ['$1', '$2::uuid', '$3', ...fields.map((f, i) => `$${i + 4}${f[2]}`), ...(graduatedAt ? [graduatedAt] : [])];+ await tx.executeRaw(`INSERT INTO persistence_graduation (singleton, ${cols.join(', ')}) VALUES (1, ${vals.join(', ')})+ ON CONFLICT (singleton) DO UPDATE SET ${cols.map(c => `${c} = EXCLUDED.${c}`).join(', ')}, created_at = now(), updated_at = now()`, params);+ return;+ }+ const sets = ['role = $1', 'run_id = $2::uuid', 'state = $3', ...fields.map((f, i) => `${f[0]} = $${i + 4}${f[2]}`),+ ...(graduatedAt ? [`graduated_at = ${graduatedAt}`] : []), 'updated_at = now()'];+ await tx.executeRaw(`UPDATE persistence_graduation SET ${sets.join(', ')} WHERE singleton = 1`, params);+}++/**+ * Move the target row to `to`, driven by TARGET_TRANSITIONS. A missing row may+ * only start as `copying`; an `abandoned` row of another run may be reused+ * (`abandoned` -> `copying`) only when `reuse` is set (`--force`). Call inside+ * `withGraduationRun` so the fence admits the write.+ */+export async function setTargetState(tx: BrainEngine, runId: string, to: TargetRowState, patch: GraduationRowPatch = {}, opts: { reuse?: boolean } = {}): Promise<void> {+ const row = await readGraduationRow(tx, { forUpdate: true });+ if (!row) {+ if (to !== 'copying') throw new Error(`Illegal graduation transition (none) -> ${to}`);+ await writeRow(tx, 'target', runId, to, patch, true);+ return;+ }+ if (row.role !== 'target') throw new Error('This database records a graduation source row; it cannot become a graduation target.');+ if (row.run_id !== runId) {+ if (!(opts.reuse && row.state === 'abandoned' && to === 'copying')) {+ throw new Error(`The target row belongs to graduation run ${row.run_id}, not ${runId}.`);+ }+ // The fence keys on the stored run id: switch the row, then this transaction's identity.+ await writeRow(tx, 'target', runId, to, { ...patch, cutoverSequence: null, tableReceipts: null, replayProbe: null, rollback: null, graduatedAt: null }, false);+ await tx.executeRaw(`SELECT set_config('${GRADUATION_RUN_SETTING}', $1, true)`, [runId]);+ return;+ }+ if (row.state !== to) assertTransition(TARGET_TRANSITIONS, row.state as TargetRowState, to);+ await writeRow(tx, 'target', runId, to, patch, false);+}++/** Move the source row to `to`, driven by SOURCE_TRANSITIONS; a fresh run starts at `quiesced`. */+export async function setSourceState(tx: BrainEngine, runId: string, to: SourceRowState, patch: GraduationRowPatch = {}): Promise<void> {+ const row = await readGraduationRow(tx, { forUpdate: true });+ if (!row) {+ if (to !== 'quiesced') throw new Error(`Illegal graduation transition (none) -> ${to}`);+ await writeRow(tx, 'source', runId, to, patch, true);+ return;+ }+ if (row.role !== 'source') throw new Error('This database records a graduation target row; it cannot become a graduation source.');+ if (row.run_id !== runId) {+ if (row.state !== 'rolled_back' || to !== 'quiesced') throw new Error(`The source row belongs to graduation run ${row.run_id}, not ${runId}.`);+ await writeRow(tx, 'source', runId, to, { cutoverSequence: null, ...patch }, true);+ return;+ }+ if (row.state !== to) assertTransition(SOURCE_TRANSITIONS, row.state as SourceRowState, to);+ await writeRow(tx, 'source', runId, to, patch, false);+}++const FENCED_TABLES_SQL = `SELECT c.oid AS relid, 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') AND NOT c.relispartition`;++/**+ * Install `gbrain_graduation_fence` (statement-level BEFORE INSERT OR UPDATE+ * OR DELETE OR TRUNCATE, `ENABLE ALWAYS` so it also fires under+ * `session_replication_role = replica`) on every table of the target schema.+ * Idempotent: repairs missing triggers and ones not set to ALWAYS.+ */+export async function installGraduationFence(target: BrainEngine, runId: string): Promise<void> {+ const row = await readGraduationRow(target);+ if (!row || row.role !== 'target' || row.run_id !== runId) {+ throw new Error(`The graduation fence needs the target row of run ${runId} first.`);+ }+ await target.executeRaw(`DO $install$ DECLARE r record; BEGIN+ FOR r IN ${FENCED_TABLES_SQL} LOOP+ IF NOT EXISTS (SELECT 1 FROM pg_trigger t WHERE t.tgrelid = r.relid AND t.tgname = '${GRADUATION_FENCE_TRIGGER}') THEN+ EXECUTE format('CREATE TRIGGER ${GRADUATION_FENCE_TRIGGER} BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON %I FOR EACH STATEMENT EXECUTE FUNCTION gbrain_graduation_fence()', r.relname);+ END IF;+ EXECUTE format('ALTER TABLE %I ENABLE ALWAYS TRIGGER ${GRADUATION_FENCE_TRIGGER}', r.relname);+ END LOOP; END $install$`);+}++/** Drop every fence trigger. The authority transaction calls this in the same transaction that grants authority. */+export async function dropGraduationFence(target: BrainEngine): Promise<void> {+ await target.executeRaw(`DO $drop$ DECLARE r record; BEGIN+ FOR r IN SELECT c.relname 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() AND t.tgname = '${GRADUATION_FENCE_TRIGGER}' LOOP+ EXECUTE format('DROP TRIGGER IF EXISTS ${GRADUATION_FENCE_TRIGGER} ON %I', r.relname);+ END LOOP; END $drop$`);+}++export interface FenceStatus {+ tables: number;+ /** Tables with the fence trigger set to ALWAYS. */+ fenced: number;+ /** Tables without a fence trigger, or with one not set to ALWAYS. */+ unfenced: readonly string[];+}++export async function graduationFenceStatus(engine: BrainEngine): Promise<FenceStatus> {+ const rows = await engine.executeRaw<{ relname: string; tgenabled: string | null }>(+ `SELECT c.relname, t.tgenabled::text AS tgenabled FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ LEFT JOIN pg_trigger t ON t.tgrelid = c.oid AND t.tgname = '${GRADUATION_FENCE_TRIGGER}'+ WHERE n.nspname = current_schema() AND c.relkind IN ('r','p') AND NOT c.relispartition ORDER BY c.relname COLLATE "C"`);+ const unfenced = rows.filter(r => r.tgenabled !== 'A').map(r => r.relname);+ return { tables: rows.length, fenced: rows.length - unfenced.length, unfenced };+}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex b9d7c214cd..03fddca8c4 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -14,6 +14,7 @@ import { publicFailureDetail } from './publication-failure.ts';import { catalogueError } from '../error-catalogue.ts';import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';+import { assertGraduationAdmission } from './graduation-custody.ts';import {isTerminal, principalKey, requestPrincipal, recoveryFiles,type JournalLimits, type Principal, type RecoveryRecord, type RequestState,@@ -147,6 +148,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overconst stamp = writerStamp();return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {await declarePersistenceProtocol(tx);+ await assertGraduationAdmission(tx);assertMutationProtocol({ target_kind: input.targetKind, protocol_version: input.protocolVersion });if (input.worktreeId) {await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [input.worktreeId]);@@ -227,6 +229,7 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writconst items = inputs.map(input => ({ input, requestId: requireUuid(input.requestId ?? randomUUID()), fingerprint: intentDigest(input),bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: input.terminalReservation ?? Math.max(16_384, jsonBytes(input.authority) + 8192) }));await declarePersistenceProtocol(tx);+ await assertGraduationAdmission(tx);assertMutationProtocol({ target_kind: 'page', protocol_version: 1 });if (first.worktreeId) {await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [first.worktreeId]);diff --git a/src/core/persistence/maintenance.ts b/src/core/persistence/maintenance.tsindex 79467e646d..097b1df9a2 100644--- a/src/core/persistence/maintenance.ts+++ b/src/core/persistence/maintenance.ts@@ -1,6 +1,6 @@-import { existsSync, renameSync } from 'node:fs';-import { join } from 'node:path';-import { acquireLock, releaseLock } from '../pglite-lock.ts';+import { closeSync, existsSync, fsyncSync, lstatSync, openSync, realpathSync, renameSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { acquireLock, releaseLock, type LockHandle } from '../pglite-lock.ts';import { assertManagedFilesystemWrite } from './filesystem-guard.ts';import { OperationError } from '../ops/contract.ts';import type { SqlEngine } from './model.ts';@@ -47,3 +47,26 @@ export async function backupUnmanagedPglite(dataDir: string, backupDir: string):lock.lockDir = join(backupDir, '.gbrain-lock');} finally { await releaseLock(lock); }}++/**+ * Engine graduation: rename a PGLite datastore while this process already+ * holds its stable sibling kernel lock (`backupUnmanagedPglite` acquires it+ * itself, which fails while it is held). The lock is never released here; its+ * metadata dir is retargeted to follow the moved datastore. Used for the+ * step-7 move-aside and the rollback move-back.+ */+export function moveHeldPglite(fromDir: string, toDir: string, lock: LockHandle): void {+ if (!lock.acquired || !lock.nativeLock || lock.nativeLock.released) throw new Error('Moving a PGLite datastore requires its held kernel lock.');+ assertManagedFilesystemWrite(fromDir);+ assertManagedFilesystemWrite(toDir);+ if (!lstatSync(fromDir).isDirectory()) throw new Error(`${fromDir} is not a PGLite data directory (symlinked datastores are not moved).`);+ if (lock.lockDir !== join(realpathSync(fromDir), '.gbrain-lock')) throw new Error(`The held kernel lock does not belong to ${fromDir}.`);+ if (existsSync(toDir)) throw new Error(`${toDir} already exists; inspect before retrying.`);+ renameSync(fromDir, toDir);+ lock.lockDir = join(toDir, '.gbrain-lock');+ if (lock.lockPath) lock.lockPath = join(lock.lockDir, 'lock');+ let fd: number | undefined;+ try { fd = openSync(dirname(toDir), 'r'); fsyncSync(fd); }+ catch (error) { if (process.platform !== 'win32') throw error; }+ finally { if (fd !== undefined) closeSync(fd); }+}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 138e0e292e..38b5d39a30 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -82,7 +82,8 @@ import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';import { PageMissingError } from './engine-errors.ts';import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';-import { acquireLock, releaseLock, type LockHandle } from './pglite-lock.ts';+import { acquireLock, pgliteLockDirFor, releaseLock, type LockHandle } from './pglite-lock.ts';+import { assertPgliteGraduationOpenable } from './persistence/graduation-custody.ts';// Engine-live path (#3596): static import, never a lazy `import()` in the// connect() catch. No cycle: pglite-repair.ts imports nothing from this file.import { attemptWalRepairAndRetry, closeRepairEpisodeIfOpen, readRepairFailedMarker, recordFailedAutoRepair, type WalRepairReceipt } from './pglite-repair.ts';@@ -710,6 +711,8 @@ export class PGLiteEngine implements BrainEngine {readonly kind = 'pglite' as const;private _db: PGLiteDB | null = null;private _lock: LockHandle | null = null;+ /** Graduation custody: a kernel lock this process already holds, adopted by the next open instead of acquired. */+ private _adoptedLock: LockHandle | null = null;private _dbWork: ReturnType<typeof trackPgliteDatabase<PGLiteDB>> | null = null;private _connectPromise: Promise<void> | null = null;private _closingWork: Promise<void> | null = null;@@ -784,7 +787,7 @@ export class PGLiteEngine implements BrainEngine {if (registerRoots) await registerManagedFilesystemEngine(this, config.database_path);}catch (error) {- try { await this._closeInternal(); }+ try { await this._closeInternal({ retainLock: this._lock !== null && this._lock === this._adoptedLock }); }catch (closeError) {this._closePoison = new PgliteClosingError(`PGLite registry failure cleanup did not close; lock retained: ${String(closeError)}`);throw this._closePoison;@@ -797,12 +800,55 @@ export class PGLiteEngine implements BrainEngine {try { await opening; }catch (error) {if (!this._db && !this._closePoison && this._lock?.acquired) {- await releaseLock(this._lock);+ if (this._lock !== this._adoptedLock) await releaseLock(this._lock);this._lock = null;}throw error;}- finally { if (this._connectPromise === opening) this._connectPromise = null; }+ finally {+ if (this._connectPromise === opening) this._connectPromise = null;+ this._adoptedLock = null;+ }+ }++ /**+ * Engine graduation: open a persistent datastore under a kernel lock this+ * process already holds (the rollback move-back), so ownership never gaps.+ * A failed open hands the lock back to the caller unreleased.+ */+ async connectWithHeldLock(config: EngineConfig, lock: LockHandle): Promise<void> {+ if (!config.database_path || !lock.acquired) throw new Error('A held-lock open needs a persistent datastore and its held kernel lock');+ if (lock.lockDir !== pgliteLockDirFor(config.database_path)) throw new Error('The held kernel lock does not belong to this datastore');+ if (this._db || this._connectPromise) throw new Error('PGLite engine is already connected or connecting');+ this._adoptedLock = lock;+ return this._connectWithRootRegistration(config, true);+ }++ /**+ * Engine graduation: drain admitted statements, checkpoint and close the+ * database, then hand the kernel lock back to the caller instead of+ * releasing it. The caller owns the handle (move-aside, then releaseLock).+ * Call the engine's ordinary disconnect afterwards to drop its wrappers.+ */+ async closeRetainingLock(): Promise<LockHandle> {+ if (this._closePoison) throw this._closePoison;+ if (this._disconnectCall || this._closingWork || this._connectPromise) throw new PgliteClosingError();+ const lock = this._lock;+ if (!this._db || !lock?.acquired || !this._savedConfig?.database_path) {+ throw new Error('closeRetainingLock needs an open persistent datastore that holds its kernel lock');+ }+ this.vectorIterativeScan = undefined;+ this._disconnectRequested = true;+ const work = this._closeInternal({ retainLock: true });+ this._closingWork = work;+ try { await work; }+ catch (error) {+ this._closePoison = new PgliteClosingError(`PGLite shutdown failed; datastore ownership is retained until process exit: ${String(error)}`);+ this._db = null;+ throw this._closePoison;+ }+ finally { this._closingWork = null; this._disconnectRequested = false; }+ return lock;}private async _connectInternal(config: EngineConfig): Promise<void> {@@ -815,12 +861,18 @@ export class PGLiteEngine implements BrainEngine {const failedRepair = dataDir ? readRepairFailedMarker(dataDir) : null;if (dataDir && failedRepair) throw (await import('./pglite-repair-consent.ts')).repairFailedRefusal(dataDir, failedRepair); // engine-dynamic-import-ok: refusal path only, keeps the consent graph off every open+ // Engine graduation: a tombstone, a stray datastore or a live run stops the open before the lock.+ if (dataDir) assertPgliteGraduationOpenable(dataDir, 'pre_lock');// Acquire file lock to prevent concurrent PGLite access (crashes with Aborted())- this._lock = await acquireLock(dataDir);+ this._lock = this._adoptedLock ?? await acquireLock(dataDir);if (!this._lock.acquired) {throw new Error('Could not acquire PGLite lock. Another gbrain process is using the database.');}+ if (dataDir && this._lock !== this._adoptedLock) {+ try { assertPgliteGraduationOpenable(dataDir, 'locked'); }+ catch (error) { await releaseLock(this._lock); this._lock = null; throw error; }+ }// Tier 3: optional snapshot fast-restore. Only applies to in-memory// engines (no persistent dataDir). The snapshot was built from a fresh@@ -947,14 +999,14 @@ export class PGLiteEngine implements BrainEngine {(retryError === undefined ? '' : `\n Cold retry error: ${retryError}`));const repairFailed = dataDir ? recordFailedAutoRepair(dataDir, ctx.repair, ctx.backupPath, original) : null;if (this._db) {- try { await this._closeInternal(); }+ try { await this._closeInternal({ retainLock: this._lock !== null && this._lock === this._adoptedLock }); }catch (closeError) {this._db = null;this._closePoison = new PgliteClosingError(`PGLite initialization cleanup failed; lock retained: ${String(closeError)}`);throw this._closePoison;}} else if (this._lock?.acquired) {- await releaseLock(this._lock);+ if (this._lock !== this._adoptedLock) await releaseLock(this._lock);this._lock = null;}if (dataDir && repairFailed) throw (await import('./pglite-repair-consent.ts')).repairFailedRefusal(dataDir, repairFailed, original, wrapped.message); // engine-dynamic-import-ok: refusal path only@@ -1000,7 +1052,7 @@ export class PGLiteEngine implements BrainEngine {return call;}- private async _closeInternal(): Promise<void> {+ private async _closeInternal(opts: { retainLock?: boolean } = {}): Promise<void> {const db = this._db;const lock = this._lock;const work = this._dbWork;@@ -1027,7 +1079,7 @@ export class PGLiteEngine implements BrainEngine {catch (error) { warnOncePerProcess('pglite-checkpoint-failed', `[pglite] checkpoint failed; retaining ownership through close: ${String(error)}`); }await db.close();}- if (lock?.acquired) await releaseLock(lock);+ if (lock?.acquired && !opts.retainLock) await releaseLock(lock);this._lock = null;this._dbWork = null;this._statements = null;diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.tsindex f48f9db72d..c25b5ea279 100644--- a/src/core/pglite-lock.ts+++ b/src/core/pglite-lock.ts@@ -317,6 +317,36 @@ export async function acquireLock(dataDir: string | undefined, opts: { timeoutMs}}+/**+ * Engine graduation: take only the stable sibling kernel lock of `dataDir`,+ * without creating the data dir or its metadata (the path may hold a+ * graduation tombstone file, or nothing while the datastore sits at its+ * moved-aside path). `lockDir` names where the datastore's metadata now+ * lives so release and a later move retarget it correctly.+ */+export async function acquireKernelLockOnly(dataDir: string, opts: { lockDir: string; timeoutMs?: number; signal?: AbortSignal }): Promise<LockHandle> {+ const timeoutMs = opts.timeoutMs ?? 30_000;+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2 ** 31 - 1) throw new RangeError('Invalid PGLite lock timeout');+ const kernelPath = getPgliteKernelLockPath(dataDir)!;+ const deadline = performance.now() + timeoutMs;+ for (;;) {+ opts.signal?.throwIfAborted();+ const nativeLock = await tryAcquireNativeLock(kernelPath);+ if (nativeLock) {+ const result: LockHandle = { lockDir: opts.lockDir, acquired: true, nativeLock, acquiredAt: Date.now() };+ retainedOwners.add(result);+ return result;+ }+ if (performance.now() >= deadline) throw busy(getLockDir(canonicalPath(dataDir)));+ await delay(Math.min(25, deadline - performance.now()), undefined, { signal: opts.signal });+ }+}++/** The metadata dir `acquireLock` uses for `dataDir`; a held handle for that datastore carries it as `lockDir`. */+export function pgliteLockDirFor(dataDir: string): string {+ return getLockDir(canonicalPath(dataDir));+}+/** Metadata removal is optional; kernel release is mandatory and never unlinks. */export async function releaseLock(lock: LockHandle): Promise<void> {if (!lock.acquired) return;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 16ef4d9ecc..154a8c3fd2 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -201,6 +201,7 @@ import { v197 } from './v197-managed-guard-null-source-fallback.ts';import { v198 } from './v198-publication-failure-detail.ts';import { v199 } from './v199-chronicle-page-state.ts';import { v200 } from './v200-sync-hold-page-index.ts';+import { v203 } from './v203-persistence-graduation.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -400,4 +401,5 @@ export const MIGRATIONS: Migration[] = [v198,v199,v200,+ v203,];diff --git a/src/core/schema-migrations/v203-persistence-graduation.ts b/src/core/schema-migrations/v203-persistence-graduation.tsnew file mode 100644index 0000000000..4803bdf7ce--- /dev/null+++ b/src/core/schema-migrations/v203-persistence-graduation.ts@@ -0,0 +1,16 @@+import type { Migration } from './types.ts';+import { PERSISTENCE_GRADUATION_SCHEMA_SQL } from '../persistence/graduation-schema.ts';++// Engine graduation (PGLite -> Postgres): the `persistence_graduation`+// singleton both engines use as their own custody record (source:+// quiesced -> cutover; target: copying -> verified -> authoritative), and the+// `gbrain_graduation_fence()` trigger function the run attaches to every+// target table until the authority transaction. DDL in+// src/core/persistence/graduation-schema.ts. The table is schema-owned: never+// copied, digested or compared.+export const v203: Migration = {+ version: 203,+ name: 'persistence_graduation',+ idempotent: true,+ sql: PERSISTENCE_GRADUATION_SCHEMA_SQL,+};