Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge G3 into g2a; orchestrator implements the G3 CLI surface (GraduationCommandOptions, status doc, rollback result, receipt fields, progress sink, SIGINT), all refusals through graduation-errors.ts, G2b duplicate helper removed, split brain resolvable with --resume --yes
garrytan181d547039fa
diff --cc src/core/persistence/engine-graduation.tsindex 5abdffa298,fe224a961a..58d21984ef--- a/src/core/persistence/engine-graduation.ts+++ b/src/core/persistence/engine-graduation.ts@@@ -1,1389 -1,19 +1,1463 @@@/**- * STUB (G3 CLI lane). The G2a lane owns this module; the integrator replaces- * this file with G2a's implementation. Signatures follow GRADUATION_LANES.md- * and the CLI <-> orchestrator types in engine-graduation.types.ts.+ * 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 type {- GraduationCommandOptions, GraduationPlan, GraduationReceipt, GraduationRollbackResult, GraduationStatusDoc,+import { createHash, randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, renameSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, 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 { 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 { acquireKernelLockOnly, inspectLockHolder, 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, graduationBoundary, MANIFEST_TRANSITIONS,+ type GraduationBoundary, type GraduationBoundaryDetail,- 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 TargetProbe, type TargetRoutes, type TriggerBypass,++ type GraduationBlocker, type GraduationCommandOptions, type GraduationManifest, type GraduationPathState, type GraduationPhase, type GraduationPlan,++ type GraduationReceipt, type GraduationRollbackResult, type GraduationStatusDoc, type GraduationTargetSpelling, type IntentMarker, type Inventory, type InventoryEntry, type LossKind,++ type ManifestState, type TableCheckpoint, type TableReceipt, type TargetIdentity, type TargetProbe, type TargetRoutes, type TargetRowState, 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,++ currentProcessIdentity, engineGraduatedFor, fsyncParent, graduatedPath, graduationDataDir, inspectGraduationPath, markerLiveness,++ allowGraduationInspection, moveAsideHeld, readIntentMarker, readTombstone, registerGraduationRunInProcess, removeIntentMarker, removeTombstone, splitBrainFor,++ targetDisplayUrl, TERMINAL_STATES, TombstonePathOccupiedError, writeFileDurably, writeIntentMarker, writeTombstone,+} from './graduation-custody.ts';++import {++ drainTimeoutError, embeddingDimensionMismatchError, foreignHostBindingError, inProgressError, interruptedError, planArgv as planArgvOf,++ resumeArgv, rollbackWritesLostError, runArgv as runArgvOf, sourceWriterHeldError, statusArgv, targetAuthFailedError, targetNotEmptyError,++ targetUnsupportedError, unsupportedPlatformError, verifyFailedError,++} from './graduation-errors.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 {+ assertTargetReachable, chooseTriggerBypass, connectTargetEngines, crossCheckRoutes, probeTarget, resolveTargetRoutes, sourceEmbeddingLayout,+ targetIdentity, targetProbeBlockers,+} from './graduation-target.ts';- import { drainForGraduation, drainTimeoutError, freezeSource, graduationBlockers, withSourceWritable } from './graduation-drain.ts';++import { drainForGraduation, freezeSource, graduationBlockers, withSourceWritable } from './graduation-drain.ts';+import { buildDeferredIndexes, copySequences, copyTable, deferIndexes, detectTriggerBypass, reenableTriggers } from './graduation-copy.ts';-function notMerged(name: string): never {- throw new Error(`${name}: the engine graduation orchestrator (G2a) is not merged into this build.`);+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'];++const STATUS_ARGV = statusArgv();+/** 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>;+ /** Main and DDL target engines; the DDL route is an explicit override (no pooler fallback). */+ connectTargets(routes: Routes): Promise<{ main: BrainEngine; ddl: BrainEngine; close(): Promise<void> }>;+ /** 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 connectTargets(routes) {+ try { return await connectTargetEngines(routes); }- catch (error) { throw mapTargetConnectError(error); }++ catch (error) { throw mapTargetConnectError(error, routes); }+ },+ async initTargetSchema(target, source) {+ const layout = await sourceEmbeddingLayout(source);+ const chunks = layout.columns.find(c => c.relation === 'content_chunks' && c.column === 'embedding');+ const dimensions = chunks?.dims ?? (Number(layout.config.embedding_dimensions) || null);+ const model = layout.config.embedding_model;+ const sized = target as BrainEngine & { initSchema(opts?: { embedding?: { dimensions: number; model: string } }): Promise<void> };+ await sized.initSchema(dimensions && model ? { embedding: { dimensions, model } } : {});+ },+ 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 {++function mapTargetConnectError(error: unknown, routes: Routes): 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 targetAuthFailedError({ host: routes.main, ...(routes.urlEnv ? { urlEnv: routes.urlEnv } : {}) });+ }+ 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 {+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ 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 {++/** Seams beyond the CLI surface: tests and embedders. The CLI passes `GraduationCommandOptions` only. */++export interface GraduationInternals {++ /** The source brain config; defaults to the config file (never env overrides). */++ config?: GBrainConfig;+ 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;- }++export type GraduationOptions = GraduationCommandOptions & GraduationInternals;++type RunOptions = Partial<GraduationCommandOptions> & GraduationInternals;++// ── run context ────────────────────────────────────────────────────────────++interface Run {+ m: GraduationManifest;+ path: string;+ deps: GraduationDeps;- opts: CommonOptions & { drainTimeoutMs?: number; batchBytes?: number; config?: GBrainConfig };++ opts: RunOptions;++ /** True when a live serve handed the source over during this process. */++ serveHandoff: boolean;+ dataDir: string;+ source: GraduationSourceEngine | null;+ lock: LockHandle | null;+ main: BrainEngine | null;+ ddl: BrainEngine | null;+ closeTargets: (() => Promise<void>) | 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, closeTargets: null, resumePause: null, unregister: registerGraduationRunInProcess(m.runId),++ source: null, lock: null, main: null, ddl: null, closeTargets: null, resumePause: null, serveHandoff: false, unregister: registerGraduationRunInProcess(m.runId),+ };+}++function progress(run: Pick<Run, 'opts'>, event: GraduationProgressEvent): void { run.opts.onProgress?.(event); }++function phase(run: Pick<Run, 'opts'>, name: GraduationPhase, total?: number): void {++ run.opts.progress?.phase(name, total);++ progress(run, { phase: name, ...(total !== undefined ? { total } : {}) });++}++++/** SIGINT stops the run at the next boundary before cutover, leaving a resumable state. */++function checkInterrupt(run: Run): void {++ if (!run.opts.signal?.aborted || STATE_RANK[run.m.state] >= STATE_RANK.cutover) return;++ throw opError('interrupted', `The move stopped after an interrupt at ${run.m.state}; it is resumable.`,++ 'Resume it when ready (fix); nothing was cut over and the PGLite brain stays authoritative.',++ { why: 'An interrupt stops the run at the next custody boundary before cutover.',++ fix: { argv: resumeArgv(), consent: [], actor: 'agent', requires_exclusive: true, why: 'Continues from the recorded state.', verify: { argv: STATUS_ARGV } } });++}++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);+}++/**+ * A custody boundary: announced right after the step's durable write+ * (test hooks may SIGKILL here), then the GBRAIN_GRADUATION_PAUSE_AT seam+ * under the same name.+ */+async function boundary(run: Run, name: GraduationBoundary, detail: GraduationBoundaryDetail = {}): Promise<void> {+ await graduationBoundary(name, { runId: run.m.runId, ...detail });+ await pauseSeam(run, name);++ checkInterrupt(run);+}++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)); }+ if (run.closeTargets) { const close = run.closeTargets; run.closeTargets = null; await attempt(close); }+ run.main = null; run.ddl = null;+ 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];++function invokedAs(run: { m: GraduationManifest }): GraduationTargetSpelling { return run.m.invokedAs ?? 'postgres'; }++function spellingOf(run: { m: GraduationManifest }): { to: GraduationTargetSpelling; urlEnv?: string } {++ return { to: invokedAs(run), ...(run.m.routes.urlEnv ? { urlEnv: run.m.routes.urlEnv } : {}) };++}++/** Escape hatches the user passed; every emitted command repeats them so the plan hash matches. */++function hatchArgs(input: Pick<PlanInputs, 'force' | 'triggerBypassOverride' | 'batchBytes'>): string[] {++ return [++ ...(input.triggerBypassOverride ? ['--trigger-bypass', input.triggerBypassOverride === 'session_replication_role' ? 'replica' : 'disable-trigger'] : []),++ ...(input.batchBytes ? ['--batch-size', String(input.batchBytes)] : []),++ ...(input.force ? ['--force'] : []),++ ];+}++// ── plan ───────────────────────────────────────────────────────────────────++interface PlanInputs {+ config: GBrainConfig;+ env: NodeJS.ProcessEnv;+ routes: Routes;+ target: TargetIdentity;- invokedAs: 'postgres' | 'supabase';++ invokedAs: GraduationTargetSpelling;+ force: boolean;+ triggerBypassOverride?: TriggerBypass;+ batchBytes?: number;+}+++function sourceConfig(opts: RunOptions): GBrainConfig {++ const config = opts.config ?? loadConfigFileOnly();++ if (!config) {++ throw opError('no_brain', 'No brain is configured on this machine.', 'Run `gbrain init --pglite --no-embedding` first.',++ { fix: { argv: ['gbrain', 'init', '--pglite', '--no-embedding'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Creates a local PGLite brain.' } });++ }++ return config;++}+++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; }++/** initSchema writes these config keys (plus the copier's deferred-index marker); any other key is user data. */+const SEED_CONFIG_KEYS = new Set(['chunk_strategy', 'embedding_dimensions', 'embedding_model', 'engine', 'version', 'graduation.deferred_indexes']);+async function userConfigKeys(main: BrainEngine): Promise<string[]> {+ const rows = await main.executeRaw<{ key: string }>('SELECT key FROM config ORDER BY key COLLATE "C"');+ return rows.map(r => r.key).filter(key => !SEED_CONFIG_KEYS.has(key));+}++function planArgvFor(input: Pick<PlanInputs, 'invokedAs' | 'routes'>): string[] {- return ['gbrain', 'migrate', '--to', input.invokedAs, '--url-env', urlEnvName(input.routes), '--plan', '--json'];++ return planArgvOf({ to: input.invokedAs, ...(input.routes.urlEnv ? { urlEnv: input.routes.urlEnv } : {}) });+}++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);+ assertTargetReachable(probe, input.routes);+ const layout = source ? await sourceEmbeddingLayout(source) : { columns: [] };+ const userConfig = main && probe.gbrainSchema && !targetOurs ? await userConfigKeys(main) : [];+ const targetAcceptable = targetOurs || (probe.empty && !userConfig.length);+ for (const blocker of targetProbeBlockers(probe, input.routes, layout.columns)) {+ if (blocker.kind === 'target_not_empty' && (targetOurs || input.force)) continue;+ blockers.push(blocker);+ }+ if (userConfig.length && !input.force) {+ blockers.push({ kind: 'target_not_empty', id: 'config', needsUser: true, argv: planArgvFor(input),+ detail: `the target config holds keys initSchema does not write: ${userConfig.slice(0, 10).join(', ')}` });+ }+ const triggerBypass = chooseTriggerBypass(probe, input.triggerBypassOverride) ?? (main && !input.triggerBypassOverride ? await deps.detectTriggerBypass(main) : null);+ if (!triggerBypass && !blockers.some(b => b.kind === 'target_unsupported' && b.id === 'trigger_bypass')) {+ blockers.push({ kind: 'target_unsupported', id: 'trigger_bypass', needsUser: true, detail: 'The requested trigger bypass is not permitted for the target role.' });+ }+ 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),++ nextArgv: runArgvOf({ to: input.invokedAs, ...(input.routes.urlEnv ? { urlEnv: input.routes.urlEnv } : {}) }, planHash, hatchArgs(input)),+ };+}+- function planInputs(deps: GraduationDeps, opts: GraduationPlanOptions): PlanInputs {++function planInputs(deps: GraduationDeps, opts: RunOptions): 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 };++ return { config: sourceConfig(opts), env, routes, target: deps.targetIdentity(routes.mainUrl), invokedAs: opts.to ?? 'postgres',++ force: !!opts.force, triggerBypassOverride: opts.triggerBypass, batchBytes: opts.batchSize };+}++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 } });++ if (state.state === 'graduated') throw engineGraduatedFor(state, 'cli');++ if (state.state === 'split_brain') throw splitBrainFor(state);++ if (state.state === 'in_progress' && state.marker) throw inProgressError({ runId: state.marker.runId, state: state.marker.state, pid: state.marker.pid, dataDir: state.dataDir });+}++/**+ * 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> {++export async function planGraduation(opts: GraduationOptions): Promise<GraduationPlan> {+ const deps = { ...defaultGraduationDeps(), ...opts.deps };+ const input = planInputs(deps, opts);- const dataDir = sourceDataDir(opts.config);++ const dataDir = sourceDataDir(input.config);++ phase({ opts }, 'plan');+ refuseOnPathState(inspectGraduationPath(dataDir));+ let source: GraduationSourceEngine | null = null;+ let targets: { main: BrainEngine; close(): Promise<void> } | null = null;+ try {+ try { source = await deps.openSource(dataDir, { migrate: false }); }+ catch (error) { if (!(error instanceof PgliteBusyError)) throw error; }+ targets = await deps.connectTargets(input.routes);+ return await assemblePlan(deps, input, source, targets.main, false);+ } finally {+ if (source) await source.disconnect();+ if (targets) await targets.close();+ }+}++// ── run ────────────────────────────────────────────────────────────────────++/** Blockers the drain resolves inside --drain-timeout; every other blocker refuses before anything is fenced. */+const DRAIN_RESOLVED_BLOCKERS: ReadonlySet<GraduationBlocker['kind']> = new Set(['request', 'topology_recovery', 'effect_recovery']);+function refusesRun(blocker: GraduationBlocker): boolean { return blocker.needsUser || !DRAIN_RESOLVED_BLOCKERS.has(blocker.kind); }+- 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',- dangling_reference: 'graduation_target_unsupported',- };- 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 blockerRefusal(blocker: GraduationBlocker, run: { m: GraduationManifest; opts: RunOptions }, probe?: TargetProbe): OperationError {++ const spelling = spellingOf(run);++ const host = run.m.routes.main;++ switch (blocker.kind) {++ case 'foreign_host_binding':++ return foreignHostBindingError({ sourceId: blocker.argv?.at(-1) ?? blocker.id, ownerHost: /host ([0-9a-f-]+)/.exec(blocker.detail)?.[1] ?? 'another host', spelling });++ case 'target_not_empty':++ return targetNotEmptyError({ host, tables: (probe?.nonEmptyTables ?? [blocker.id]).map(relation => ({ relation, rows: -1 })), spelling });++ case 'unsupported_platform':++ return unsupportedPlatformError({ platform: process.platform });++ case 'embedding_dimension': {++ const m = /source (\S+), target (\S+)/.exec(blocker.detail);++ return embeddingDimensionMismatchError({ column: blocker.id, source: m?.[1] ?? 'unknown', target: m?.[2] ?? 'unknown', host, spelling });++ }++ case 'target_unsupported':++ case 'env_override':++ return targetUnsupportedError({ requirement: blocker.kind === 'env_override' ? 'env_override' : blocker.id, detail: blocker.detail, host, spelling });++ case 'writer_held':++ return sourceWriterHeldError({ owner: null, rerun: runArgvOf(spelling, run.m.planHash) });++ default:++ return drainTimeoutError({ blockers: [blocker], timeoutSec: Math.ceil((run.opts.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS) / 1000) });++ }+}+- function planArgv(run: { m: GraduationManifest }): string[] {- return ['gbrain', 'migrate', '--to', invokedAs(run), '--url-env', urlEnvName(run.m.routes), '--plan', '--json'];++function planArgv(run: { m: GraduationManifest }, extra: readonly string[] = []): string[] {++ return planArgvOf(spellingOf(run), extra);+}++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);++ const holder = inspectLockHolder(run.dataDir);++ const owner = liveServeOwner(error) ?? (peek.held && peek.isServe && peek.pid ? { pid: peek.pid, transport: peek.http ? 'http' as const : 'stdio' as const, is_self: false } : null);++ return sourceWriterHeldError({ owner, ...(peek.pid ? { pid: peek.pid } : {}), ...(holder.subcommand ? { subcommand: holder.subcommand } : {}),++ rerun: runArgvOf(spellingOf(run), run.m.planHash) });+}++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);++ run.serveHandoff = true;+ 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 } });- }++ if (!resume) throw inProgressError({ runId: run.m.runId, state: run.m.state, dataDir: run.dataDir });+ run.resumePause = resume;+}++function recordedRoutes(run: Run): Routes {+ const urls = run.m.targetUrls;+ if (!urls) throw new Error('The graduation manifest has no target URLs.');+ return { ...run.m.routes, mainUrl: urls.main, ddlUrl: urls.ddl };+}++async function openTargets(run: Run): Promise<void> {+ if (run.main && run.ddl) return;+ const targets = await run.deps.connectTargets(recordedRoutes(run));+ run.main = targets.main; run.ddl = targets.ddl; run.closeTargets = targets.close;+}++/** 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> {++ phase(run, 'quiesce');+ 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 } } });- }++ if (plan.planHash !== expect) throw previewChanged(run, hatchArgs(input), plan.planHash);+ const blocker = plan.blockers.find(refusesRun);+ 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);+}+++function previewChanged(run: { m: GraduationManifest }, extra: readonly string[], freshHash: string): OperationError {++ return opError('preview_changed', 'The brain or target changed since the approved plan; nothing was moved.',++ 'Show the user the fresh plan (fix) and run the move with its plan_hash after they agree.',++ { why: 'The approval binds identities, inventory, person-needed blockers, trigger bypass and target emptiness; one of them changed.',++ fix: { argv: planArgv(run, extra), consent: [], actor: 'agent', requires_exclusive: false, plan_hash: freshHash,++ why: 'Shows the fresh read-only plan and its plan_hash.', verify: { argv: planArgv(run, extra) } } });++}+++/** Step 1 on resume: same custody, recorded identities; before cutover the recorded approval must still match. */+async function quiesceResume(run: Run): Promise<void> {++ phase(run, 'quiesce');+ 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}.` });++ throw splitBrainFor({ dataDir: run.dataDir, movedTo: existsSync(graduatedPath(run.dataDir, run.m.runId)) ? graduatedPath(run.dataDir, run.m.runId) : null });+ }+ 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 config = run.opts.config ?? loadConfigFileOnly() ?? ({ 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,++ invokedAs: invokedAs(run), force: false, triggerBypassOverride: run.m.triggerBypass, batchBytes: run.m.batchSize,+ };+ 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(refusesRun);+ 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 } } });- }++ if (!run.m.force && plan.planHash !== run.m.planHash) throw previewChanged(run, [], plan.planHash);+}++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 withSourceWritable(run.source!, tx => setSourceState(tx, run.m.runId, 'quiesced'));+ 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 withSourceWritable(run.source!, tx => setSourceState(tx, run.m.runId, 'quiesced', { sourceBrainId: run.m.source.brainId || null, sourceDataDir: run.dataDir }));+ advance(run, 'quiesced');+ await boundary(run, 'quiesced');+}++async function stepDrain(run: Run): Promise<void> {+ if (run.m.state !== 'draining') advance(run, 'draining');++ phase(run, 'drain');+ await boundary(run, 'drain_started');+ 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(blockers, timeoutMs);++ const { blockers } = await run.deps.drainForGraduation(run.source!, { timeoutMs, hostId: run.m.source.hostId, config: sourceConfig(run.opts) });++ if (blockers.length) throw drainTimeoutError({ blockers, timeoutSec: Math.ceil(timeoutMs / 1000) });+ 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);+ await boundary(run, 'drained');+}++/** 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'>>;++ phase(run, 'schema');+ 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 = recordedRoutes(run);- 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');++ if (existing && !reuse) throw notEmpty(run, [{ relation: `persistence_graduation (run ${existing.run_id}, ${existing.state})`, rows: 1 }]);++ if (!existing) {++ const probe = await run.deps.probeTarget(routes);++ if (!probeTargetEmpty(probe) && !opts.force) throw notEmpty(run, await tableCounts(main!, probe.nonEmptyTables));++ }+ 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) {++ const probe = await run.deps.probeTarget(routes);++ if (!probeTargetEmpty(probe)) throw notEmpty(run, await tableCounts(main!, probe.nonEmptyTables));++ }+ if (opts.force) await wipeUncopiedTables(run);+ await boundary(run, 'target_fenced');+ 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) } });++function notEmpty(run: Run, tables: readonly { relation: string; rows: number }[]): OperationError {++ return targetNotEmptyError({ host: run.m.routes.main, tables, spelling: spellingOf(run) });++}++++async function tableCounts(engine: BrainEngine, relations: readonly string[]): Promise<Array<{ relation: string; rows: number }>> {++ const out: Array<{ relation: string; rows: number }> = [];++ for (const relation of relations.slice(0, 10)) {++ const [q] = 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 (!q?.q) continue;++ const [n] = await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM ${q.q}`);++ out.push({ relation, rows: Number(n?.n ?? 0) });++ }++ return out;+}++/** 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'));+ }+ 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'));++ phase(run, 'copy', pending.length);+ if (pending.length) await run.deps.deferIndexes(run.main!, { runId: run.m.runId });++ const sourceRows = new Map((run.m.sourceReceipts ?? []).map(r => [r.relation, r.rows]));+ let done = order.length - pending.length;+ for (const entry of pending) {++ checkInterrupt(run);+ setCheckpoint(run, entry.relation, { state: 'copying', batches: 0, disabledTriggers: run.m.triggerBypass === 'disable_trigger' });++ run.opts.progress?.table(entry.relation, sourceRows.get(entry.relation) ?? 0);+ let batches = 0;- await run.deps.copyTable(engines, entry, { bypass: run.m.triggerBypass, batchBytes: run.opts.batchBytes, runId: run.m.runId,++ await run.deps.copyTable(engines, entry, { bypass: run.m.triggerBypass, batchBytes: run.m.batchSize, runId: run.m.runId,+ onBatch: rows => {+ batches += 1;++ run.opts.progress?.batch(entry.relation, rows);+ progress(run, { phase: 'copy', relation: entry.relation, rows, done, total: order.length });+ void graduationBoundary('batch_copied', { runId: run.m.runId, relation: entry.relation, batch: batches });++ checkInterrupt(run);+ } });+ setCheckpoint(run, entry.relation, { state: 'copied', batches });+ done += 1;+ await boundary(run, 'table_copied', { relation: entry.relation });+ }+ await run.deps.copySequences(engines, { runId: run.m.runId });++ phase(run, 'indexes');+ await run.deps.buildDeferredIndexes(run.ddl!, { runId: run.m.runId, log: line => progress(run, { phase: 'index', message: line }) });+ const disabled = run.m.tables.filter(t => t.disabledTriggers).map(t => t.relation);+ if (disabled.length) {+ await run.deps.reenableTriggers(run.main!, disabled, { runId: run.m.runId });+ 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);+ await boundary(run, 'copied');+}++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'));+ const started = Date.now();+ await run.deps.assertRelationSet(run.main!, 'postgres', run.deps.inventory);++ phase(run, 'verify');+ 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,+ runId: run.m.runId, expectFence: true,- runDoctor: () => run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main),++ runDoctor: () => { phase(run, 'doctor'); return 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)));++ throw verifyFailedError({ failures: result.failures, repeated });+ }+ 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 boundary(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> {++ phase(run, 'cutover');+ await run.deps.copySequences({ source: run.source!, target: run.main! }, { runId: run.m.runId });+ 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 withSourceWritable(run.source!, tx => setSourceState(tx, run.m.runId, 'cutover', { cutoverSequence: seq?.s ?? '0' }));+ if (run.m.state !== 'cutover') advance(run, 'cutover', { sourceEnabled: brain?.enabled === true, cutoverSequence: seq?.s ?? '0' });+ await boundary(run, 'source_cutover');+ const source = run.source!;+ run.lock = await source.closeRetainingLock();+ run.source = null;+ await source.disconnect();+ await boundary(run, 'source_closed');+ moveAsideHeld(run.dataDir, run.lock, run.m.runId);+ await boundary(run, 'moved_aside');+ 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));++ if (error instanceof TombstonePathOccupiedError) throw splitBrainFor(inspectGraduationPath(run.dataDir));+ throw error;+ }+ }+ advance(run, 'tombstoned', { graduatedAt: run.m.graduatedAt ?? new Date().toISOString() });+ await boundary(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);++ if (state.state === 'split_brain' || readTombstone(run.dataDir)?.runId !== run.m.runId) throw splitBrainFor(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 boundary(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> {++ phase(run, 'flip');+ 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);+ await boundary(run, 'config_flipped');+ 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 }; });+ if (mounts.length) { run.m.rewrittenMounts = [...new Set([...(run.m.rewrittenMounts ?? []), ...mounts])]; save(run); }+ await boundary(run, 'registry_rewritten');+ advance(run, 'graduated');+ await boundary(run, 'graduated');+}++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!);++ const doctor = (row?.doctor ?? {}) as { source?: readonly string[]; target?: readonly string[] };+ 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 };++ triggerBypass: run.m.triggerBypass, replay: row?.replay_probe ?? { status: 'not_available', reason: 'no_uncompacted_request' }, timings: run.m.timings,++ targetDisplayUrl: run.m.routes.main, retainedPath: graduatedPath(run.dataDir, run.m.runId), serveHandoff: run.serveHandoff,++ doctor: { source: doctor.source ?? [], target: doctor.target ?? [] } };+}++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);++ if (run.m.state === 'cutover' || run.m.state === 'tombstoned') {++ let path = inspectGraduationPath(run.dataDir);++ if (path.state === 'split_brain') {++ if (!run.opts.yes) throw splitBrainFor(path);++ moveStrayAside(run);++ path = inspectGraduationPath(run.dataDir);++ }+ 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);+}+++/**++ * `--resume --yes` after the user decided about a stray datastore at the old++ * path: move it to `<path>.stray-<run_id>` (never deleted) so the tombstone++ * can be written and the move can finish.++ */++function moveStrayAside(run: Run): void {++ const stray = `${run.dataDir}.stray-${run.m.runId}`;++ if (existsSync(stray)) throw splitBrainFor(inspectGraduationPath(run.dataDir));++ renameSync(run.dataDir, stray);++ fsyncParent(run.dataDir);++ progress(run, { phase: 'split_brain', message: `moved the stray datastore to ${stray}` });++}+++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,++ ...(input.batchBytes ? { batchSize: input.batchBytes } : {}),+ };+}++/** 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> {++export async function runGraduation(opts: GraduationOptions): 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);++ const dataDir = sourceDataDir(input.config);+ refuseOnPathState(inspectGraduationPath(dataDir));++ const expect = opts.yes ? opts.expectPlanHash : undefined;++ if (!expect) {++ const fresh = await planGraduation(opts);++ throw opError('confirmation_required', 'Moving this brain to Postgres needs the user\'s approval of the plan; nothing was changed.',++ 'Show the user the plan and run the command in fix after they agree.',++ { why: 'The move copies the brain to another database and fences this one; it runs only against an approved plan_hash.',++ fix: { argv: [...fresh.nextArgv], consent: ['egress', 'destructive'], actor: 'agent', requires_exclusive: true, plan_hash: fresh.planHash,++ preview_argv: planArgvFor(input), why: 'Runs the move against the approved plan.', verify: { argv: STATUS_ARGV } } });++ }+ if (existing) renameSync(path, `${path.replace(/\.json$/, '')}.${existing.runId}.json`);- const manifest = newManifest(input, opts.expect, randomUUID());++ const manifest = newManifest(input, expect, randomUUID());+ manifest.inventoryVersion = deps.inventory.version;+ const run = newRun(manifest, path, { ...opts, deps });+ try {- try { await quiesceFresh(run, input, opts.expect); }++ try { await quiesceFresh(run, input, 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.' });++ if (marker && markerLiveness(marker) === 'alive') return inProgressError({ runId: m.runId, state: m.state, pid: marker.pid, dataDir: m.source.dataDir });++ return interruptedError({ runId: m.runId, state: m.state, dataDir: m.source.dataDir });+}+- function loadRun(opts: CommonOptions & { url?: string; urlEnv?: string }): Run {++function loadRun(opts: RunOptions): 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> {++export async function resumeGraduation(opts: RunOptions = {}): 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 (path.state === 'split_brain' && !(run.opts.yes && (run.m.state === 'cutover' || run.m.state === 'tombstoned'))) throw splitBrainFor(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> {++export async function reconcileGraduation(opts: RunOptions = {}): 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> {++export async function rollbackGraduation(opts: RunOptions = {}): Promise<GraduationRollbackResult> {+ const run = loadRun(opts);+ try {++ phase(run, 'rollback');+ await reconcileRun(run);+ const state = run.m.state;- if (state === 'rolled_back' || state === 'abandoned') return { runId: run.m.runId, state, dropped: [] };++ if (state === 'rolled_back') return { state, restoredPath: run.dataDir, dropped: [] };++ if (state === 'abandoned') return { state, restoredPath: null, 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 withSourceWritable(run.source!, tx => setSourceState(tx, run.m.runId, 'rolled_back'));+ }+ 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: [] };++ return { state: 'abandoned', restoredPath: null, dropped: [] };+}+- async function rollbackAfterCutover(run: Run, opts: GraduationRollbackOptions): Promise<GraduationRollbackResult> {++async function rollbackAfterCutover(run: Run, opts: RunOptions): 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 boundary(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)) {++ if (!(opts.yes && opts.expectPlanHash === hash)) {+ await returnToAuthority(run);+ throw rollbackLostError(run, confirmable, hash);+ }+ }+ await approveAndRestore(run);- return { runId: run.m.runId, state: 'rolled_back', dropped: losses };++ return { state: 'rolled_back', restoredPath: run.dataDir,++ dropped: losses.filter(l => l.lossKind === 'operational').map(l => ({ relation: l.relation, rows: l.rows, lossKind: l.lossKind })) };+}++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 boundary(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 boundary(run, 'source_restoring');+ const movedTo = graduatedPath(run.dataDir, run.m.runId);+ if (readTombstone(run.dataDir)) { removeTombstone(run.dataDir, run.m.runId); await boundary(run, 'tombstone_removed'); }+ if (existsSync(movedTo)) {- if (existsSync(run.dataDir)) throw graduationSplitBrainError(inspectGraduationPath(run.dataDir));++ if (existsSync(run.dataDir)) throw splitBrainFor(inspectGraduationPath(run.dataDir));+ moveHeldPglite(movedTo, run.dataDir, run.lock!);+ await boundary(run, 'renamed_back');+ }+ 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 withSourceWritable(source, tx => setSourceState(tx, run.m.runId, 'rolled_back'));+ }+ 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 }; });+ await boundary(run, 'config_restored');+ 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);+ await boundary(run, 'rolled_back');+}++/** 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);++function rollbackLostError(_run: Run, losses: readonly RollbackLoss[], hash: string | null): OperationError {++ return rollbackWritesLostError({ losses: losses.map(l => ({ relation: `${l.relation} ${l.change}`, rows: l.rows })), final: hash === null, ...(hash ? { planHash: hash } : {}) });+}++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;+ // persistence_brain.enabled legitimately differs after cutover: digest it through its transform, like the receipt.+ const now = await run.deps.digestTable(run.main!, entry, { applyTransforms: entry.relation === 'persistence_brain' });+ 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> {++/**++ * `gbrain migrate --status`: never reconciles, migrates, repairs fences,++ * rewrites routing or touches graduation markers. It reads the manifest, the++ * marker and tombstone, and the target row through a read-only session; for++ * split brain it also opens both datastores read-only for their row counts.++ */++export async function graduationStatus(opts: Pick<GraduationInternals, 'manifestPath' | 'config' | 'deps'> = {}): Promise<GraduationStatusDoc> {+ const m = readGraduationManifest(opts.manifestPath ?? graduationManifestPath());- const configured = opts.config === undefined ? loadConfigFileOnly() : opts.config;++ const configured = opts.config ?? loadConfigFileOnly();+ 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';++ const liveRun = path?.marker && path.liveness === 'alive' ? { pid: path.marker.pid } : null;+ 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.' };++ return { schema_version: 1, state: 'none', runId: path?.marker?.runId ?? null, to: 'postgres', source: null, sourcePath: path, target: null, receipt: null,++ liveRun, tables: [], nextArgv: path?.state === 'graduated' ? ['gbrain', 'config', 'set', 'database_url', '<target_url>'] : null };++ }++ const deps = { ...defaultGraduationDeps(), ...opts.deps };++ let row: Awaited<ReturnType<typeof readGraduationRow>> = null;++ let reachable = false;++ if (m.targetUrls) {++ try {++ const targets = await deps.connectTargets({ ...m.routes, mainUrl: m.targetUrls.main, ddlUrl: m.targetUrls.ddl });++ try { row = await targets.main.transaction(async tx => { await tx.executeRaw('SET TRANSACTION READ ONLY'); return readGraduationRow(tx); }); reachable = true; }++ finally { await targets.close(); }++ } catch { reachable = false; }+ }++ const ours = row?.role === 'target' && row.run_id === m.runId ? row : null;++ const receipt: GraduationReceipt | null = ours?.table_receipts ? {++ runId: m.runId, state: ours.state as GraduationReceipt['state'], tables: ours.table_receipts, triggerBypass: m.triggerBypass,++ replay: ours.replay_probe ?? { status: 'not_available', reason: 'no_uncompacted_request' }, timings: m.timings,++ targetDisplayUrl: m.routes.main, retainedPath: graduatedPath(m.source.dataDir, m.runId),++ } : null;++ const to = m.invokedAs ?? 'postgres';+ 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 ?? '' };++ : path?.state === 'split_brain' ? resumeArgv(['--yes'])++ : liveRun ? STATUS_ARGV++ : STATE_RANK[m.state] >= STATE_RANK.rollback_fenced ? ['gbrain', 'migrate', '--rollback-to-source'] : resumeArgv();++ return {++ schema_version: 1, state: m.state, runId: m.runId, to, source: m.source, sourcePath: path,++ target: { identity: m.target, displayUrl: m.routes.main, row: (ours?.state ?? null) as TargetRowState | null, reachable },++ receipt, liveRun, tables: m.tables,++ ...(path?.state === 'split_brain' ? { splitBrain: await splitBrainSides(deps, path, m) } : {}),++ nextArgv,++ };++}++++/** Both datastores of a split brain, opened read-only for row counts and newest page writes. */++async function splitBrainSides(deps: GraduationDeps, path: GraduationPathState, m: GraduationManifest): Promise<NonNullable<GraduationStatusDoc['splitBrain']>> {++ const sides = [path.dataDir, graduatedPath(m.source.dataDir, m.runId)];++ const out: Array<NonNullable<GraduationStatusDoc['splitBrain']>[number]> = [];++ for (const side of sides) {++ const entry = { path: side, brainId: null as string | null, rows: 0, newestWriteAt: null as string | null };++ if (!existsSync(side)) continue;++ const release = allowGraduationInspection(side);++ try {++ const engine = await deps.openSource(side, { migrate: false });++ try {++ const [brain] = await engine.executeRaw<{ brain_id: string }>(`SELECT brain_id::text AS brain_id FROM persistence_brain WHERE singleton = 1`).catch(() => []);++ const [pages] = await engine.executeRaw<{ n: string; newest: string | null }>(`SELECT count(*)::text AS n, max(updated_at)::text AS newest FROM pages`).catch(() => []);++ Object.assign(entry, { brainId: brain?.brain_id ?? null, rows: Number(pages?.n ?? 0), newestWriteAt: pages?.newest ?? null });++ } finally { await engine.disconnect(); }++ } catch { /* unreadable side: reported with what the filesystem shows */ } finally { release(); }++ out.push(entry);++ }++ return out;}-export async function planGraduation(_opts: GraduationCommandOptions): Promise<GraduationPlan> { return notMerged('planGraduation'); }-export async function runGraduation(_opts: GraduationCommandOptions): Promise<GraduationReceipt> { return notMerged('runGraduation'); }-export async function graduationStatus(): Promise<GraduationStatusDoc> { return notMerged('graduationStatus'); }-export async function resumeGraduation(_opts: GraduationCommandOptions): Promise<GraduationReceipt> { return notMerged('resumeGraduation'); }-export async function rollbackGraduation(_opts: GraduationCommandOptions): Promise<GraduationRollbackResult> { return notMerged('rollbackGraduation'); }-export async function reconcileGraduation(): Promise<void> { return notMerged('reconcileGraduation'); }+export type { InventoryEntry };diff --cc src/core/persistence/engine-graduation.types.tsindex 3b267ef768,42bbb622ba..74db18ff47--- a/src/core/persistence/engine-graduation.types.ts+++ b/src/core/persistence/engine-graduation.types.ts@@@ -218,25 -218,6 +218,27 @@@ export interface GraduationManifesttimings: 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[];++ /** `--batch-size`: copy batch size in bytes (part of the plan hash). */++ batchSize?: number;+ /** 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). */@@@ -324,33 -305,86 +326,92 @@@ export interface GraduationReceipttriggerBypass: TriggerBypass;replay: ReplayProbeResult;timings: Record<string, number>;+ /** Redacted target URL (never the password); the success output names it. */+ targetDisplayUrl?: string;+ /** Where the source data dir was moved (`<path>.graduated-<run_id>`). */+ retainedPath?: string;+ /** True when a live serve handed the source over through the intent marker. */+ serveHandoff?: boolean;+ /** Failing doctor check names on each side; the cutover gate is `target` empty. */+ doctor?: { source: readonly string[]; target: readonly string[] };}- /** What `inspectGraduationPath` sees at a PGLite data dir path, without opening or locking it. */+ // ── CLI <-> orchestrator (src/commands/migrate-graduation.ts consumes; engine-graduation.ts implements) ──++ /** The `--to` spelling the user typed; every emitted command echoes it. */+ export type GraduationTargetSpelling = 'postgres' | 'supabase';++ /** graduation-custody.ts `inspectGraduationPath(dataDir)`: file reads only, never a lock attempt. */export interface GraduationPathState {- kind: 'none' | 'in_progress' | 'interrupted' | 'graduated' | 'split_brain';dataDir: string;+ state: 'none' | 'in_progress' | 'interrupted' | 'graduated' | 'split_brain';marker: IntentMarker | null;tombstone: Tombstone | null;+ /** Liveness of the marker's requesting process; null without a non-terminal marker. */- liveness: 'alive' | 'dead' | 'unknown' | null;++ liveness?: 'alive' | 'dead' | 'unknown' | null;+ /** The `<dataDir>.graduated-<run_id>` directory when it exists. */- movedTo: string | null;- detail: string;++ movedTo?: string | null;++ /** One-line explanation for refusals and --status. */++ detail?: string;}- /** `gbrain migrate --status --json`: read-only, never reconciles. */+ export type GraduationPhase =+ | 'plan' | 'quiesce' | 'drain' | 'schema' | 'copy' | 'indexes' | 'verify' | 'doctor' | 'cutover' | 'flip' | 'rollback';++ /** Progress callbacks the CLI wires to createProgress (stderr); the orchestrator calls them. */+ export interface GraduationProgressSink {+ phase(phase: GraduationPhase, total?: number): void;+ /** A carried table starts copying (or digesting) with this many source rows. */+ table(relation: string, rows: number): void;+ /** One batch of `rows` rows finished for the current table. */+ batch(relation: string, rows: number): void;+ }++ /** Options every orchestrator entry point takes (plan, run, resume, rollback). */+ export interface GraduationCommandOptions {+ to: GraduationTargetSpelling;+ /** Full target URL from `--url` / `--url -`; never printed. */+ url?: string;+ /** `--url-env <VAR>`: the env var name printed in every emitted command. */+ urlEnv?: string;+ drainTimeoutMs: number;+ triggerBypass?: TriggerBypass;+ batchSize?: number;+ force: boolean;+ /** `--expect <plan_hash>`: the plan (or rollback loss list) the user approved. */+ expectPlanHash?: string;+ /** `--yes`: the user approved; without `expectPlanHash` the orchestrator refuses destructive steps. */+ yes: boolean;+ progress?: GraduationProgressSink;+ /** SIGINT: stop at the next batch boundary, leave a resumable state, throw `interrupted`. */+ signal?: AbortSignal;+ }++ /** `gbrain migrate --status --json` (zero mutations). */export interface GraduationStatusDoc {+ schema_version: 1;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;+ to: GraduationTargetSpelling;+ source: SourceIdentity | null;+ sourcePath: GraduationPathState | null;+ target: { identity: TargetIdentity; displayUrl: string; row: TargetRowState | null; reachable: boolean } | null;+ receipt: GraduationReceipt | null;+ /** A live process owns the run (its kernel lock is held). */+ liveRun: { pid: number } | null;+ tables: readonly TableCheckpoint[];+ /** graduation_split_brain: both paths side by side so the agent can relay a concrete choice. */+ splitBrain?: readonly { path: string; brainId: string | null; rows: number; newestWriteAt: string | null }[];+ /** The next command for this state (resume, rollback, nothing), echoing the user's spelling. */nextArgv: readonly string[] | null;- detail: string;+ }++ export interface GraduationRollbackResult {+ state: 'abandoned' | 'rolled_back';+ /** The PGLite data dir that is authoritative again (null before cutover: it never moved). */+ restoredPath: string | null;+ /** Operational differences dropped by the rollback (telemetry, logs, queue state). */+ dropped: readonly { relation: string; rows: number; lossKind: LossKind }[];}export interface GraduationEngines {diff --cc src/core/persistence/graduation-copy.tsindex 2a8f8d9813,2a8f8d9813..68f6456990--- a/src/core/persistence/graduation-copy.ts+++ b/src/core/persistence/graduation-copy.ts@@@ -31,7 -31,7 +31,7 @@@ import { ANN_BUILD_MESSAGE, buildDeferrimport type { ColumnMeta, GraduationEngines, Inventory, InventoryEntry, TriggerBypass } from './engine-graduation.types.ts';import { digestPlan, quoteIdent, tableColumns, withDigestSession, type DigestPlan } from './graduation-digest.ts';import { fkClosure, GRADUATION_INVENTORY } from './graduation-inventory.ts';--import { graduationError } from './graduation-target.ts';++import { targetUnsupportedError } from './graduation-errors.ts';/** Target-owned config row holding the deferred index list; the config copy never deletes it. */export const GRADUATION_DEFERRED_INDEXES_KEY = 'graduation.deferred_indexes';@@@ -81,11 -81,11 +81,9 @@@ export function columnContract(entry: Pif (!sourceNames.has(column.name) && !(column.name in allow)) problems.push(`${column.name} (${column.type}) exists only on the target`);}if (problems.length) {-- throw graduationError('graduation_target_unsupported', `The target's ${entry.relation} columns do not match the source.`,-- 'Use an empty target database created by this gbrain version; the column contract never copies into a different shape.',-- { why: `Graduation copies every column verbatim; ${entry.relation}: ${problems.join('; ')}.`, detail: problems.join('; '),-- fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--plan', '--json'], consent: [], actor: 'agent', requires_exclusive: false,-- why: 'Re-plans after the target is replaced or its schema is upgraded.' } });++ const error = targetUnsupportedError({ requirement: 'column', detail: `the ${entry.relation} columns do not match the source (${problems.join('; ')})`, host: 'the target' });++ error.detail = problems.join('; ');++ throw error;}return copied;}diff --cc src/core/persistence/graduation-custody.tsindex 92c9884b0e,3d76b07f65..f03d1a6636--- a/src/core/persistence/graduation-custody.ts+++ b/src/core/persistence/graduation-custody.ts@@@ -1,421 -1,43 +1,375 @@@/**- * STUB (G3 CLI lane). The G2a lane owns this module; the integrator replaces- * this file with G2a's implementation. Only `inspectGraduationPath` is- * stubbed (file reads per the plan's marker and tombstone formats) so the- * CLI, serve and doctor consumers can be exercised before G2a merges.+ * 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 { readFileSync, statSync } from 'node:fs';-import type { GraduationPathState, IntentMarker, Tombstone } from './engine-graduation.types.ts';+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 type { OperationError } from '../ops/contract.ts';++import { engineGraduatedError, inProgressError, interruptedError, splitBrainError } from './graduation-errors.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';++import type { GraduationPathState, IntentMarker, ManifestState, TargetIdentity, 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 `${dataDir}.gbrain-graduation.json`;+ 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)); }-function readJson<T>(path: string): T | null {- try { return JSON.parse(readFileSync(path, 'utf8')) as T; } catch { return null; }+/** 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);}-function pidAlive(pid: number): boolean {- try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }+// ── 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); }++const inspectionPaths = new Set<string>();++/** `--status` on a split brain: let this process open `dataDir` read-only despite the refusal (counts only). */++export function allowGraduationInspection(dataDir: string): () => void {++ const path = graduationDataDir(dataDir);++ inspectionPaths.add(path);++ return () => { inspectionPaths.delete(path); };++}+++// ── 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 {- return readJson<IntentMarker>(intentMarkerPath(dataDir));+ 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 (!statSync(dataDir).isFile()) return null;- } catch {- return null;- }- const t = readJson<Tombstone>(dataDir);- return t?.kind === 'gbrain-engine-graduated' ? t : null;+ 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 marker = readIntentMarker(dataDir);- const tombstone = readTombstone(dataDir);- if (tombstone) return { dataDir, state: 'graduated', marker, tombstone };- if (!marker) return { dataDir, state: 'none', marker, tombstone };- if (marker.state === 'graduated' || marker.state === 'rolled_back' || marker.state === 'abandoned') return { dataDir, state: 'none', marker, tombstone };- return { dataDir, state: pidAlive(marker.pid) ? 'in_progress' : 'interrupted', marker, tombstone };+ 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, state: '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.` };++ return { ...base, state: '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 };++ return { ...base, state: '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, state: '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: '' };++ return { ...base, state: '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,++ return { ...base, state: '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,++ return { ...base, state: 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, state: '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}).` };++ return { ...base, state: '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;++ if (state.state === 'none' || inspectionPaths.has(state.dataDir)) 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 (state.state === 'graduated') throw engineGraduatedFor(state, 'cli');++ if (state.state === 'split_brain') throw splitBrainFor(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') {++ if (state.state === 'in_progress' && state.liveness === 'alive') throw inProgressFor(state);++ if (state.state === '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' });- }++ if (holder.held && holder.subcommand === 'migrate') throw inProgressFor(state);+ }+ 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 });++ throw interruptedError({ runId: state.marker.runId, state: state.marker.state, dataDir: state.dataDir });++}++++function inProgressFor(state: GraduationPathState): OperationError {++ return inProgressError({ runId: state.marker?.runId, state: state.marker?.state, pid: state.marker?.pid, dataDir: state.dataDir });++}++++/** `engine_graduated` for a tombstoned path; the graduating host (its marker names the tombstone's run, not yet graduated) gets `--resume`. */++export function engineGraduatedFor(state: GraduationPathState, transport: 'cli' | 'stdio' | 'http'): OperationError {++ return engineGraduatedError({ tombstone: state.tombstone, dataDir: state.dataDir, transport,++ graduatingHost: state.marker?.runId !== undefined && state.marker.runId === state.tombstone?.runId && state.marker.state !== 'graduated' });++}++++/** `graduation_split_brain`: a stray datastore at the old path next to the run's retained copy. */++export function splitBrainFor(state: Pick<GraduationPathState, 'dataDir' | 'movedTo'>, strayRows?: number): OperationError {++ return splitBrainError({ sourcePath: state.dataDir, strayPath: state.dataDir, ...(state.movedTo ? { retainedPath: state.movedTo } : {}), ...(strayRows !== undefined ? { strayRows } : {}) });+}++// ── 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' });++ throw inProgressError({ runId: row.run_id, state: row.state });+ }+ 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.' });++ throw cutoverSourceRefusal(row.run_id, row.source_data_dir);++}++++function cutoverSourceRefusal(runId: string, sourceDataDir: string | null): OperationError {++ const path = sourceDataDir ? inspectGraduationPath(sourceDataDir) : null;++ if (path?.state === 'graduated') return engineGraduatedFor(path, 'cli');++ return interruptedError({ runId, state: 'cutover', ...(sourceDataDir ? { dataDir: sourceDataDir } : {}) });+}++/**+ * 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' });++ throw inProgressError({ runId: row.run_id, state: row.state });+ }+ 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.' });++ throw cutoverSourceRefusal(row.run_id, row.source_data_dir);}diff --cc src/core/persistence/graduation-drain.tsindex 9b65f113bf,3714230c79..90a4d25bc4--- a/src/core/persistence/graduation-drain.ts+++ b/src/core/persistence/graduation-drain.ts@@@ -12,8 -12,8 +12,6 @@@ import { PersistenceConsumer } from './import { disposePersistenceConsumer, preparePersistedMutation } from './service.ts';import { readWriterAdminLock } from './admin-lock.ts';import type { GraduationBlocker } from './engine-graduation.types.ts';--import { graduationError } from './graduation-target.ts';--import type { OperationError } from '../ops/contract.ts';const PENDING_REQUESTS_SQL = `SELECT r.request_id::text AS request_id, r.source_id, r.operation, r.state,r.recovery IS NOT NULL AS recovering, w.owner_host_id::text AS owner_host_id@@@ -133,24 -133,24 +131,6 @@@ export async function drainForGraduatioreturn { drained: terminal.map(r => r.request_id), blockers };}--/** The `--drain-timeout` refusal: resumable when every blocker is still progressing, otherwise the first person-needed action. */--export function drainTimeoutError(blockers: readonly GraduationBlocker[], timeoutMs: number): OperationError {-- const seconds = Math.max(1, Math.ceil(timeoutMs / 1000));-- const needsPerson = blockers.find(b => b.needsUser || b.argv);-- const resume = ['gbrain', 'migrate', '--resume', '--drain-timeout', String(seconds * 2), '--json'];-- const listed = blockers.slice(0, 10).map(b => `${b.kind} ${b.id} (${b.detail})${b.argv ? `: ${b.argv.join(' ')}` : ''}`).join(' | ');-- return graduationError('graduation_drain_timeout', `The drain did not finish within ${seconds}s; ${blockers.length} item(s) remain.`,-- needsPerson ? `Clear ${needsPerson.kind} ${needsPerson.id} first (${needsPerson.argv?.join(' ') ?? 'see detail'}), then resume.` : `Resume with a longer drain: ${resume.join(' ')}.`,-- { why: `Graduation copies only a drained brain; the source is unchanged and still writable. Remaining: ${listed}`,- detail: listed,- detail: listed, reason: needsPerson ? 'blocked' : 'progressing',-- fix: needsPerson?.argv-- ? { argv: [...needsPerson.argv], consent: [], actor: needsPerson.needsUser ? 'user' : 'agent', requires_exclusive: false,-- why: `Clears ${needsPerson.kind} ${needsPerson.id}, which the request-only drain cannot finish.`,-- verify: { argv: ['gbrain', 'migrate', '--status', '--json'] } }-- : { argv: resume, consent: [], actor: 'agent', requires_exclusive: true, why: 'Every remaining request is still progressing; a longer drain finishes it.',-- verify: { argv: ['gbrain', 'migrate', '--status', '--json'] } } });--}--/*** Freezes the PGLite source after the drain: the resident consumer is stopped* and the single connection defaults to read-only transactions, so anydiff --cc src/core/persistence/graduation-errors.tsindex 0000000000,d8c1cf2a37..2e473e0c61mode 000000,100644..100644--- a/src/core/persistence/graduation-errors.ts+++ b/src/core/persistence/graduation-errors.ts@@@ -1,0 -1,364 +1,364 @@@+ /**+ * Engine graduation refusals (PGLite -> Postgres): one builder per+ * GRADUATION_ERROR_CODES entry. Every builder returns an `opError` with a+ * `why`, a filled `fix` (`argv` or deliberately none for `report`), a+ * read-only `fix.verify` and the guide anchor, and says when to ask the user.+ * Emitted commands echo the `--to` spelling the user typed and name the target+ * URL only through `--url-env <VAR>`; no builder ever receives a URL with a+ * password.+ *+ * The orchestrator, the CLI, serve and doctor all build refusals here so each+ * code renders one way on every surface (test/graduation-errors.test.ts).+ */+ import type { Action } from '../agent-output.ts';+ import { exclusiveFix } from '../exclusive-fix.ts';+ import type { LockOwner } from '../readiness.ts';+ import { opError, type OperationError } from '../ops/contract.ts';+ import type {+ GraduationBlocker, GraduationErrorCode, GraduationTargetSpelling, Tombstone, VerifyFailure,+ } from './engine-graduation.types.ts';++ export const GRADUATION_GUIDE = 'docs/guides/move-to-postgres.md';+ export const DEFAULT_TARGET_URL_ENV = 'GBRAIN_TARGET_URL';++ /** Doc anchor per code; test/graduation-errors.test.ts asserts each anchor exists. */+ export const GRADUATION_DOCS: Readonly<Record<GraduationErrorCode, string>> = {+ graduation_source_writer_held: 'docs/ENGINES.md#graduation-writer-held',+ graduation_unclassified_table: `${GRADUATION_GUIDE}#inventory`,+ graduation_embedding_dimension_mismatch: `${GRADUATION_GUIDE}#embeddings`,+ graduation_drain_timeout: `${GRADUATION_GUIDE}#drain`,+ graduation_target_not_empty: `${GRADUATION_GUIDE}#target-not-empty`,+ graduation_foreign_host_binding: `${GRADUATION_GUIDE}#hosts`,+ graduation_verify_failed: `${GRADUATION_GUIDE}#verify`,+ graduation_interrupted: `${GRADUATION_GUIDE}#resume`,+ graduation_in_progress: `${GRADUATION_GUIDE}#in-progress`,+ graduation_split_brain: `${GRADUATION_GUIDE}#split-brain`,+ graduation_rollback_writes_lost: `${GRADUATION_GUIDE}#rollback`,+ graduation_target_auth_failed: `${GRADUATION_GUIDE}#credentials`,+ graduation_target_ddl_unreachable: `${GRADUATION_GUIDE}#ddl-connection`,+ graduation_target_unsupported: `${GRADUATION_GUIDE}#target-requirements`,+ graduation_unsupported_platform: `${GRADUATION_GUIDE}#platforms`,+ engine_graduated: `${GRADUATION_GUIDE}#graduated-datastore`,+ };++ /** How the user spelled the move; defaults match the guide. */+ export interface GraduationCommandSpelling {+ to?: GraduationTargetSpelling;+ urlEnv?: string;+ }++ export function statusArgv(): string[] {+ return ['gbrain', 'migrate', '--status', '--json'];+ }++ export function planArgv(s: GraduationCommandSpelling = {}, extra: readonly string[] = []): string[] {+ return ['gbrain', 'migrate', '--to', s.to ?? 'postgres', '--url-env', s.urlEnv ?? DEFAULT_TARGET_URL_ENV, '--plan', ...extra, '--json'];+ }++ export function runArgv(s: GraduationCommandSpelling, planHash: string, extra: readonly string[] = []): string[] {+ return ['gbrain', 'migrate', '--to', s.to ?? 'postgres', '--url-env', s.urlEnv ?? DEFAULT_TARGET_URL_ENV, ...extra, '--yes', '--expect', planHash];+ }++ export function resumeArgv(extra: readonly string[] = []): string[] {+ return ['gbrain', 'migrate', '--resume', ...extra];+ }++ export function rollbackArgv(extra: readonly string[] = []): string[] {+ return ['gbrain', 'migrate', '--rollback-to-source', ...extra];+ }++ const STATUS_VERIFY = { argv: statusArgv() };+ const DOCTOR_VERIFY = { argv: ['gbrain', 'doctor', '--no-migrate', '--json'] };+ const planVerify = (s: GraduationCommandSpelling) => ({ argv: planArgv(s) });+ const NOTHING_CHANGED = 'Nothing has changed: the brain stays on PGLite and keeps working.';+ const MCP_RESTART = 'Some desktop agent apps stop relaunching a server that exited; restart the MCP client (or its gbrain server entry) after the fix.';++ /** `graduation_source_writer_held`: a serve or daemon holds the source and did not hand it over. */+ export function sourceWriterHeldError(opts: { owner: LockOwner | null; pid?: number; subcommand?: string; rerun: string[] }): OperationError {+ const holder = opts.owner+ ? `a live \`gbrain serve\` (PID ${opts.owner.pid}, ${opts.owner.transport})`+ : `a gbrain process (PID ${opts.pid ?? 'unknown'}${opts.subcommand ? `, \`gbrain ${opts.subcommand}\`` : ''})`;+ const why = `${holder} holds this PGLite brain's single-writer lock and did not hand it over within 30 seconds, so the move cannot fence the source.`;+ const rerun: Action = { argv: opts.rerun, consent: [], actor: 'agent', requires_exclusive: true, verify: STATUS_VERIFY,+ why: 'Re-runs the move once nothing else holds the brain.' };+ const fix: Action = opts.owner ? { ...exclusiveFix(rerun, opts.owner), verify: STATUS_VERIFY } : {+ ...rerun, actor: 'user',+ why: `Stop ${holder} (let it finish, or end it), then run this command again.`,+ user_message: `Moving your brain to Postgres needs the brain to itself, and ${holder.replace(/`/g, '')} is using it. Can you stop it? Then I'll run the move again. ${NOTHING_CHANGED}`,+ };+ return opError('graduation_source_writer_held', `${holder.replace(/`/g, '')} holds the brain; the move did not start.`,+ 'Ask the user to stop the named process (fix), then re-run the move (fix.then). Do not remove a live lock.',+ { why, docs: GRADUATION_DOCS.graduation_source_writer_held, fix: { ...fix, docs: GRADUATION_DOCS.graduation_source_writer_held } });+ }++ /** `graduation_unclassified_table`: a relation the built-in inventory does not list. */+ export function unclassifiedTableError(opts: { relations: readonly string[]; side: 'source' | 'target'; cause: 'newer_schema' | 'missing_inventory_row'; spelling?: GraduationCommandSpelling }): OperationError {+ const list = opts.relations.join(', ');+ const docs = GRADUATION_DOCS.graduation_unclassified_table;+ if (opts.cause === 'newer_schema') {+ const why = `The ${opts.side} database has relations this gbrain does not know (${list}); it was created by a newer gbrain, and copying unknown tables could lose data.`;+ return opError('graduation_unclassified_table', `The ${opts.side} has relations this gbrain version does not classify: ${list}.`,+ 'Ask the user to upgrade gbrain on this machine (fix), then preview the move again.',+ { why, reason: 'newer_schema', docs,+ fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'user', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}),+ why: `${why} Upgrading this binary gives it the newer inventory.`,+ user_message: `The Postgres database was set up by a newer gbrain than this one. Can you upgrade gbrain here (gbrain upgrade)? Then I'll check the move again. ${NOTHING_CHANGED}` } });+ }+ const why = `This gbrain's own migrations created relations its graduation inventory does not list (${list}). Moving without a classification for every table could drop data, so the move refuses; this is a gbrain bug.`;+ return opError('graduation_unclassified_table', `The graduation inventory has no row for: ${list}.`,+ 'Report this to the gbrain maintainers with `gbrain doctor --json` output; nothing changed and the brain keeps working on PGLite.',+ { why, reason: 'missing_inventory_row', docs,+ fix: { consent: [], actor: 'agent', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}),+ why, user_message: `gbrain found a table it does not know how to move (${list}), which is a gbrain bug. Your brain stays on PGLite and keeps working; I can report it to the maintainers.` } });+ }++ /** `graduation_embedding_dimension_mismatch`: a pre-existing, non-empty target has a different embedding layout. */+ export function embeddingDimensionMismatchError(opts: { column: string; source: string; target: string; host: string; spelling?: GraduationCommandSpelling }): OperationError {+ const docs = GRADUATION_DOCS.graduation_embedding_dimension_mismatch;+ const why = `${opts.column} is ${opts.source} on this brain but ${opts.target} in the existing database at ${opts.host}; vectors cannot be copied into a column of another size, and gbrain never drops a vector silently.`;+ return opError('graduation_embedding_dimension_mismatch', `The target's ${opts.column} (${opts.target}) does not match this brain (${opts.source}).`,+ 'Ask the user for an empty database, or whether to preview wiping this one (fix); nothing changed.',+ { why, docs,+ fix: { argv: planArgv(opts.spelling ?? {}, ['--force']), consent: ['destructive'], actor: 'agent', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}),+ why: `${why} An empty database always matches (gbrain sizes it from this brain). The --force preview lists exactly what a wipe of ${opts.host} deletes.`,+ user_message: `The Postgres database at ${opts.host} already holds embeddings of a different size than your brain's. Do you have an empty database I can use instead, or should I show you what wiping this one would delete? ${NOTHING_CHANGED}` } });+ }++ /** The structured next step for one drain blocker (DX amendment "Blocker actions"). */+ export function blockerAction(b: GraduationBlocker, rerun: string[]): Action {+ if (b.argv?.length) {+ return { argv: [...b.argv], consent: [], actor: b.needsUser ? 'user' : 'agent', requires_exclusive: false, verify: STATUS_VERIFY,+ why: `${b.detail} Then run the move again: ${rerun.join(' ')}.` };+ }+ return { argv: rerun, consent: [], actor: 'agent', requires_exclusive: false, verify: STATUS_VERIFY, why: b.detail };+ }++ /** `graduation_drain_timeout` (exit 11 when every blocker still progresses). */+ export function drainTimeoutError(opts: { blockers: readonly GraduationBlocker[]; timeoutSec: number }): OperationError {+ const docs = GRADUATION_DOCS.graduation_drain_timeout;- const stuck = opts.blockers.find(b => b.needsUser);++ const stuck = opts.blockers.find(b => b.needsUser) ?? opts.blockers.find(b => b.argv?.length);+ const longer = resumeArgv(['--drain-timeout', String(Math.max(opts.timeoutSec * 2, 1))]);+ const why = `${opts.blockers.length} queued or running write(s) did not finish within --drain-timeout ${opts.timeoutSec}s. The move copies only a drained brain, so it stopped before copying; the source is unchanged and writable.`;+ const fix: Action = stuck+ ? { ...blockerAction(stuck, longer), docs }+ : { argv: longer, consent: [], actor: 'agent', requires_exclusive: false, docs, verify: STATUS_VERIFY,+ why: `${why} Every blocker is still progressing, so a longer drain finishes them; queued work is drained, never cancelled.` };+ return opError('graduation_drain_timeout', `Writes still pending after ${opts.timeoutSec}s: ${opts.blockers.map(b => `${b.kind} ${b.id}`).join(', ')}.`,+ stuck ? 'One blocker needs a person (fix); clear it, then resume the move.' : 'Resume with a longer drain (fix); it is safe to re-run.',+ { why, reason: stuck ? 'blocked' : 'progressing', docs, fix });+ }++ /** `graduation_target_not_empty`: the target holds data that is not this run's. */+ export function targetNotEmptyError(opts: { host: string; tables: readonly { relation: string; rows: number }[]; spelling?: GraduationCommandSpelling }): OperationError {+ const docs = GRADUATION_DOCS.graduation_target_not_empty;+ const listed = opts.tables.slice(0, 5).map(t => `${t.relation} (${t.rows})`).join(', ');+ const why = `The database at ${opts.host} already holds data (${listed}${opts.tables.length > 5 ? ', …' : ''}). Graduation copies only into an empty database, or one holding just this run's rows, so another brain is never overwritten.`;+ return opError('graduation_target_not_empty', `The target database at ${opts.host} is not empty.`,+ 'Ask the user for an empty database, or whether to preview wiping this one (fix); nothing changed.',+ { why, docs,+ fix: { argv: planArgv(opts.spelling ?? {}, ['--force']), consent: ['destructive'], actor: 'agent', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}),+ why: `${why} The --force preview lists every table and row count a wipe deletes; the wipe itself then needs --yes --expect with that plan's hash.`,+ user_message: `The Postgres database at ${opts.host} already has data in it. Do you have an empty database I can use instead, or should I show you exactly what wiping this one would delete? ${NOTHING_CHANGED}` } });+ }++ /** `graduation_foreign_host_binding`: a source's worktree is owned by another host. */+ export function foreignHostBindingError(opts: { sourceId: string; ownerHost: string; spelling?: GraduationCommandSpelling }): OperationError {+ const docs = GRADUATION_DOCS.graduation_foreign_host_binding;+ const why = `Source ${opts.sourceId}'s worktree is owned by host ${opts.ownerHost}, not this one. Graduation moves only rows this host owns, so ownership moves here first (prepare on the owner, accept here).`;+ const accept: Action = {+ argv: ['gbrain', 'sources', 'writer', 'transfer', 'accept', opts.sourceId, '--path', '<worktree_root>', '--expected-epoch', '<epoch>', '--manifest', '<manifest_sha256>', '--admin-intent', 'writer_transfer_accept', '--expected-state', '<admin_state>'],+ inputs: [+ { name: 'worktree_root', how: `The checkout of ${opts.sourceId} on this host.` },+ { name: 'epoch', how: 'The epoch the prepare step printed on the owner host.' },+ { name: 'manifest_sha256', how: 'The manifest sha256 the prepare step printed on the owner host.' },+ { name: 'admin_state', how: `admin_state from \`gbrain sources writer status ${opts.sourceId} --json\` on this host.` },+ ],+ consent: [], actor: 'user', requires_exclusive: false, verify: planVerify(opts.spelling ?? {}),+ why: 'Accepts the prepared transfer on this host; then preview the move again.',+ };+ return opError('graduation_foreign_host_binding', `Source ${opts.sourceId} is owned by another host (${opts.ownerHost}).`,+ 'Ask the user to run the two-host transfer (fix on the owner host, fix.then here), then preview the move again.',+ { why, docs,+ fix: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', opts.sourceId, '--admin-intent', 'writer_transfer_prepare', '--expected-state', '<admin_state>'],+ inputs: [{ name: 'admin_state', how: `admin_state from \`gbrain sources writer status ${opts.sourceId} --json\` on host ${opts.ownerHost}.` }],+ consent: [], actor: 'user', requires_exclusive: false, docs, verify: { argv: ['gbrain', 'sources', 'status', opts.sourceId, '--json'] },+ why: `${why} Run this on host ${opts.ownerHost}.`,+ user_message: `Your source ${opts.sourceId} is owned by another computer (${opts.ownerHost}). Its ownership has to move to this computer before the brain can move to Postgres; that takes one command there and one here. ${NOTHING_CHANGED}`,+ then: accept } });+ }++ const VERIFY_WHY: Readonly<Record<VerifyFailure['kind'], string>> = {+ count: 'a table has a different number of rows on the target',+ digest: 'a table\'s content digest differs between source and target',+ sequence: 'a target sequence is behind the source position or column maximum',+ fk: 'a foreign key has rows without a parent on the target',+ trigger: 'a schema trigger is not in its expected state on the target',+ relation_set: 'the target relation set differs from the inventory',+ replay: 'replaying a stored request on the target did not return the stored outcome',+ doctor: 'a doctor check fails on the target that passed on the source',+ };++ /** `graduation_verify_failed`: the target is still fenced; the source stays authoritative. */+ export function verifyFailedError(opts: { failures: readonly VerifyFailure[]; repeated: boolean }): OperationError {+ const docs = GRADUATION_DOCS.graduation_verify_failed;+ const first = opts.failures[0];+ const kind = first?.kind ?? 'digest';+ const where = first ? `${first.relation}${first.firstKey ? ` (first differing key ${first.firstKey}${first.column ? `, column ${first.column}` : ''})` : ''}` : 'the target';+ const why = `Verification compares every carried table before the target may take over: ${VERIFY_WHY[kind]} (${where}). The target stays fenced and the PGLite brain stays authoritative and writable.`;+ if (opts.repeated) {+ return opError('graduation_verify_failed', `Verification failed again after a re-copy: ${first?.detail ?? kind}.`,+ 'Report this to the gbrain maintainers with the redacted bug bundle; the safe exit is a rollback to the source.',+ { why: `${why} A re-copy did not fix it, so it is a gbrain bug, not a transient fault. \`gbrain migrate --rollback-to-source\` discards the target and keeps the PGLite brain.`,+ reason: kind, docs, detail: first?.detail,+ fix: { consent: [], actor: 'agent', requires_exclusive: false, docs, verify: STATUS_VERIFY,+ why: `${why} Report the table, first key and column (no row content) to the maintainers.`,+ user_message: 'Moving your brain to Postgres stopped at the final check, twice. Your brain is still on PGLite and works normally. I can report this to the gbrain maintainers, and discard the half-built Postgres copy if you want.' } });+ }+ return opError('graduation_verify_failed', `Verification failed: ${first?.detail ?? kind}.`,+ 'Resume the move (fix): it re-copies the mismatched tables once and verifies again.',+ { why, reason: kind, docs, detail: first?.detail,+ fix: { argv: resumeArgv(), consent: [], actor: 'agent', requires_exclusive: true, docs, verify: STATUS_VERIFY,+ why: `${why} Resume re-copies the mismatched tables with their dependants and verifies again.` } });+ }++ /** `graduation_interrupted`: a run stopped (crash, SIGINT, lock gap) before it finished. */+ export function interruptedError(opts: { runId: string; state: string; dataDir?: string }): OperationError {+ const docs = GRADUATION_DOCS.graduation_interrupted;+ const why = `Graduation run ${opts.runId} stopped in state ${opts.state} and no process owns it now${opts.dataDir ? ` (brain ${opts.dataDir})` : ''}. Resume continues from the first incomplete step; \`gbrain migrate --rollback-to-source\` discards the target instead.`;+ return opError('graduation_interrupted', `An engine graduation (run ${opts.runId}) was interrupted in state ${opts.state}.`,+ 'Resume it (fix); `gbrain migrate --status --json` shows where it stopped.',+ { why, docs,+ fix: { argv: resumeArgv(), consent: [], actor: 'agent', requires_exclusive: true, docs, verify: STATUS_VERIFY, why } });+ }++ /** `graduation_in_progress` (exit 75): another process is running the move; wait for it. */+ export function inProgressError(opts: { runId?: string; state?: string; pid?: number; dataDir?: string }): OperationError {+ const docs = GRADUATION_DOCS.graduation_in_progress;+ const who = opts.pid !== undefined ? ` (PID ${opts.pid})` : '';+ const why = `This brain${opts.dataDir ? ` (${opts.dataDir})` : ''} is being moved to Postgres by another process${who}${opts.state ? `, now ${opts.state}` : ''}. While it runs, neither engine may be opened by anything else.`;+ return opError('graduation_in_progress', `An engine graduation${opts.runId ? ` (run ${opts.runId})` : ''} is in progress${who}.`,+ 'Wait for the move to finish, then retry; `gbrain migrate --status --json` shows its progress.',+ { why, docs,+ fix: { argv: statusArgv(), consent: [], actor: 'provider', requires_exclusive: false, docs, verify: STATUS_VERIFY,+ why: `${why} Poll the status until the run ends, then retry the same request. ${MCP_RESTART}`,+ user_message: 'gbrain is moving your brain to Postgres right now; memory is back as soon as the move finishes.' } });+ }++ /** `graduation_split_brain`: a stray brain appeared at the old path. */+ export function splitBrainError(opts: { sourcePath: string; strayPath: string; strayRows?: number; retainedPath?: string }): OperationError {+ const docs = GRADUATION_DOCS.graduation_split_brain;+ const why = `A different brain appeared at ${opts.strayPath} (where the graduated brain used to be${opts.strayRows !== undefined ? `; ${opts.strayRows} rows` : ''}), probably created by an older gbrain after a crash. The target is withheld from authority until the user decides what happens to it.`;+ return opError('graduation_split_brain', `A stray brain exists at ${opts.strayPath} next to graduation's retained copy${opts.retainedPath ? ` ${opts.retainedPath}` : ''}.`,+ 'Ask the user which copy to keep (fix); `gbrain migrate --status --json` lists both paths with row counts and newest writes.',+ { why, docs,- fix: { argv: resumeArgv(), consent: ['destructive'], actor: 'agent', requires_exclusive: true, docs, verify: STATUS_VERIFY,- why: `${why} Resuming forward keeps the graduated Postgres brain and leaves the stray brain where it is; the alternative is to move the stray brain aside and run \`gbrain migrate --rollback-to-source\`.`,- user_message: `While moving your brain to Postgres, a second brain showed up at ${opts.strayPath}. Should I finish the move to Postgres (the stray brain is left alone for you to inspect), or go back to the original PGLite brain? Nothing is deleted either way.` } });++ fix: { argv: resumeArgv(['--yes']), consent: ['destructive'], actor: 'agent', requires_exclusive: true, docs, verify: STATUS_VERIFY,++ why: `${why} After the user agrees, \`--resume --yes\` moves the stray brain to \`<path>.stray-<run_id>\` (nothing is deleted) and finishes the move to Postgres; the alternative is to move the stray brain aside yourself and run \`gbrain migrate --rollback-to-source\`.`,++ user_message: `While moving your brain to Postgres, a second brain showed up at ${opts.strayPath}. Should I finish the move to Postgres (the stray brain is moved aside, not deleted, for you to inspect), or go back to the original PGLite brain? Nothing is deleted either way.` } });+ }++ /** `graduation_rollback_writes_lost`: rollback would drop target-side changes. */+ export function rollbackWritesLostError(opts: { losses: readonly { relation: string; rows: number }[]; final: boolean; planHash?: string }): OperationError {+ const docs = GRADUATION_DOCS.graduation_rollback_writes_lost;+ const listed = opts.losses.map(l => `${l.relation} (${l.rows})`).join(', ');+ if (opts.final) {+ const why = `The Postgres brain has security or withdrawal changes since the move (${listed}). Rolling back would resurrect withdrawn facts or revoked credentials, and nothing is written back to the source, so rollback refuses; the Postgres brain stays authoritative.`;+ return opError('graduation_rollback_writes_lost', `Rollback refused: the target has withdrawals or credential changes since cutover (${listed}).`,+ 'Keep the Postgres brain and recover forward on it; report if rollback is still needed.',+ { why, reason: 'security_changes', docs,+ fix: { consent: [], actor: 'agent', requires_exclusive: false, docs, verify: STATUS_VERIFY,+ why: `${why} Recover forward on Postgres (re-create what was revoked, re-withdraw what was withdrawn).`,+ user_message: 'Your brain cannot go back to PGLite: since the move, facts were withdrawn or access was revoked on Postgres, and going back would undo that. Your brain keeps working on Postgres.' } });+ }+ const why = `Rolling back makes the PGLite brain authoritative again and drops what changed on Postgres since the move: ${listed}. Nothing is written back to PGLite.`;+ return opError('graduation_rollback_writes_lost', `Rollback would drop target-side writes: ${listed}.`,+ 'Ask the user whether those changes may be dropped (fix); the Postgres brain stays authoritative until they agree.',+ { why, reason: 'user_data', docs,+ fix: { argv: rollbackArgv(['--yes', '--expect', opts.planHash ?? '<plan_hash>']), ...(opts.planHash ? {} : { inputs: [{ name: 'plan_hash', how: 'plan_hash from `gbrain migrate --status --json`.' }] }),+ consent: ['destructive'], actor: 'agent', requires_exclusive: true, docs, verify: STATUS_VERIFY, ...(opts.planHash ? { plan_hash: opts.planHash } : {}), why,+ user_message: `Going back to PGLite would lose what changed on Postgres since the move: ${listed}. Should I go back anyway? If not, nothing changes and Postgres stays in use.` } });+ }++ /** `graduation_target_auth_failed`: the recorded target URL no longer authenticates. */+ export function targetAuthFailedError(opts: { host: string; urlEnv?: string }): OperationError {+ const docs = GRADUATION_DOCS.graduation_target_auth_failed;+ const env = opts.urlEnv ?? DEFAULT_TARGET_URL_ENV;+ const why = `${opts.host} rejected the credentials recorded for this move (the password probably changed). The new URL must name the same host, port, database and user.`;+ return opError('graduation_target_auth_failed', `The target database at ${opts.host} rejected the recorded credentials.`,+ `Ask the user for the new connection string, put it in ${env}, then resume (fix).`,+ { why, docs,+ fix: { argv: resumeArgv(['--url-env', env]), consent: ['credentials'], actor: 'agent', requires_exclusive: true, docs, verify: STATUS_VERIFY,+ why: `${why} Export the new URL as ${env} first; the command never carries the password.`,+ user_message: `The Postgres database at ${opts.host} no longer accepts the saved password. Can you give me its current connection string? I'll keep it out of the command line.` } });+ }++ /** `graduation_target_ddl_unreachable`: the direct/DDL route does not reach the same database. */+ export function targetDdlUnreachableError(opts: { host: string; ddlHost: string; spelling?: GraduationCommandSpelling }): OperationError {+ const docs = GRADUATION_DOCS.graduation_target_ddl_unreachable;+ const why = `gbrain reaches ${opts.host} but not its direct (schema) connection ${opts.ddlHost}, or the two do not name the same database. Supabase's derived direct host is IPv6-only; its session pooler works from IPv4 networks.`;+ return opError('graduation_target_ddl_unreachable', `The direct database connection ${opts.ddlHost} for ${opts.host} is unreachable or names another database.`,+ 'Ask the user for the session pooler URL, set GBRAIN_DIRECT_DATABASE_URL to it, then preview again (fix).',+ { why, docs,+ fix: { argv: planArgv(opts.spelling ?? {}), consent: ['credentials'], actor: 'agent', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}),+ why: `${why} Set GBRAIN_DIRECT_DATABASE_URL to the session pooler URL (port 5432) before re-running the plan.`,+ user_message: `gbrain can reach your Postgres database but not the direct connection it needs to set up tables (common on Supabase over IPv4). Can you copy the "session pooler" connection string from the database's connect settings? ${NOTHING_CHANGED}` } });+ }++ const REQUIREMENT_FIX: Readonly<Record<string, string>> = {+ server_version: 'a Postgres 15, 16 or 17 server',+ vector: 'the `vector` extension (`CREATE EXTENSION vector;`)',+ halfvec: 'a `vector` extension version with halfvec support (0.7 or newer)',+ create_privilege: 'the CREATE privilege on the database for this user',+ column: 'a target schema whose columns match this brain',+ env_override: 'GBRAIN_DATABASE_URL / DATABASE_URL unset or equal to the target (otherwise the routing flip has no effect)',+ };++ /** `graduation_target_unsupported`: a named prerequisite is missing on the target. */+ export function targetUnsupportedError(opts: { requirement: keyof typeof REQUIREMENT_FIX | string; detail: string; host: string; spelling?: GraduationCommandSpelling }): OperationError {+ const docs = GRADUATION_DOCS.graduation_target_unsupported;+ const need = REQUIREMENT_FIX[opts.requirement] ?? opts.requirement;+ const why = `The move needs ${need}; ${opts.detail}.`;+ return opError('graduation_target_unsupported', `The target at ${opts.host} is missing a prerequisite: ${opts.detail}.`,+ 'Ask the user to provide the prerequisite or another database, then preview again (fix).',+ { why, reason: opts.requirement, docs,+ fix: { argv: planArgv(opts.spelling ?? {}), consent: ['egress'], actor: 'agent', requires_exclusive: false, docs, verify: planVerify(opts.spelling ?? {}), why,+ user_message: `The Postgres database at ${opts.host} is missing something gbrain needs: ${need}. Can you set that up, or give me a different database? ${NOTHING_CHANGED}` } });+ }++ /** `graduation_unsupported_platform`: Windows, brain with history. */+ export function unsupportedPlatformError(opts: { platform: string }): OperationError {+ const docs = GRADUATION_DOCS.graduation_unsupported_platform;+ const why = `Graduating a brain with write history is not available on ${opts.platform} yet: its tombstone and crash protections are tested on macOS and Linux only. The brain stays on PGLite; \`gbrain mcp expose\` shares it with agents on other machines without moving it.`;+ return opError('graduation_unsupported_platform', `Moving a brain with write history to Postgres is not available on ${opts.platform}.`,+ 'Ask the user whether to share the PGLite brain over MCP instead (fix); nothing changed.',+ { why, docs,+ fix: { argv: ['gbrain', 'mcp', 'expose'], consent: ['persistent_install', 'egress'], actor: 'agent', requires_exclusive: false, docs, verify: DOCTOR_VERIFY, why,+ user_message: 'Moving this brain to Postgres is not available on Windows yet. Should I share it with your other machines over MCP instead (gbrain mcp expose)? It stays on this computer.' } });+ }++ /**+ * `engine_graduated`: a client opened the old PGLite path (tombstone) or a+ * fenced source. On the graduating host the manifest finishes the flip; any+ * other client points its config at the target in one step.+ */+ export function engineGraduatedError(opts: { tombstone: Pick<Tombstone, 'targetDisplayUrl' | 'movedTo' | 'runId'> | null; dataDir: string; graduatingHost: boolean; transport?: 'cli' | 'stdio' | 'http' }): OperationError {+ const docs = GRADUATION_DOCS.engine_graduated;+ const where = opts.tombstone?.targetDisplayUrl ?? 'Postgres';+ const mcp = opts.transport === 'stdio' || opts.transport === 'http';+ const why = `This brain moved to ${where}; ${opts.dataDir} is a tombstone${opts.tombstone ? ` and the retained PGLite copy is ${opts.tombstone.movedTo}` : ''}. gbrain never opens or recreates a brain there.`;+ if (opts.graduatingHost) {+ return opError('engine_graduated', `This brain moved to ${where}; ${opts.dataDir} is no longer a brain.`,+ 'Finish the move on this host (fix): it completes the routing flip and the registry rewrites.',+ { why, docs,+ fix: { argv: resumeArgv(), consent: [], actor: 'agent', requires_exclusive: false, docs, verify: DOCTOR_VERIFY,+ why: `${why} The graduation manifest on this host is past cutover; resuming finishes pointing the config and mounts at Postgres.${mcp ? ` ${MCP_RESTART}` : ''}` } });+ }+ const restart = mcp ? ` Then restart this MCP server in your agent app (or rewire it with \`gbrain bootstrap harness --harness all\`). ${MCP_RESTART}` : '';+ return opError('engine_graduated', `This brain moved to ${where}; ${opts.dataDir} is no longer a brain.`,+ 'Ask the user to point this config at the Postgres brain (fix); one command, then retry.',+ { why, docs,+ fix: { argv: ['gbrain', 'config', 'set', 'database_url', '<target_url>'],+ inputs: [{ name: 'target_url', how: `The connection string of ${where}; the graduating host's config.json holds it. Pass it from the environment (e.g. "$GBRAIN_TARGET_URL"), never typed into a shared log.` }],+ consent: [], actor: 'user', requires_exclusive: false, docs, verify: DOCTOR_VERIFY,+ why: `${why} Pointing this config's database_url at the target is the whole fix; existing tokens and OAuth clients stay valid.${restart}`,+ user_message: `Your gbrain brain moved to Postgres (${where}), but this ${mcp ? 'agent app' : 'machine'} still points at the old local copy. Can you run \`gbrain config set database_url "$GBRAIN_TARGET_URL"\` with the Postgres connection string${mcp ? ', then restart the app\'s gbrain server' : ''}?` } });+ }diff --cc src/core/persistence/graduation-serve-guard.tsindex 0000000000,bed2ed5598..76a4b89fcemode 000000,100644..100644--- a/src/core/persistence/graduation-serve-guard.ts+++ b/src/core/persistence/graduation-serve-guard.ts@@@ -1,0 -1,138 +1,135 @@@+ /**+ * Engine graduation and long-lived servers (plan §6.4). File reads only:+ * the intent marker and tombstone through `inspectGraduationPath`, and the+ * durable config. Never a lock attempt, never a write.+ *+ * - `serveGraduationStartRefusal`: a `gbrain serve` (re)launched while a+ * graduation run owns the brain exits with `graduation_in_progress`+ * (exit 75) instead of entering status-only mode and later reconnecting to+ * the abandoned path.+ * - `graduationStatusReason`: a serve whose config still names a graduated+ * PGLite path (stale MCP config) stays in status-only mode and answers+ * with `engine_graduated` and its one-step fix.+ * - `exitOnEngineIdentityChange`: a status-only or degraded serve re-resolves+ * config on each reconnect attempt and exits for relaunch when the engine+ * identity changed, a tombstone appeared, or a run started (a serve that+ * started without any config keeps recovering in place).+ * - `graduationHandoffRequested`: a resident PGLite serve sees a live run's+ * marker and hands the brain over (it shuts down and exits 75).+ */+ import { createHash } from 'node:crypto';+ import { readFileSync } from 'node:fs';+ import { renderCliError } from '../agent-output.ts';+ import { gbrainPath, loadConfig, type GBrainConfig } from '../config.ts';+ import type { OperationError } from '../ops/contract.ts';-import { inspectGraduationPath } from './graduation-custody.ts';-import { engineGraduatedError, inProgressError } from './graduation-errors.ts';++import { engineGraduatedFor, inspectGraduationPath } from './graduation-custody.ts';++import { inProgressError } from './graduation-errors.ts';+ import type { GraduationManifest, GraduationPathState, ManifestState } from './engine-graduation.types.ts';++ export const GRADUATION_SERVE_EXIT = 75;++ /** The host brain's PGLite data dir, or null (Postgres, thin client, no config). */+ export function hostPgliteDataDir(cfg: GBrainConfig | null = loadConfig()): string | null {+ if (!cfg || cfg.database_url || (cfg.engine ?? 'pglite') !== 'pglite' || cfg.remote_mcp) return null;+ return cfg.database_path ?? gbrainPath('brain.pglite');+ }++ function pathState(cfg: GBrainConfig | null): GraduationPathState | null {+ const dataDir = hostPgliteDataDir(cfg);+ return dataDir ? inspectGraduationPath(dataDir) : null;+ }++ /** `graduation_in_progress` when another process is graduating the host brain; null otherwise. */+ export function serveGraduationStartRefusal(cfg: GBrainConfig | null = loadConfig()): OperationError | null {+ const st = pathState(cfg);+ if (st?.state !== 'in_progress' || st.marker?.pid === process.pid) return null;+ return inProgressError({ runId: st.marker?.runId, state: st.marker?.state, pid: st.marker?.pid, dataDir: st.dataDir });+ }++ /** The status-only reason for a graduated (tombstoned) host path, with its refusal. */+ export function graduationStatusReason(cfg: GBrainConfig | null = loadConfig()): { reason: 'engine_graduated'; error: OperationError; dataDir: string } | null {+ const st = pathState(cfg);+ if (st?.state !== 'graduated') return null;+ return { reason: 'engine_graduated', dataDir: st.dataDir, error: engineGraduatedFor(st, 'stdio') };+ }+-/** `engine_graduated` for a tombstoned path; the graduating host (its marker names this machine's run) gets `--resume`. */-export function engineGraduatedFor(st: GraduationPathState, transport: 'cli' | 'stdio' | 'http'): OperationError {- return engineGraduatedError({ tombstone: st.tombstone, dataDir: st.dataDir, graduatingHost: st.marker?.runId !== undefined && st.marker.runId === st.tombstone?.runId && st.marker.state !== 'graduated', transport });-}++export { engineGraduatedFor };++ /** The engine a config routes to, hashed (the URL may carry a password; only its hash is kept); null without a config. */+ export function engineIdentity(cfg: GBrainConfig | null = loadConfig()): string | null {+ if (!cfg) return null;+ const route = [cfg.engine ?? 'pglite', cfg.database_url ?? '', cfg.database_url ? '' : (cfg.database_path ?? gbrainPath('brain.pglite'))];+ return createHash('sha256').update(JSON.stringify(route)).digest('hex');+ }++ /** Write the classified envelope (one JSON document) to stderr and return the exit code. */+ export function writeServeGraduationEnvelope(e: OperationError, write: (s: string) => void = s => { process.stderr.write(s); }): number {+ write(renderCliError(e, { json: true, command: 'serve', tty: false }).stdout ?? '');+ return GRADUATION_SERVE_EXIT;+ }++ /**+ * Reconnect gate for a status-only or degraded serve: when the engine+ * identity it started with no longer holds (config flipped by a graduation or+ * a rollback), a tombstone appeared, or a run now owns the brain, it exits for+ * relaunch so the next process opens the right engine. Otherwise returns.+ */+ export function exitOnEngineIdentityChange(startIdentity: string | null, opts: { exit?: (code: number) => void; log?: (s: string) => void; startedGraduated?: boolean } = {}): void {+ const exit = opts.exit ?? ((code: number) => { process.exit(code); });+ const log = opts.log ?? ((s: string) => { process.stderr.write(s); });+ const cfg = loadConfig();+ const running = serveGraduationStartRefusal(cfg);+ if (running) { exit(writeServeGraduationEnvelope(running, log)); return; }+ // No config at start (status-only no_brain) or now: F4 recovers in place; only a config that names another engine relaunches.+ if (startIdentity === null || cfg === null) return;+ if (engineIdentity(cfg) !== startIdentity) {+ log('gbrain serve: the brain\'s engine changed (an engine graduation or rollback flipped the config); exiting so the server is relaunched on the new engine. Restart the MCP client if it does not relaunch servers.\n');+ exit(GRADUATION_SERVE_EXIT);+ return;+ }+ if (!opts.startedGraduated && pathState(cfg)?.state === 'graduated') {+ log('gbrain serve: this PGLite brain was moved to Postgres; exiting so the server is relaunched on the new engine. Restart the MCP client if it does not relaunch servers.\n');+ exit(GRADUATION_SERVE_EXIT);+ }+ }++ /** `gbrain serve` startup: exit 75 with the envelope on stderr when another live run owns the host brain. */+ export function exitIfGraduationRunning(exit: (code: number) => void = (code) => { process.exit(code); }): void {+ const running = serveGraduationStartRefusal();+ if (running) exit(writeServeGraduationEnvelope(running));+ }++ /** The degraded serve's reconnect gate: captures the identity now, checks it on each call. */+ export function engineIdentityGate(): () => void {+ const start = engineIdentity();+ return () => exitOnEngineIdentityChange(start);+ }++ /** A resident PGLite serve should hand the brain over: a live graduation run (not this process) wrote its marker. */+ export function graduationHandoffRequested(cfg: GBrainConfig | null = loadConfig()): OperationError | null {+ return serveGraduationStartRefusal(cfg);+ }++ export const GRADUATION_MANIFEST_FILE = 'graduation-manifest.json';+ export const TERMINAL_MANIFEST_STATES: ReadonlySet<ManifestState> = new Set(['graduated', 'rolled_back', 'abandoned']);++ /** The redacted, file-only view of the 0600 manifest (no URLs); null when absent or unreadable. */+ export interface GraduationManifestSummary {+ runId: string;+ state: ManifestState;+ dataDir: string;+ brainId: string;+ target: { host: string; port: number; database: string };+ updatedAt: string;+ }++ export function readGraduationManifestSummary(home: string = gbrainPath()): GraduationManifestSummary | null {+ try {+ const m = JSON.parse(readFileSync(`${home}/${GRADUATION_MANIFEST_FILE}`, 'utf8')) as Partial<GraduationManifest>;+ if (typeof m.runId !== 'string' || typeof m.state !== 'string' || !m.source?.dataDir || !m.target) return null;+ return { runId: m.runId, state: m.state, dataDir: m.source.dataDir, brainId: m.source.brainId ?? '',+ target: { host: m.target.host, port: m.target.port, database: m.target.database }, updatedAt: m.updatedAt ?? '' };+ } catch {+ return null;+ }+ }diff --cc src/core/persistence/graduation-target.tsindex 62505e90ad,5f6f3e37b3..1a97274f4a--- a/src/core/persistence/graduation-target.ts+++ b/src/core/persistence/graduation-target.ts@@@ -20,9 -20,8 +20,8 @@@ import type { BrainEngine } from '../enimport { PostgresEngine } from '../postgres-engine.ts';import { normalizeDirectUrl, isNetworkUnreachableError } from '../connection-manager.ts';import { redactConnectionInfo } from '../audit/redact-connection-info.ts';--import { opError, type OpErrorOpts, type OperationError } from '../ops/contract.ts';- import type { RegistryCode } from '../error-registry.ts';--import type { EmbeddingColumn, GraduationBlocker, GraduationErrorCode, TargetIdentity, TargetProbe, TargetRoutes, TriggerBypass } from './engine-graduation.types.ts';++import type { EmbeddingColumn, GraduationBlocker, TargetIdentity, TargetProbe, TargetRoutes, TriggerBypass } from './engine-graduation.types.ts';++import { targetAuthFailedError, targetDdlUnreachableError, targetUnsupportedError } from './graduation-errors.ts';export type ResolvedTargetRoutes = TargetRoutes & { mainUrl: string; ddlUrl: string };@@@ -33,24 -32,24 +32,13 @@@ export const MIN_TARGET_SERVER_VERSION_/** pgvector release that added halfvec (facts.embedding, query_cache.embedding). */export const MIN_VECTOR_HALFVEC_VERSION = '0.7.0';- /** Graduation codes are registered by the agent-contract batch; until then they are typed by the shared list. */-/** A graduation refusal (every GraduationErrorCode has a registry row in src/core/error-registry.ts). */--export function graduationError(code: GraduationErrorCode, message: string, suggestion: string, opts: OpErrorOpts = {}): OperationError {- return opError(code as RegistryCode, message, suggestion, opts);- return opError(code, message, suggestion, opts);--}--export function targetPlanArgv(routes: Pick<TargetRoutes, 'urlEnv'>, to: 'postgres' | 'supabase' = 'postgres'): string[] {return ['gbrain', 'migrate', '--to', to, '--url-env', routes.urlEnv ?? DEFAULT_TARGET_URL_ENV, '--plan', '--json'];}function parsePostgresUrl(url: string): URL {if (!/^postgres(?:ql)?:\/\//i.test(url)) {-- throw graduationError('graduation_target_unsupported', 'The target is not a Postgres URL.',-- 'Pass a postgres:// or postgresql:// URL through --url-env, then rerun the plan.',-- { why: 'Graduation moves a PGLite brain into a Postgres database; the given value is not a Postgres connection URL.',-- fix: { argv: targetPlanArgv({}), consent: ['credentials'], actor: 'agent', requires_exclusive: false,-- why: 'Re-plans against a URL held in an environment variable, so the password never appears in argv.',-- user_message: `Set ${DEFAULT_TARGET_URL_ENV} to the Postgres connection URL of the target database (user, password, host, port and database).`,-- verify: { argv: targetPlanArgv({}) } } });++ throw targetUnsupportedError({ requirement: 'postgres_url', detail: 'the given target is not a postgres:// or postgresql:// URL', host: 'the given target' });}return new URL(url.replace(/^postgres(?:ql)?:\/\//i, 'http://'));}@@@ -79,21 -78,21 +67,12 @@@ export function targetIdentity(url: strexport function resolveTargetRoutes(opts: { url?: string; urlEnv?: string; env?: NodeJS.ProcessEnv }): ResolvedTargetRoutes {const env = opts.env ?? process.env;if (opts.url && opts.urlEnv) {-- throw graduationError('graduation_target_unsupported', 'Both --url and --url-env were given.',-- 'Pass the target once, preferably as --url-env <VAR>.',-- { why: 'Two target sources could name different databases.',-- fix: { argv: targetPlanArgv({ urlEnv: opts.urlEnv }), consent: [], actor: 'agent', requires_exclusive: false,-- why: 'Re-plans with the target named only by its environment variable.', verify: { argv: targetPlanArgv({ urlEnv: opts.urlEnv }) } } });++ throw targetUnsupportedError({ requirement: 'one_target', detail: 'both --url and --url-env were given; pass the target once, preferably as --url-env <VAR>', host: 'the given target', spelling: { urlEnv: opts.urlEnv } });}const mainUrl = opts.urlEnv ? env[opts.urlEnv] : opts.url;if (!mainUrl) {const urlEnv = opts.urlEnv ?? DEFAULT_TARGET_URL_ENV;-- throw graduationError('graduation_target_unsupported', opts.urlEnv ? `${opts.urlEnv} is not set.` : 'No target URL was given.',-- `Set ${urlEnv} to the target Postgres URL and rerun with --url-env ${urlEnv}.`,-- { why: 'Graduation needs the target database URL; it is read from an environment variable so the password never reaches argv or logs.',-- fix: { argv: targetPlanArgv({ urlEnv }), consent: ['credentials'], actor: 'agent', requires_exclusive: false,-- why: 'Plans the move once the variable holds the target URL.',-- user_message: `Set ${urlEnv} to the Postgres URL of the empty target database.`, verify: { argv: targetPlanArgv({ urlEnv }) } } });++ throw targetUnsupportedError({ requirement: 'target_url', detail: opts.urlEnv ? `${opts.urlEnv} is not set; it must hold the target Postgres URL` : `no target URL was given; set ${urlEnv} to it and pass --url-env ${urlEnv}`, host: 'the target', spelling: { urlEnv } });}parsePostgresUrl(mainUrl);const ddlUrl = normalizeDirectUrl(mainUrl, env.GBRAIN_DIRECT_DATABASE_URL || null) ?? mainUrl;@@@ -285,34 -284,34 +264,15 @@@ export function targetProbeBlockers(pro/** Throws the typed refusal when either route is unreachable or refuses authentication. */export function assertTargetReachable(probe: TargetProbe, routes: Pick<TargetRoutes, 'urlEnv' | 'main' | 'ddl'>): void {-- const urlEnv = routes.urlEnv ?? DEFAULT_TARGET_URL_ENV;-- const argv = targetPlanArgv(routes);-- if (probe.reachable && !probe.auth) {-- throw graduationError('graduation_target_auth_failed', `The target ${routes.main} refused authentication.`,-- `Ask the user for the current URL of the same database, put it in ${urlEnv} and rerun with --url-env ${urlEnv}.`,-- { why: `The server answered but rejected the credentials (${probe.error?.code ?? 'auth'}); a rotated password is the usual cause.`,-- fix: { argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, why: 'Re-plans with the corrected URL for the same target identity.',-- user_message: `The Postgres server at ${routes.main} rejected the password. Set ${urlEnv} to the current URL for this database.`, verify: { argv } } });-- }++ const spelling = routes.urlEnv ? { urlEnv: routes.urlEnv } : {};++ if (probe.reachable && !probe.auth) throw targetAuthFailedError({ host: routes.main, ...(routes.urlEnv ? { urlEnv: routes.urlEnv } : {}) });if (!probe.reachable) {-- throw graduationError('graduation_target_unsupported', `The target ${routes.main} is unreachable.`,-- 'Check that the database is running and reachable from this machine, then rerun the plan.',-- { why: `Connecting failed before authentication (${probe.error?.code ?? 'unreachable'}: ${probe.error?.message ?? 'no detail'}).`,-- fix: { argv, consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-probes the target once it is reachable.', verify: { argv } } });++ throw targetUnsupportedError({ requirement: 'reachable', detail: `the server is unreachable (${probe.error?.code ?? 'unreachable'}: ${probe.error?.message ?? 'no detail'})`, host: routes.main, spelling });}if (probe.serverVersion === null) {-- throw graduationError('graduation_target_unsupported', `The target ${routes.main} could not be probed.`,-- 'Fix the named connection problem (for example create the database), then rerun the plan.',-- { why: `The server answered but the probe session failed (${probe.error?.code ?? 'unknown'}: ${probe.error?.message ?? 'no detail'}).`,-- fix: { argv, consent: [], actor: 'agent', requires_exclusive: false, why: 'Re-probes the target after the fix.', verify: { argv } } });-- }-- if (!probe.ddl.reachable || !probe.ddl.auth) {-- throw graduationError('graduation_target_ddl_unreachable', `The DDL connection ${routes.ddl} is unreachable.`,-- 'Ask the user for a session-mode connection (Supabase: the session pooler on port 5432), set GBRAIN_DIRECT_DATABASE_URL to it and rerun the plan.',-- { why: `gbrain runs schema changes and the copy on a direct/session connection; it failed (${probe.ddl.error?.code ?? 'unreachable'}). Graduation never falls back to another route on its own.`,-- fix: { argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, why: 'Re-plans with the DDL route the user provides.',-- user_message: `Set GBRAIN_DIRECT_DATABASE_URL to the session-mode connection URL of ${routes.main}.`, verify: { argv } } });++ throw targetUnsupportedError({ requirement: 'probe', detail: `the probe session failed (${probe.error?.code ?? 'unknown'}: ${probe.error?.message ?? 'no detail'})`, host: routes.main, spelling });}++ if (!probe.ddl.reachable || !probe.ddl.auth) throw targetDdlUnreachableError({ host: routes.main, ddlHost: routes.ddl, spelling });}/**@@@ -324,12 -323,12 +284,11 @@@*/export async function crossCheckRoutes(main: BrainEngine, ddl: BrainEngine, runId: string): Promise<void> {const keys = [randomInt(1, 2 ** 31 - 1), randomInt(1, 2 ** 31 - 1)];-- const refuse = (detail: string) => graduationError('graduation_target_ddl_unreachable',-- 'The DDL connection does not reach the same database as the main connection.',-- 'Ask the user for the session-mode URL of the same database, set GBRAIN_DIRECT_DATABASE_URL to it and rerun the plan.',-- { why: `Run ${runId}: ${detail}. Schema changes through a different database would leave the target incomplete, so nothing was changed.`,-- fix: { argv: targetPlanArgv({}), consent: ['credentials'], actor: 'agent', requires_exclusive: false, why: 'Re-plans with a DDL route that names the target database.',-- user_message: 'Set GBRAIN_DIRECT_DATABASE_URL to the session-mode connection URL of the target database.', verify: { argv: targetPlanArgv({}) } } });++ const refuse = (detail: string) => {++ const error = targetDdlUnreachableError({ host: 'the main connection', ddlHost: 'the DDL connection' });++ error.detail = `Run ${runId}: ${detail}`;++ return error;++ };let seen: boolean;try {seen = await ddl.transaction(async tx => {diff --cc test/graduation-custody.test.tsindex 31a67cee69,0000000000..6911f02e22mode 100644,000000..100644--- a/test/graduation-custody.test.ts+++ b/test/graduation-custody.test.ts@@@ -1,213 -1,0 +1,213 @@@+/**+ * Engine graduation filesystem custody: intent marker, tombstone, lock-free+ * path inspection, lock-retaining close, held-lock move-aside and the PGLite+ * open-path refusals.+ *+ * Protects: the kernel lock never gaps between close, rename and tombstone+ * (no opener acquires it and none creates a data dir); the tombstone is+ * exclusive and 0600; a tombstoned path refuses with engine_graduated and is+ * never re-initialised; a live marker refuses opens before the lock while a+ * dead pre-cutover marker lets the source open; a dead marker past cutover is+ * graduation_interrupted with the lock released. Regressions that fail it: a+ * close that releases the lock, a tombstone write that overwrites, an opener+ * that mkdirs over the tombstone, a liveness check fooled by PID reuse.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ assertPgliteGraduationOpenable, currentProcessIdentity, graduatedPath, graduationHandOffRequested, inspectGraduationPath,+ intentMarkerPath, moveAsideHeld, processStartTime, readIntentMarker, readTombstone, registerGraduationRunInProcess, removeTombstone,+ TombstonePathOccupiedError, writeIntentMarker, writeTombstone,+} from '../src/core/persistence/graduation-custody.ts';+import type { IntentMarker, ManifestState, Tombstone } from '../src/core/persistence/engine-graduation.types.ts';+import { acquireKernelLockOnly, acquireLock, PgliteBusyError, releaseLock, type LockHandle } from '../src/core/pglite-lock.ts';+import { moveHeldPglite } from '../src/core/persistence/maintenance.ts';+import { openPglite } from './helpers/graduation-harness.ts';++const target = { id: 'target-id', host: 'db.example.test', port: 5432, database: 'brain', user: 'alice-example' };+function marker(runId: string, state: ManifestState, identity: Partial<IntentMarker> = {}): IntentMarker {+ return { runId, state, ...currentProcessIdentity(), target, updatedAt: new Date().toISOString(), ...identity };+}+function tombstone(runId: string, movedTo: string): Tombstone {+ return { kind: 'gbrain-engine-graduated', runId, brainId: 'brain', movedTo, target, targetDisplayUrl: 'postgres://[email protected]:5432/brain',+ graduatedAt: new Date().toISOString(), fixArgv: ['gbrain', 'config', 'set', 'database_url', '<GBRAIN_TARGET_URL>'] };+}+function codeOf(error: unknown): string | undefined { return (error as { code?: string })?.code; }+function deadPid(): number {+ const child = Bun.spawnSync(['sh', '-c', 'echo $$']);+ return Number(child.stdout.toString().trim());+}++let root: string;+beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'gbrain-custody-')); });+afterAll(() => {});++describe('intent marker and tombstone files', () => {+ test('the marker is replaced atomically with mode 0600; an unreadable one is never read as "no graduation"', () => {+ const dir = join(root, 'marker.pglite');+ mkdirSync(dir);+ expect(readIntentMarker(dir)).toBeNull();+ writeIntentMarker(dir, marker('run-a', 'planned'));+ writeIntentMarker(dir, marker('run-a', 'quiesced'));+ expect(readIntentMarker(dir)?.state).toBe('quiesced');+ expect(statSync(intentMarkerPath(dir)).mode & 0o777).toBe(0o600);+ writeFileSync(intentMarkerPath(dir), '{not json');+ expect(() => readIntentMarker(dir)).toThrow();- expect(inspectGraduationPath(dir).kind).toBe('interrupted');++ expect(inspectGraduationPath(dir).state).toBe('interrupted');+ });++ test('the tombstone is created exclusively, 0600, and only its own run removes it', () => {+ const path = join(root, 'tomb.pglite');+ writeTombstone(path, tombstone('run-t', `${path}.graduated-run-t`));+ expect(statSync(path).mode & 0o777).toBe(0o600);+ expect(() => writeTombstone(path, tombstone('run-u', 'x'))).toThrow(TombstonePathOccupiedError);+ expect(readTombstone(path)?.runId).toBe('run-t');+ expect(() => removeTombstone(path, 'run-u')).toThrow(/belongs to graduation run run-t/);+ removeTombstone(path, 'run-t');+ expect(existsSync(path)).toBe(false);+ mkdirSync(path);+ expect(() => writeTombstone(path, tombstone('run-t', 'x'))).toThrow(TombstonePathOccupiedError);+ expect(readTombstone(path)).toBeNull();+ });+});++describe('inspectGraduationPath and marker liveness', () => {+ test('none, in_progress, interrupted, graduated and split_brain', () => {+ const dir = join(root, 'inspect.pglite');+ mkdirSync(dir);- expect(inspectGraduationPath(dir).kind).toBe('none');++ expect(inspectGraduationPath(dir).state).toBe('none');+ const unregister = registerGraduationRunInProcess('run-live');+ writeIntentMarker(dir, marker('run-live', 'copying'));- expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'in_progress', liveness: 'alive' });++ expect(inspectGraduationPath(dir)).toMatchObject({ state: 'in_progress', liveness: 'alive' });+ unregister();- expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'interrupted', liveness: 'dead' });++ expect(inspectGraduationPath(dir)).toMatchObject({ state: 'interrupted', liveness: 'dead' });+ writeIntentMarker(dir, marker('run-dead', 'copying', { pid: deadPid(), processStart: null }));- expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'interrupted', liveness: 'dead' });++ expect(inspectGraduationPath(dir)).toMatchObject({ state: 'interrupted', liveness: 'dead' });+ writeIntentMarker(dir, marker('run-reused', 'copying', { pid: process.ppid, processStart: '1' }));+ if (processStartTime(process.ppid)) expect(inspectGraduationPath(dir).liveness).toBe('dead');+ writeIntentMarker(dir, marker('run-other-host', 'copying', { pid: process.ppid, bootId: 'another-boot' }));+ expect(inspectGraduationPath(dir).liveness).toBe('unknown');+ writeIntentMarker(dir, marker('run-split', 'tombstoned', { pid: deadPid() }));+ mkdirSync(graduatedPath(dir, 'run-split'));- expect(inspectGraduationPath(dir)).toMatchObject({ kind: 'split_brain', movedTo: graduatedPath(dir, 'run-split') });++ expect(inspectGraduationPath(dir)).toMatchObject({ state: 'split_brain', movedTo: graduatedPath(dir, 'run-split') });+ writeIntentMarker(dir, marker('run-split', 'rolled_back'));- expect(inspectGraduationPath(dir).kind).toBe('none');++ expect(inspectGraduationPath(dir).state).toBe('none');+ const tombPath = join(root, 'inspect-tomb.pglite');+ writeTombstone(tombPath, tombstone('run-g', `${tombPath}.graduated-run-g`));- expect(inspectGraduationPath(tombPath)).toMatchObject({ kind: 'graduated', tombstone: { runId: 'run-g' } });++ expect(inspectGraduationPath(tombPath)).toMatchObject({ state: 'graduated', tombstone: { runId: 'run-g' } });+ });++ test('a serve hands off only to a live requester on another process', () => {+ const dir = join(root, 'handoff.pglite');+ mkdirSync(dir);+ writeIntentMarker(dir, marker('run-self', 'planned'));+ expect(graduationHandOffRequested(dir)).toBeNull();+ writeIntentMarker(dir, marker('run-dead', 'planned', { pid: deadPid(), processStart: null }));+ expect(graduationHandOffRequested(dir)).toBeNull();+ writeIntentMarker(dir, marker('run-parent', 'planned', { pid: process.ppid, processStart: processStartTime(process.ppid) }));+ expect(graduationHandOffRequested(dir)?.runId).toBe('run-parent');+ });+});++describe('lock-retaining close and held-lock move-aside', () => {+ test('the kernel lock never gaps from close through rename and tombstone; the tombstone then refuses every opener', async () => {+ const dataDir = join(root, 'custody.pglite');+ const engine = await openPglite(dataDir);+ let lock: LockHandle | null = null;+ const attempts: string[] = [];+ let polling = true;+ const poller = (async () => {+ while (polling) {+ try { const stolen = await acquireLock(dataDir, { timeoutMs: 0 }); attempts.push('acquired'); await releaseLock(stolen); }+ catch (error) { attempts.push(error instanceof PgliteBusyError ? 'busy' : codeOf(error) ?? (error as Error).message); }+ await Bun.sleep(5);+ }+ })();+ try {+ await engine.executeRaw('CREATE TABLE kept (id int primary key)');+ await engine.executeRaw('INSERT INTO kept VALUES (1)');+ lock = await engine.closeRetainingLock();+ await engine.disconnect();+ expect(lock.acquired).toBe(true);+ await Bun.sleep(30);+ const movedTo = moveAsideHeld(dataDir, lock, 'run-c');+ expect(lock.lockDir).toBe(join(movedTo, '.gbrain-lock'));+ expect(existsSync(dataDir)).toBe(false);+ await Bun.sleep(30);+ writeTombstone(dataDir, tombstone('run-c', movedTo));+ await Bun.sleep(30);+ } finally {+ polling = false;+ await poller;+ if (lock) await releaseLock(lock);+ }+ expect(attempts.length).toBeGreaterThan(3);+ expect(attempts).not.toContain('acquired');+ expect(lstatSync(dataDir).isFile()).toBe(true);+ await expect(acquireLock(dataDir, { timeoutMs: 0 })).rejects.toThrow(/EEXIST|ENOTDIR|not a directory|file already exists/i);+ expect(lstatSync(dataDir).isFile()).toBe(true);+ expect(codeOf(await openPglite(dataDir).catch(e => e))).toBe('engine_graduated');+ const retained = await openPglite(graduatedPath(dataDir, 'run-c'));+ try { expect(await retained.executeRaw('SELECT id FROM kept')).toEqual([{ id: 1 }]); } finally { await retained.disconnect(); }+ }, 30_000);++ test('a held lock moves only its own datastore, and a held-lock open adopts it without a gap', async () => {+ const dataDir = join(root, 'adopt.pglite');+ const other = join(root, 'adopt-other.pglite');+ mkdirSync(other);+ const engine = await openPglite(dataDir);+ const lock = await engine.closeRetainingLock();+ await engine.disconnect();+ expect(() => moveHeldPglite(other, `${other}.moved`, lock)).toThrow(/does not belong/);+ const moved = `${dataDir}.graduated-run-adopt`;+ moveHeldPglite(dataDir, moved, lock);+ moveHeldPglite(moved, dataDir, lock);+ await expect(acquireLock(dataDir, { timeoutMs: 0 })).rejects.toBeInstanceOf(PgliteBusyError);+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+ const adopted = new PGLiteEngine();+ await adopted.connectWithHeldLock({ engine: 'pglite', database_path: dataDir }, lock);+ try { expect(await adopted.executeRaw('SELECT 1 AS one')).toEqual([{ one: 1 }]); } finally { await adopted.disconnect(); }+ const after = await openPglite(dataDir);+ await after.disconnect();+ }, 30_000);++ test('a kernel-only lock on a tombstoned path creates nothing and excludes openers', async () => {+ const path = join(root, 'kernel-only.pglite');+ writeTombstone(path, tombstone('run-k', `${path}.graduated-run-k`));+ const lock = await acquireKernelLockOnly(path, { lockDir: join(`${path}.graduated-run-k`, '.gbrain-lock'), timeoutMs: 0 });+ try {+ await expect(acquireKernelLockOnly(path, { lockDir: 'x', timeoutMs: 0 })).rejects.toBeInstanceOf(PgliteBusyError);+ expect(lstatSync(path).isFile()).toBe(true);+ } finally { await releaseLock(lock); }+ }, 30_000);+});++describe('PGLite open-path refusals', () => {+ test('a dead run before cutover lets the source open; past cutover it is interrupted and the lock is released', async () => {+ const dataDir = join(root, 'open.pglite');+ const first = await openPglite(dataDir);+ await first.disconnect();+ writeIntentMarker(dataDir, marker('run-o', 'verified', { pid: deadPid(), processStart: null }));+ const opened = await openPglite(dataDir);+ await opened.disconnect();+ writeIntentMarker(dataDir, marker('run-o', 'cutover', { pid: deadPid(), processStart: null }));+ const refused = await openPglite(dataDir).catch(e => e);+ expect(codeOf(refused)).toBe('graduation_interrupted');+ expect(refused.fix?.argv).toEqual(['gbrain', 'migrate', '--resume']);+ const lock = await acquireLock(dataDir, { timeoutMs: 0 });+ await releaseLock(lock);+ }, 30_000);++ test('a live run on another process refuses before the lock, and the refusal names the status command', () => {+ const dataDir = join(root, 'live.pglite');+ mkdirSync(dataDir);+ writeIntentMarker(dataDir, marker('run-p', 'copying', { pid: process.ppid, processStart: processStartTime(process.ppid) }));+ let error: unknown;+ try { assertPgliteGraduationOpenable(dataDir, 'pre_lock'); } catch (e) { error = e; }+ expect(codeOf(error)).toBe('graduation_in_progress');+ expect((error as { fix?: { argv?: string[]; actor?: string } }).fix).toMatchObject({ argv: ['gbrain', 'migrate', '--status', '--json'], actor: 'provider' });+ expect(readFileSync(intentMarkerPath(dataDir), 'utf8')).toContain('run-p');+ });+});diff --cc test/graduation-drain.test.tsindex ea5e273428,ea5e273428..406a8c3ba5--- a/test/graduation-drain.test.ts+++ b/test/graduation-drain.test.ts@@@ -25,7 -25,7 +25,8 @@@ import { buildHistoryFixture } from '..import { localHostId } from '../src/core/persistence/identity.ts';import { persistenceConsumerStatus } from '../src/core/persistence/service.ts';import { WRITER_ADMIN_LOCK_KEY } from '../src/core/persistence/admin-contract.ts';--import { drainForGraduation, drainTimeoutError, freezeSource, graduationBlockers, unfreezeSource, withSourceWritable } from '../src/core/persistence/graduation-drain.ts';++import { drainForGraduation, freezeSource, graduationBlockers, unfreezeSource, withSourceWritable } from '../src/core/persistence/graduation-drain.ts';++import { drainTimeoutError } from '../src/core/persistence/graduation-errors.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';@@@ -103,18 -103,18 +104,19 @@@ for (const backend of testBackends())describe('drainTimeoutError', () => {test('progressing requests resume with twice the timeout', () => {-- const json = drainTimeoutError([{ kind: 'request', id: 'r1', detail: 'put_page running (source a)', needsUser: false }], 60_000).toJSON() as Record<string, any>;++ const json = drainTimeoutError({ blockers: [{ kind: 'request', id: 'r1', detail: 'put_page running (source a)', needsUser: false }], timeoutSec: 60 }).toJSON() as Record<string, any>;expect(json.code).toBe('graduation_drain_timeout');-- expect(json.fix.argv).toEqual(['gbrain', 'migrate', '--resume', '--drain-timeout', '120', '--json']);++ expect(json.fix.argv).toEqual(['gbrain', 'migrate', '--resume', '--drain-timeout', '120']);++ expect(json.reason).toBe('progressing');expect(json.fix.verify.argv).toEqual(['gbrain', 'migrate', '--status', '--json']);-- expect(json.why).toContain('source is unchanged and still writable');++ expect(json.why).toContain('source is unchanged and writable');});test('a blocker with its own action is named instead of a longer wait', () => {-- const json = drainTimeoutError([++ const json = drainTimeoutError({ blockers: [{ kind: 'request', id: 'r1', detail: 'running', needsUser: false },{ kind: 'request', id: 'r2', detail: 'recovering', argv: ['gbrain', 'sync', '--source', 'a', '--no-pull', '--retry-failed'], needsUser: false },-- ], 5_000).toJSON() as Record<string, any>;++ ], timeoutSec: 5 }).toJSON() as Record<string, any>;expect(json.fix.argv).toEqual(['gbrain', 'sync', '--source', 'a', '--no-pull', '--retry-failed']);expect(json.fix.actor).toBe('agent');});diff --cc test/graduation-rollback.test.tsindex a3f0dceab7,0000000000..0ec59dcff3mode 100644,000000..100644--- a/test/graduation-rollback.test.ts+++ b/test/graduation-rollback.test.ts@@@ -1,186 -1,0 +1,187 @@@+/**+ * Engine graduation rollback custody.+ *+ * Protects: rollback before cutover abandons the target (fence kept) and+ * leaves the source writable; after cutover it fences first, compares the+ * target with the graduation receipt and the retained source's security+ * state by identity and content, refuses finally on withdrawals and+ * revocations, needs `--yes --expect <hash>` for other user-data loss, never+ * writes back to the source, and returns the target to authority on every+ * refusal; durable substeps reconcile after a crash (back to authority before+ * approval, forward to rolled_back after it). Regressions that fail it: a+ * timestamp-based security check (revocations delete rows), a refusal that+ * strands the target fenced, a crash after approval that restores authority.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, lstatSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import {- planGraduation, readGraduationManifest, reconcileGraduation, rollbackGraduation, runGraduation, type GraduationRunOptions,++ planGraduation, readGraduationManifest, reconcileGraduation, rollbackGraduation, runGraduation, type GraduationOptions,+} from '../src/core/persistence/engine-graduation.ts';+import { assertGraduationConnectAllowed, readIntentMarker, readTombstone } from '../src/core/persistence/graduation-custody.ts';+import { graduationFenceStatus, readGraduationRow } from '../src/core/persistence/graduation-schema.ts';+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';+import { crashAt, makeHarness, openPglite, probeRows, SOURCE_TOKEN_ID, TARGET_URL, type Harness } from './helpers/graduation-harness.ts';++function codeOf(error: unknown): string | undefined { return (error as { code?: string })?.code; }+async function refusal(promise: Promise<unknown>): Promise<{ code?: string; fix?: { argv?: string[]; plan_hash?: string; consent?: string[] }; message: string }> {+ try { await promise; } catch (error) { return { code: codeOf(error), fix: (error as { fix?: never }).fix, message: (error as Error).message }; }+ throw new Error('expected a refusal');+}++const POSTGRES_URL = process.env.DATABASE_URL;+const targets: Array<[string, string | undefined]> = [['pglite target', undefined]];+if (POSTGRES_URL) { assertSafeE2eDatabaseUrl(POSTGRES_URL); targets.push(['postgres target', POSTGRES_URL]); }++for (const [label, postgresUrl] of targets) {+ describe(`graduation rollback (${label})`, () => {+ let h: Harness;+ beforeAll(async () => { h = await makeHarness({ postgresUrl }); });+ afterAll(async () => { await h.close(); });++ async function fresh(): Promise<void> { await h.close(); h = await makeHarness({ postgresUrl }); }- function runOpts(expect: string, extra: Partial<GraduationRunOptions> = {}): GraduationRunOptions {- return { config: { engine: 'pglite', database_path: h.dataDir } as GraduationRunOptions['config'], url: TARGET_URL, env: {}, expect, deps: h.deps, handoffTimeoutMs: 1_000, ...extra };++ function runOpts(expect: string, extra: Partial<GraduationOptions> = {}): GraduationOptions {++ return { config: { engine: 'pglite', database_path: h.dataDir } as GraduationOptions['config'], to: 'postgres', url: TARGET_URL, env: {}, drainTimeoutMs: 60_000,++ force: false, yes: true, expectPlanHash: expect, deps: h.deps, handoffTimeoutMs: 1_000, ...extra };+ }- async function graduate(extra: Partial<GraduationRunOptions> = {}): Promise<void> {++ async function graduate(extra: Partial<GraduationOptions> = {}): Promise<void> {+ const hash = (await planGraduation(runOpts(''))).planHash;+ await runGraduation(runOpts(hash, extra));+ }+ const rollbackOpts = (extra: Record<string, unknown> = {}) => ({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000, ...extra });+ const manifest = () => readGraduationManifest(join(h.gbrainDir, 'graduation-manifest.json'))!;+ const config = () => JSON.parse(readFileSync(join(h.gbrainDir, 'config.json'), 'utf8'));++ async function assertTargetAuthoritative(): Promise<void> {+ expect((await readGraduationRow(h.target))?.state).toBe('authoritative');+ expect((await graduationFenceStatus(h.target)).fenced).toBe(0);+ await h.target.executeRaw(`INSERT INTO grad_probe VALUES (700 + (SELECT count(*) FROM grad_probe)::int, 'normal-client-write')`);+ expect(lstatSync(h.dataDir).isFile()).toBe(true);+ }+ async function assertRolledBack(): Promise<void> {+ expect(manifest().state).toBe('rolled_back');+ expect(lstatSync(h.dataDir).isDirectory()).toBe(true);+ expect(readTombstone(h.dataDir)).toBeNull();+ expect(readIntentMarker(h.dataDir)).toBeNull();+ expect(config()).toMatchObject({ engine: 'pglite', database_path: h.dataDir });+ expect(config().database_url).toBeUndefined();+ const mounts = JSON.parse(readFileSync(h.mountsPath, 'utf8'));+ expect(mounts.mounts[0]).toMatchObject({ engine: 'pglite', database_path: h.dataDir });+ expect(mounts.mounts[0].database_url).toBeUndefined();+ expect((await readGraduationRow(h.target))?.state).toBe('rolled_back');+ expect((await graduationFenceStatus(h.target)).unfenced).toEqual([]);+ expect(codeOf(await assertGraduationConnectAllowed(h.target, {}).catch(e => e))).toBe('graduation_in_progress');+ const source = await openPglite(h.dataDir);+ try {+ expect((await readGraduationRow(source))?.state).toBe('rolled_back');+ await source.executeRaw(`INSERT INTO grad_probe VALUES (900, 'source-writable-again')`);+ } finally { await source.disconnect(); }+ }++ test('before cutover: the target is abandoned and stays fenced; the source is released writable', async () => {+ await h.inHome(async () => {+ await expect(graduate({ pauseAt: 'verified', pauseHook: crashAt('verified') })).rejects.toThrow();+ const result = await rollbackGraduation(rollbackOpts());+ expect(result.state).toBe('abandoned');+ expect(manifest().state).toBe('abandoned');+ expect(readIntentMarker(h.dataDir)).toBeNull();+ expect((await readGraduationRow(h.target))?.state).toBe('abandoned');+ expect((await graduationFenceStatus(h.target)).unfenced).toEqual([]);+ await expect(h.target.executeRaw(`INSERT INTO grad_probe VALUES (50, 'x')`)).rejects.toThrow(/graduation_in_progress/);+ const source = await openPglite(h.dataDir);+ try {+ expect((await readGraduationRow(source))?.state).toBe('rolled_back');+ await source.executeRaw(`INSERT INTO grad_probe VALUES (51, 'writable')`);+ } finally { await source.disconnect(); }+ });+ }, 120_000);++ test('after graduation with no target writes: the datastore, routing and mounts are restored', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`UPDATE access_tokens SET last_used_at = now() WHERE id = $1::uuid`, [SOURCE_TOKEN_ID]);+ const result = await rollbackGraduation(rollbackOpts());+ expect(result.state).toBe('rolled_back');+ await assertRolledBack();+ });+ }, 120_000);++ test('a target page-style edit is listed and rolls back only with the expect hash; it is never written back', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`INSERT INTO grad_probe VALUES (10, 'written-on-target')`);+ const refused = await refusal(rollbackGraduation(rollbackOpts()));+ expect(refused.code).toBe('graduation_rollback_writes_lost');+ expect(refused.message).toContain('grad_probe');+ expect(refused.fix?.consent).toEqual(['destructive']);+ const hash = refused.fix!.plan_hash!;+ expect(refused.fix?.argv).toEqual(['gbrain', 'migrate', '--rollback-to-source', '--yes', '--expect', hash]);+ expect(manifest().state).toBe('graduated');+ await assertTargetAuthoritative();- const wrong = await refusal(rollbackGraduation(rollbackOpts({ yes: true, expect: '0000000000000000' })));++ const wrong = await refusal(rollbackGraduation(rollbackOpts({ yes: true, expectPlanHash: '0000000000000000' })));+ expect(wrong.code).toBe('graduation_rollback_writes_lost');+ const relisted = wrong.fix!.plan_hash!;- await rollbackGraduation(rollbackOpts({ yes: true, expect: relisted }));++ await rollbackGraduation(rollbackOpts({ yes: true, expectPlanHash: relisted }));+ await assertRolledBack();+ const source = await openPglite(h.dataDir);+ try { expect((await probeRows(source)).map(r => r.v)).not.toContain('written-on-target'); } finally { await source.disconnect(); }+ });+ }, 120_000);++ test('a fact withdrawal on the target refuses finally, with and without --yes', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', 'hash-w1')`);- for (const extra of [{}, { yes: true, expect: 'anything' }]) {++ for (const extra of [{}, { yes: true, expectPlanHash: 'anything' }]) {+ const refused = await refusal(rollbackGraduation(rollbackOpts(extra)));+ expect(refused.code).toBe('graduation_rollback_writes_lost');+ expect(refused.fix?.argv).toBeUndefined();+ expect(refused.message).toContain('fact_withdrawals');+ await assertTargetAuthoritative();+ }+ });+ }, 120_000);++ test('a token revocation on the target (the row is deleted) refuses finally', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await h.target.executeRaw(`DELETE FROM access_tokens WHERE id = $1::uuid`, [SOURCE_TOKEN_ID]);- const refused = await refusal(rollbackGraduation(rollbackOpts({ yes: true, expect: 'x' })));++ const refused = await refusal(rollbackGraduation(rollbackOpts({ yes: true, expectPlanHash: 'x' })));+ expect(refused.code).toBe('graduation_rollback_writes_lost');+ expect(refused.fix?.argv).toBeUndefined();- expect(refused.message).toContain('access_tokens: 1 missing');++ expect(refused.message).toContain('access_tokens missing (1)');+ await assertTargetAuthoritative();+ });+ }, 120_000);++ test('a crash after fencing returns the target to authority; a crash after approval rolls forward', async () => {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await expect(rollbackGraduation(rollbackOpts({ pauseAt: 'rollback_fenced', pauseHook: crashAt('rollback_fenced') }))).rejects.toThrow();+ expect((await readGraduationRow(h.target))?.state).toBe('rollback_fenced');+ await expect(h.target.executeRaw(`INSERT INTO grad_probe VALUES (60, 'x')`)).rejects.toThrow(/graduation_in_progress/);+ const reconciled = await reconcileGraduation(rollbackOpts());+ expect(reconciled.actions).toContain('returned target to authority');+ expect(manifest().state).toBe('graduated');+ await assertTargetAuthoritative();+ });+ for (const seam of ['rollback_approved', 'source_restoring', 'tombstone_removed', 'renamed_back', 'config_restored']) {+ await fresh();+ await h.inHome(async () => {+ await graduate();+ await expect(rollbackGraduation(rollbackOpts({ pauseAt: seam, pauseHook: crashAt(seam) }))).rejects.toThrow();+ expect(['rollback_approved', 'source_restoring']).toContain(manifest().state);+ const reconciled = await reconcileGraduation(rollbackOpts());+ expect(reconciled.actions).toContain('finished rollback');+ await assertRolledBack();+ expect(existsSync(`${h.dataDir}.graduated-${manifest().runId}`)).toBe(false);+ });+ }+ }, 120_000);+ });+}diff --cc test/graduation-state.test.tsindex d12c3b04fe,0000000000..689cb71385mode 100644,000000..100644--- a/test/graduation-state.test.ts+++ b/test/graduation-state.test.ts@@@ -1,339 -1,0 +1,346 @@@+/**+ * Engine graduation state machine and run custody.+ *+ * Protects: the transition tables drive every manifest/row change (an illegal+ * transition throws); manifest v3 is 0600 and never leaks the password; the+ * run reaches exactly one authoritative engine from a fresh start and after a+ * crash at every custody seam; the target fence refuses every writer but the+ * run; a source change during a lock gap reaches the target; a stray+ * datastore at the old path is split brain with the target withheld;+ * refusals before the fence leave the source writable; --status mutates+ * nothing. Regressions that fail it: a resume that trusts current routing, a+ * cutover that grants authority before the tombstone, a fence that admits+ * unidentified sessions, a lock gap that skips the re-check.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, lstatSync, mkdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import {+ assertTransition, GRADUATION_RUN_BOUNDARIES, MANIFEST_STATES, MANIFEST_TRANSITIONS, SOURCE_ROW_STATES, SOURCE_TRANSITIONS, TARGET_ROW_STATES, TARGET_TRANSITIONS,+ type GraduationManifest, type ManifestState,+} from '../src/core/persistence/engine-graduation.types.ts';+import {+ graduationStatus, planGraduation, readGraduationManifest, redactManifest, resumeGraduation, runGraduation, transitionManifest,- writeGraduationManifest, type GraduationRunOptions,++ writeGraduationManifest, type GraduationOptions,+} from '../src/core/persistence/engine-graduation.ts';+import { assertGraduationAdmission, assertGraduationConnectAllowed, graduatedPath, readIntentMarker, readTombstone } from '../src/core/persistence/graduation-custody.ts';+import { graduationFenceStatus, readGraduationRow, setSourceState, setTargetState, withGraduationRun } from '../src/core/persistence/graduation-schema.ts';+import { LiveServeLockError } from '../src/core/pglite-lock.ts';+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';+import { crashAt, makeHarness, openPglite, probeRows, TARGET_URL, type Harness } from './helpers/graduation-harness.ts';++/** Another process opening the datastore (a respawned serve): its refusal code, or 'opened'. */+function openInChild(dataDir: string): string {+ const script = `import { PGLiteEngine } from ${JSON.stringify(join(import.meta.dir, '../src/core/pglite-engine.ts'))};+const e = new PGLiteEngine();+try { await e.connect({ engine: 'pglite', database_path: ${JSON.stringify(dataDir)} }); console.log('opened'); await e.disconnect(); }+catch (err) { console.log(err?.code ?? String(err)); }`;+ const child = Bun.spawnSync([process.execPath, '-e', script], { stdout: 'pipe', stderr: 'pipe', timeout: 60_000 });+ return child.stdout.toString().trim().split('\n').pop() ?? '';+}++function codeOf(error: unknown): string | undefined { return (error as { code?: string })?.code; }+async function refusal(promise: Promise<unknown>): Promise<{ code?: string; fix?: { argv?: string[]; plan_hash?: string }; message: string }> {+ try { await promise; } catch (error) { return { code: codeOf(error), fix: (error as { fix?: { argv?: string[] } }).fix, message: (error as Error).message }; }+ throw new Error('expected a refusal');+}++describe('transition tables', () => {+ const tables = [+ ['manifest', MANIFEST_STATES, MANIFEST_TRANSITIONS],+ ['target', TARGET_ROW_STATES, TARGET_TRANSITIONS],+ ['source', SOURCE_ROW_STATES, SOURCE_TRANSITIONS],+ ] as const;+ for (const [name, states, table] of tables) {+ test(`${name}: assertTransition admits exactly the listed transitions`, () => {+ for (const from of states) {+ for (const to of states) {+ const allowed = (table as Record<string, readonly string[]>)[from]!.includes(to);+ const attempt = () => assertTransition(table as Record<string, readonly string[]>, from, to);+ if (allowed) expect(attempt).not.toThrow(); else expect(attempt).toThrow(/Illegal graduation transition/);+ }+ }+ });+ }+ test('every manifest state is reachable from planned, and terminal states have no exit', () => {+ const seen = new Set<string>(['planned']);+ const queue: string[] = ['planned'];+ while (queue.length) for (const next of MANIFEST_TRANSITIONS[queue.shift() as ManifestState]) if (!seen.has(next)) { seen.add(next); queue.push(next); }+ expect([...seen].sort()).toEqual([...MANIFEST_STATES].sort());+ expect(MANIFEST_TRANSITIONS.rolled_back).toEqual([]);+ expect(MANIFEST_TRANSITIONS.abandoned).toEqual([]);+ expect(MANIFEST_TRANSITIONS.rollback_approved).toEqual(['source_restoring']);+ });+});++describe('manifest v3', () => {+ let h: Harness;+ beforeAll(async () => { h = await makeHarness(); });+ afterAll(async () => { await h.close(); });++ test('written 0600 atomically, round-trips, redaction drops the URLs, illegal transitions throw', () => {+ const path = join(h.root, 'manifest-check.json');+ const m: GraduationManifest = {+ version: 3, runId: 'r', state: 'planned', source: { dataDir: h.dataDir, brainId: '', hostId: '' },+ target: { id: 'x', host: 'h', port: 5432, database: 'd', user: 'u' }, routes: { main: 'postgres://u@h:5432/d', ddl: 'postgres://u@h:5432/d' },+ inventoryVersion: 1, schemaVersion: 1, planHash: 'p', triggerBypass: 'session_replication_role', tables: [], timings: {},+ startedAt: '', updatedAt: '', targetUrls: { main: TARGET_URL, ddl: TARGET_URL },+ };+ writeGraduationManifest(m, path);+ expect(statSync(path).mode & 0o777).toBe(0o600);+ expect(readGraduationManifest(path)).toEqual(m);+ expect(JSON.stringify(redactManifest(m))).not.toContain('secret-pw');+ expect(() => transitionManifest(m, 'cutover')).toThrow(/planned -> cutover/);+ transitionManifest(m, 'quiesced');+ expect(m.state).toBe('quiesced');+ });+});++describe('row state machine, connect and admission checks', () => {+ let h: Harness;+ beforeAll(async () => { h = await makeHarness(); await h.target.initSchema(); });+ afterAll(async () => { await h.close(); });++ test('target row transitions follow TARGET_TRANSITIONS; connect and admission refuse until authority', async () => {+ const run = crypto.randomUUID();+ const t = h.target;+ await expect(withGraduationRun(t, run, tx => setTargetState(tx, run, 'verified'))).rejects.toThrow(/\(none\) -> verified/);+ await withGraduationRun(t, run, tx => setTargetState(tx, run, 'copying'));+ await expect(withGraduationRun(t, run, tx => setTargetState(tx, run, 'authoritative'))).rejects.toThrow(/copying -> authoritative/);+ expect(codeOf(await assertGraduationConnectAllowed(t, {}).catch(e => e))).toBe('graduation_in_progress');+ await expect(assertGraduationConnectAllowed(t, { GBRAIN_GRADUATION_RUN: run })).resolves.toBeUndefined();+ expect(codeOf(await t.transaction(tx => assertGraduationAdmission(tx)).catch(e => e))).toBe('graduation_in_progress');+ await expect(withGraduationRun(t, run, tx => assertGraduationAdmission(tx))).resolves.toBeUndefined();+ await expect(withGraduationRun(t, crypto.randomUUID(), tx => setTargetState(tx, crypto.randomUUID(), 'copying'))).rejects.toThrow(/belongs to graduation run/);+ await withGraduationRun(t, run, async tx => { await setTargetState(tx, run, 'verifying'); await setTargetState(tx, run, 'verified'); await setTargetState(tx, run, 'authoritative'); });+ await expect(assertGraduationConnectAllowed(t, {})).resolves.toBeUndefined();+ await expect(t.transaction(tx => assertGraduationAdmission(tx))).resolves.toBeUndefined();+ }, 60_000);++ test('a source row at cutover refuses: interrupted before the tombstone exists', async () => {+ const source = await openPglite(join(h.root, 'cutover-source.pglite'));+ try {+ await source.initSchema();+ const run = crypto.randomUUID();+ await withGraduationRun(source, run, tx => setSourceState(tx, run, 'quiesced', { sourceDataDir: join(h.root, 'cutover-source.pglite') }));+ await expect(assertGraduationConnectAllowed(source, {})).resolves.toBeUndefined();+ await withGraduationRun(source, run, tx => setSourceState(tx, run, 'cutover'));+ expect(codeOf(await assertGraduationConnectAllowed(source, {}).catch(e => e))).toBe('graduation_interrupted');+ expect(codeOf(await source.transaction(tx => assertGraduationAdmission(tx)).catch(e => e))).toBe('graduation_interrupted');+ await expect(withGraduationRun(source, run, tx => setSourceState(tx, run, 'quiesced'))).resolves.toBeUndefined();+ } finally { await source.disconnect(); }+ }, 60_000);+});++const POSTGRES_URL = process.env.DATABASE_URL;+const targets: Array<[string, string | undefined]> = [['pglite target', undefined]];+if (POSTGRES_URL) { assertSafeE2eDatabaseUrl(POSTGRES_URL); targets.push(['postgres target', POSTGRES_URL]); }++for (const [label, postgresUrl] of targets) {+ describe(`graduation run (${label})`, () => {+ let h: Harness;+ beforeAll(async () => { h = await makeHarness({ postgresUrl }); });+ afterAll(async () => { await h.close(); });++ async function fresh(): Promise<void> { await h.close(); h = await makeHarness({ postgresUrl }); }- function runOpts(expect: string, extra: Partial<GraduationRunOptions> = {}): GraduationRunOptions {- return { config: { engine: 'pglite', database_path: h.dataDir } as GraduationRunOptions['config'], url: TARGET_URL, env: {}, expect, deps: h.deps, handoffTimeoutMs: 1_000, ...extra };++ function runOpts(expect: string, extra: Partial<GraduationOptions> = {}): GraduationOptions {++ return { config: { engine: 'pglite', database_path: h.dataDir } as GraduationOptions['config'], to: 'postgres', url: TARGET_URL, env: {}, drainTimeoutMs: 60_000,++ force: false, yes: true, expectPlanHash: expect, deps: h.deps, handoffTimeoutMs: 1_000, ...extra };+ }- async function plan(extra: Partial<GraduationRunOptions> = {}): Promise<string> {- return (await planGraduation(runOpts('', extra))).planHash;++ async function plan(extra: Partial<GraduationOptions> = {}): Promise<string> {++ return (await planGraduation(runOpts('', { yes: false, ...extra }))).planHash;+ }+ async function assertGraduated(): Promise<void> {+ const config = JSON.parse(readFileSync(join(h.gbrainDir, 'config.json'), 'utf8'));+ expect(config.engine).toBe('postgres');+ expect(config.database_url).toBe(TARGET_URL);+ expect(config.database_path).toBeUndefined();+ expect(lstatSync(h.dataDir).isFile()).toBe(true);+ const tombstone = readTombstone(h.dataDir)!;+ expect(JSON.stringify(tombstone)).not.toContain('secret-pw');+ expect(existsSync(tombstone.movedTo)).toBe(true);+ const row = await readGraduationRow(h.target);+ expect(row?.state).toBe('authoritative');+ expect((await graduationFenceStatus(h.target)).fenced).toBe(0);+ expect((await probeRows(h.target)).map(r => r.v)).toEqual(['alpha', 'beta', 'gamma']);+ const manifest = readGraduationManifest(join(h.gbrainDir, 'graduation-manifest.json'))!;+ expect(manifest.state).toBe('graduated');+ expect(statSync(join(h.gbrainDir, 'graduation-manifest.json')).mode & 0o777).toBe(0o600);+ const mounts = JSON.parse(readFileSync(h.mountsPath, 'utf8'));+ expect(mounts.mounts[0]).toMatchObject({ id: 'team-example', engine: 'postgres', database_url: TARGET_URL });+ expect(mounts.mounts[0].database_path).toBeUndefined();+ const reopen = await openPglite(h.dataDir).catch(e => e);+ expect(codeOf(reopen)).toBe('engine_graduated');+ expect(lstatSync(h.dataDir).isFile()).toBe(true);+ }++ test('plan -> run reaches one authoritative engine; the source path is a tombstone', async () => {+ await h.inHome(async () => {+ const hash = await plan();+ const receipt = await runGraduation(runOpts(hash));+ expect(receipt.state).toBe('authoritative');+ expect(receipt.triggerBypass).toBe('session_replication_role');+ await assertGraduated();+ const moved = readTombstone(h.dataDir)!.movedTo;+ const retained = await openPglite(moved);+ try { expect((await readGraduationRow(retained))?.state).toBe('cutover'); } finally { await retained.disconnect(); }+ expect(h.calls.pause_released).toBe(1);+ });+ }, 60_000);++ test('the fence refuses other writers while the copy runs; the run itself writes', async () => {+ await fresh();+ await h.inHome(async () => {+ let observed: { write?: string; exempt?: boolean; respawn?: string } = {};+ const hash = await plan();+ await runGraduation(runOpts(hash, { pauseAt: 'table_copied', pauseHook: async () => {+ const run = readGraduationManifest(join(h.gbrainDir, 'graduation-manifest.json'))!.runId;+ observed = {+ ...observed,+ write: await h.target.executeRaw(`INSERT INTO config (key, value) VALUES ('stray', 'x')`).then(() => 'accepted', (e: Error) => e.message.split(':')[0]),+ exempt: await assertGraduationConnectAllowed(h.target, { GBRAIN_GRADUATION_RUN: run }).then(() => true),+ };+ const marker = readIntentMarker(h.dataDir)!;+ expect(marker.state).toBe('copying');+ observed.respawn = openInChild(h.dataDir);+ } }));+ expect(observed).toEqual({ write: 'graduation_in_progress', exempt: true, respawn: 'graduation_in_progress' });+ await assertGraduated();+ });+ }, 60_000);++ const seams = GRADUATION_RUN_BOUNDARIES.filter(b => b !== 'batch_copied' && b !== 'graduated');+ for (const seam of seams) {+ test(`a crash at ${seam} resumes to exactly one authoritative engine`, async () => {+ await fresh();+ await h.inHome(async () => {+ const hash = await plan();+ await expect(runGraduation(runOpts(hash, { pauseAt: seam, pauseHook: crashAt(seam) }))).rejects.toThrow(`simulated crash at ${seam}`);- const status = await graduationStatus();- expect(status.live).toBe(false);++ const status = await graduationStatus({ deps: h.deps });++ expect(status.liveRun).toBeNull();+ expect(status.nextArgv).toEqual(['gbrain', 'migrate', '--resume']);+ const row = await readGraduationRow(h.target);+ if (row) expect(row.state === 'authoritative' ? seam : 'non-authoritative').toBe(['authoritative', 'config_flipped', 'registry_rewritten'].includes(seam) ? seam : 'non-authoritative');+ await resumeGraduation({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000 });+ await assertGraduated();+ });+ }, 60_000);+ }++ test('a source write during a lock gap after verify reaches the target', async () => {+ await fresh();+ await h.inHome(async () => {+ const hash = await plan();+ await expect(runGraduation(runOpts(hash, { pauseAt: 'verified', pauseHook: crashAt('verified') }))).rejects.toThrow();+ const copiesBefore = h.calls.copy_probe ?? 0;+ const source = await openPglite(h.dataDir);+ try { await source.executeRaw(`INSERT INTO grad_probe VALUES (4, 'written-in-gap')`); } finally { await source.disconnect(); }+ await resumeGraduation({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000 });+ expect(h.calls.copy_probe).toBe(copiesBefore + 1);+ expect((await probeRows(h.target)).map(r => r.v)).toContain('written-in-gap');+ });+ }, 60_000);++ test('a stray datastore at the old path is split brain; the target stays non-authoritative', async () => {+ await fresh();+ await h.inHome(async () => {+ const hash = await plan();+ await expect(runGraduation(runOpts(hash, { pauseAt: 'moved_aside', pauseHook: crashAt('moved_aside') }))).rejects.toThrow();+ mkdirSync(h.dataDir);+ const refused = await refusal(resumeGraduation({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000 }));+ expect(refused.code).toBe('graduation_split_brain');- expect(refused.fix?.argv?.[0]).toBe('mv');++ expect(refused.fix?.argv).toEqual(['gbrain', 'migrate', '--resume', '--yes']);+ expect((await readGraduationRow(h.target))?.state).toBe('verified');- expect((await graduationStatus()).path?.kind).toBe('split_brain');++ const status = await graduationStatus({ deps: h.deps });++ expect(status.sourcePath?.state).toBe('split_brain');++ expect(status.splitBrain?.map(side => side.path)).toEqual([h.dataDir, `${h.dataDir}.graduated-${status.runId}`]);++ await resumeGraduation({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000, yes: true });++ expect(existsSync(`${h.dataDir}.stray-${status.runId}`)).toBe(true);++ await assertGraduated();+ });+ }, 60_000);++ test('a path occupied when the live run creates the tombstone refuses as split brain', async () => {+ await fresh();+ await h.inHome(async () => {+ const hash = await plan();+ const refused = await refusal(runGraduation(runOpts(hash, { pauseAt: 'moved_aside', pauseHook: async () => { mkdirSync(h.dataDir); } })));+ expect(refused.code).toBe('graduation_split_brain');+ expect((await readGraduationRow(h.target))?.state).toBe('verified');+ expect((await graduationFenceStatus(h.target)).unfenced).toEqual([]);+ });+ }, 60_000);++ test('a changed plan refuses before anything is fenced and leaves the source writable', async () => {+ await fresh();+ await h.inHome(async () => {+ const refused = await refusal(runGraduation(runOpts('0000000000000000')));+ expect(refused.code).toBe('preview_changed');+ expect(readIntentMarker(h.dataDir)).toBeNull();+ expect(readGraduationManifest(join(h.gbrainDir, 'graduation-manifest.json'))?.state).toBe('abandoned');+ const source = await openPglite(h.dataDir);+ try { await source.executeRaw(`INSERT INTO grad_probe VALUES (9, 'still-writable')`); } finally { await source.disconnect(); }+ expect(await readGraduationRow(h.target)).toBeNull();+ });+ }, 60_000);++ test('a live serve that never hands off refuses with the two-step writer-held fix; one that does is waited for', async () => {+ await fresh();+ await h.inHome(async () => {+ const hash = await plan();+ const held = { ...h.deps, openSource: async () => { throw new LiveServeLockError('held by serve', { pid: 424242, transport: 'stdio' }); } };+ const refused = await refusal(runGraduation(runOpts(hash, { deps: held, handoffTimeoutMs: 300 })));+ expect(refused.code).toBe('graduation_source_writer_held');+ expect(refused.fix?.argv).toEqual(['kill', '424242']);+ expect(readIntentMarker(h.dataDir)).toBeNull();+ let refusals = 2;+ const { defaultGraduationDeps } = await import('../src/core/persistence/engine-graduation.ts');+ const real = defaultGraduationDeps();+ const handOff = { ...h.deps, openSource: async (dir: string, o: { migrate: boolean }) => {+ if (refusals-- > 0) throw new LiveServeLockError('held by serve', { pid: 424242, transport: 'stdio' });+ return real.openSource.call(real, dir, o);+ } };+ await runGraduation(runOpts(hash, { deps: handOff, handoffTimeoutMs: 5_000 }));+ await assertGraduated();+ });+ }, 60_000);++ test('a drain timeout and a verify failure are resumable; the source stays writable in between', async () => {+ await fresh();+ await h.inHome(async () => {+ const hash = await plan();+ const stuck = { ...h.deps, drainForGraduation: async () => ({ drained: [], blockers: [{ kind: 'request' as const, id: 'req-1', detail: 'running', needsUser: false }] }) };+ const timeout = await refusal(runGraduation(runOpts(hash, { deps: stuck, drainTimeoutMs: 60_000 })));+ expect(timeout.code).toBe('graduation_drain_timeout');- expect(timeout.fix?.argv).toEqual(['gbrain', 'migrate', '--resume', '--drain-timeout', '120', '--json']);++ expect(timeout.fix?.argv).toEqual(['gbrain', 'migrate', '--resume', '--drain-timeout', '120']);+ expect(readGraduationManifest(join(h.gbrainDir, 'graduation-manifest.json'))?.state).toBe('draining');+ const failing = { ...h.deps, verifyGraduation: async () => ({ ok: false, tables: [], failures: [{ relation: 'grad_probe', kind: 'digest' as const, detail: 'mismatch' }], replay: { status: 'not_available' as const, reason: 'no_caller_input' as const }, doctorFailingChecks: [] }) };+ const failed = await refusal(resumeGraduation({ env: {}, deps: failing, handoffTimeoutMs: 1_000 }));+ expect(failed.code).toBe('graduation_verify_failed');+ expect((await readGraduationRow(h.target))?.state).toBe('verify_failed');+ const source = await openPglite(h.dataDir);+ try { await source.executeRaw(`INSERT INTO grad_probe VALUES (5, 'after-verify-failure')`); } finally { await source.disconnect(); }+ await resumeGraduation({ env: {}, deps: h.deps, handoffTimeoutMs: 1_000 });+ expect((await probeRows(h.target)).map(r => r.v)).toContain('after-verify-failure');+ expect(lstatSync(h.dataDir).isFile()).toBe(true);+ });+ }, 60_000);++ test('--status performs zero mutations at a crash point', async () => {+ await fresh();+ await h.inHome(async () => {+ const hash = await plan();+ await expect(runGraduation(runOpts(hash, { pauseAt: 'source_cutover', pauseHook: crashAt('source_cutover') }))).rejects.toThrow();+ const files = [join(h.gbrainDir, 'graduation-manifest.json'), `${h.dataDir}.gbrain-graduation.json`, join(h.gbrainDir, 'config.json')];+ const before = files.map(f => [readFileSync(f, 'utf8'), statSync(f).mtimeMs]);- const status = await graduationStatus();++ const status = await graduationStatus({ deps: h.deps });+ expect(status.state).toBe('cutover');- expect(status.path?.kind).toBe('interrupted');++ expect(status.sourcePath?.state).toBe('interrupted');++ expect(status.target?.row).toBe('verified');+ expect(JSON.stringify(status)).not.toContain('secret-pw');+ expect(files.map(f => [readFileSync(f, 'utf8'), statSync(f).mtimeMs])).toEqual(before);+ expect(existsSync(graduatedPath(h.dataDir, status.runId!))).toBe(false);+ });+ }, 60_000);+ });+}diff --cc test/migrate-graduation-cli.serial.test.tsindex 0000000000,ba7715c777..28160d6632mode 000000,100644..100644--- a/test/migrate-graduation-cli.serial.test.ts+++ b/test/migrate-graduation-cli.serial.test.ts@@@ -1,0 -1,252 +1,251 @@@+ /**+ * `gbrain migrate` engine graduation CLI (plan §7, DX amendments): routing,+ * flag parsing, the exit-3 consent payload, `--plan`, the run, run-scoped+ * verbs, the exit-code map (0/1/2/3/11/75/130) and secret hygiene, over a+ * fake orchestrator (the G2a module is exercised by its own lane's tests).+ * Serial: it points GBRAIN_HOME at a temp dir and reads the file-plane+ * opt-out from it.+ */+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+ import { tmpdir } from 'node:os';+ import { join } from 'node:path';+ import { withEnv } from './helpers/with-env.ts';+ import { opError } from '../src/core/ops/contract.ts';+ import { renderCliError } from '../src/core/agent-output.ts';+ import type { ProgressReporter } from '../src/core/progress.ts';+ import type {+ GraduationCommandOptions, GraduationPlan, GraduationReceipt, GraduationStatusDoc,+ } from '../src/core/persistence/engine-graduation.types.ts';+ import { drainTimeoutError, inProgressError } from '../src/core/persistence/graduation-errors.ts';-import { drainTimeoutError as drainRefusal } from '../src/core/persistence/graduation-drain.ts';+ import {+ parseGraduationArgs, routesToGraduation, runMigrateGraduation, type GraduationApi,+ } from '../src/commands/migrate-graduation.ts';++ const SECRET_URL = 'postgresql://alice:[email protected]:5432/brain';+ let home: string;++ beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-grad-cli-'));+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, 'brain.pglite') }));+ });+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });++ const plan: GraduationPlan = {+ planHash: 'ph_0123456789abcdef01234567',+ source: { dataDir: '/home/alice-example/.gbrain/brain.pglite', brainId: 'brain-1', hostId: 'host-1' },+ target: { id: 'tid', host: 'db.acme-example.test', port: 5432, database: 'brain', user: 'alice' },+ routes: { main: 'postgresql://alice:***@db.acme-example.test:5432/brain', ddl: 'postgresql://alice:***@db.acme-example.test:5432/brain', urlEnv: 'GBRAIN_TARGET_URL' },+ triggerBypass: 'session_replication_role',+ tables: [{ relation: 'pages', class: 'carry', rows: 10, bytes: 100 }, { relation: 'query_cache', class: 'rebuild', rows: 3, bytes: 1 }],+ blockers: [],+ estimateSeconds: { copy: 1, verify: 1, doctor: 2, total: 4 },+ sourceMeasured: 'now',+ nextArgv: [],+ };+ const receipt: GraduationReceipt = {+ runId: 'run-1', state: 'authoritative', tables: [{ relation: 'pages', rows: 10, rootSha256: 'x', batches: [] }],+ triggerBypass: 'session_replication_role', replay: { status: 'passed', requestId: 'r1' }, timings: { copy: 1000 },+ targetDisplayUrl: 'postgresql://alice:***@db.acme-example.test:5432/brain', retainedPath: '/home/alice-example/.gbrain/brain.pglite.graduated-run-1',+ serveHandoff: true, doctor: { source: [], target: [] },+ };+ const statusDoc: GraduationStatusDoc = {+ schema_version: 1, state: 'copying', runId: 'run-1', to: 'postgres', source: plan.source, sourcePath: null,+ target: { identity: plan.target, displayUrl: plan.routes.main, row: 'copying', reachable: true }, receipt: null,+ liveRun: { pid: 123 }, tables: [], nextArgv: ['gbrain', 'migrate', '--status', '--json'],+ };++ function fakeApi(over: Partial<GraduationApi> = {}): GraduationApi & { calls: { fn: string; opts?: GraduationCommandOptions }[] } {+ const calls: { fn: string; opts?: GraduationCommandOptions }[] = [];+ return {+ calls,+ planGraduation: async (opts) => { calls.push({ fn: 'plan', opts }); return plan; },+ runGraduation: async (opts) => { calls.push({ fn: 'run', opts }); return receipt; },+ graduationStatus: async () => { calls.push({ fn: 'status' }); return statusDoc; },+ resumeGraduation: async (opts) => { calls.push({ fn: 'resume', opts }); return receipt; },+ rollbackGraduation: async (opts) => { calls.push({ fn: 'rollback', opts }); return { state: 'abandoned', restoredPath: null, dropped: [] }; },+ ...over,+ };+ }++ const silentProgress: ProgressReporter = { start() {}, tick() {}, heartbeat() {}, finish() {}, child() { return silentProgress; } };++ async function run(args: string[], api = fakeApi(), extra: { env?: NodeJS.ProcessEnv; signal?: AbortSignal; stdin?: string } = {}) {+ const out: string[] = [];+ const err: string[] = [];+ const realStdout = process.stdout.write.bind(process.stdout);+ const realStderr = process.stderr.write.bind(process.stderr);+ process.stdout.write = ((s: string) => { out.push(String(s)); return true; }) as typeof process.stdout.write;+ process.stderr.write = ((s: string) => { err.push(String(s)); return true; }) as typeof process.stderr.write;+ try {+ const code = await withEnv({ GBRAIN_HOME: home }, () => runMigrateGraduation(args, {+ api, env: extra.env ?? { GBRAIN_TARGET_URL: SECRET_URL }, out: t => { out.push(t); }, err: t => { err.push(t); },+ progress: silentProgress, signal: extra.signal ?? new AbortController().signal,+ writeError: (e, o) => {+ const r = renderCliError(e, { json: o.json, command: 'migrate', tty: false });+ if (r.stdout) out.push(JSON.stringify({ ...(o.legacy ?? {}), ...JSON.parse(r.stdout) }));+ if (r.stderr) err.push(r.stderr);+ return r.exitCode;+ },+ ...(extra.stdin !== undefined ? { readStdin: async () => extra.stdin! } : {}),+ }));+ return { code, stdout: out.join(''), stderr: err.join(''), api };+ } finally {+ process.stdout.write = realStdout;+ process.stderr.write = realStderr;+ }+ }++ describe('routing', () => {+ const pglite = { engine: 'pglite' as const, database_path: '/x/brain.pglite' };+ test('PGLite --to postgres|supabase routes to graduation; other forms fall through', () => {+ expect(routesToGraduation(['--to', 'postgres', '--url-env', 'X'], pglite, 'linux')).toBe(true);+ expect(routesToGraduation(['--to', 'supabase'], pglite, 'darwin')).toBe(true);+ expect(routesToGraduation(['--to=postgres'], pglite, 'linux')).toBe(true);+ expect(routesToGraduation(['--to', 'pglite'], { engine: 'postgres', database_url: 'postgresql://h/db' }, 'linux')).toBe(false);+ expect(routesToGraduation(['embeddings', '--to', 'openai:x'], pglite, 'linux')).toBe(false);+ expect(routesToGraduation(['--to', 'postgres', '--help'], pglite, 'linux')).toBe(false);+ expect(routesToGraduation(['--to', 'postgres'], { engine: 'postgres', database_url: 'postgresql://h/db' }, 'linux')).toBe(false);+ });+ test('opt-out and Windows keep the legacy copier for the bare run; run-scoped verbs always route', () => {+ expect(routesToGraduation(['--to', 'postgres'], { ...pglite, migrate: { graduation: false } }, 'linux')).toBe(false);+ expect(routesToGraduation(['--to', 'postgres'], pglite, 'win32')).toBe(false);+ for (const verb of ['--status', '--resume', '--rollback-to-source', '--plan', '--dry-run']) {+ expect(routesToGraduation([verb], { ...pglite, migrate: { graduation: false } }, 'win32')).toBe(true);+ }+ });+ });++ describe('parseGraduationArgs', () => {+ test('modes, aliases and escape hatches', () => {+ expect(parseGraduationArgs(['--to', 'supabase', '--dry-run']).mode).toBe('plan');+ expect(parseGraduationArgs(['--status']).mode).toBe('status');+ const a = parseGraduationArgs(['--to', 'postgres', '--url-env', 'U', '--drain-timeout', '120', '--trigger-bypass', 'disable-trigger', '--batch-size', '500', '--yes', '--expect', 'ph_x']);+ expect(a).toMatchObject({ mode: 'run', to: 'postgres', urlEnv: 'U', drainTimeoutSec: 120, triggerBypass: 'disable_trigger', batchSize: 500, yes: true, expect: 'ph_x' });+ expect(parseGraduationArgs(['--to', 'postgres']).drainTimeoutSec).toBe(60);+ expect(parseGraduationArgs(['--to', 'postgres', '--url', '-']).urlFromStdin).toBe(true);+ });+ test.each([+ [['--plan', '--status']], [['--resume', '--rollback-to-source']], [['--to', 'mysql']], [['--to', 'pglite', '--plan']],+ [['--plan']], [['--to', 'postgres', '--url', 'u', '--url-env', 'V']], [['--to', 'postgres', '--drain-timeout', '0']],+ [['--to', 'postgres', '--trigger-bypass', 'off']], [['--status', '--yes']], [['--to', 'postgres', '--url']],+ ])('usage error %j', (args) => {+ let code: string | undefined;+ try { parseGraduationArgs(args); } catch (e) { code = (e as { code?: string }).code; }+ expect(code).toBe('invalid_params');+ });+ });++ describe('runMigrateGraduation', () => {+ test('bare run: exit 3 consent payload bound to the plan, never the password', async () => {+ const r = await run(['--to', 'supabase', '--url-env', 'GBRAIN_TARGET_URL', '--json']);+ expect(r.code).toBe(3);+ const doc = JSON.parse(r.stdout);+ expect(doc.code).toBe('confirmation_required');+ expect(doc.effects).toEqual(['egress', 'destructive']);+ expect(doc.plan_hash).toBe(plan.planHash);+ expect(doc.fix.argv).toEqual(['gbrain', 'migrate', '--to', 'supabase', '--url-env', 'GBRAIN_TARGET_URL', '--yes', '--expect', plan.planHash]);+ expect(doc.fix.next).toBe('ask_user');+ expect(doc.preview.argv).toEqual(['gbrain', 'migrate', '--to', 'supabase', '--url-env', 'GBRAIN_TARGET_URL', '--plan', '--json']);+ expect(doc.user_message).toContain('db.acme-example.test');+ expect(doc.what_moves.length).toBeGreaterThan(0);+ expect(doc.what_stays.join(' ')).toContain('graduated');+ expect(r.api.calls.map(c => c.fn)).toEqual(['plan']);+ expect(r.api.calls[0]!.opts).toMatchObject({ to: 'supabase', urlEnv: 'GBRAIN_TARGET_URL', drainTimeoutMs: 60_000, yes: false });+ expect(r.stdout + r.stderr).not.toContain('s3cret-pw');+ });++ test('--yes without --expect re-plans and refuses with the fresh hash; --expect alone on a changed plan is preview_changed', async () => {+ const yes = await run(['--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--yes', '--json']);+ expect(yes.code).toBe(3);+ expect(JSON.parse(yes.stdout).fix.argv).toContain(plan.planHash);+ const stale = await run(['--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--expect', 'ph_stale', '--json']);+ expect(stale.code).toBe(1);+ expect(JSON.parse(stale.stdout).code).toBe('preview_changed');+ });++ test('--force and escape hatches are echoed into the approved command', async () => {+ const r = await run(['--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--force', '--batch-size', '200', '--json']);+ expect(r.code).toBe(3);+ expect(JSON.parse(r.stdout).fix.argv).toEqual(['gbrain', 'migrate', '--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--batch-size', '200', '--force', '--yes', '--expect', plan.planHash]);+ });++ test('--plan: exit 0, one document with the plan and the next command', async () => {+ const r = await run(['--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--plan', '--json']);+ expect(r.code).toBe(0);+ const doc = JSON.parse(r.stdout);+ expect(doc).toMatchObject({ schema_version: 1, status: 'plan', plan: { planHash: plan.planHash } });+ expect(doc.next.command).toBe(`gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --yes --expect ${plan.planHash}`);+ });++ test('the approved run: receipt, retained copy, doctor, mcp expose, credentials and MCP restart notes', async () => {+ const r = await run(['--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--yes', '--expect', plan.planHash, '--json']);+ expect(r.code).toBe(0);+ const doc = JSON.parse(r.stdout);+ expect(doc.status).toBe('graduated');+ expect(doc.next_steps[0].argv).toEqual(['gbrain', 'mcp', 'expose']);+ expect(doc.credentials).toContain('stay valid');+ expect(doc.mcp_client_restart).toContain('restart your MCP client');+ expect(r.api.calls.map(c => c.fn)).toEqual(['run']);+ expect(r.api.calls[0]!.opts).toMatchObject({ expectPlanHash: plan.planHash, yes: true });+ const human = await run(['--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--yes', '--expect', plan.planHash]);+ expect(human.stdout).toContain('Target doctor: no failing checks');+ expect(human.stdout).toContain('gbrain mcp expose');+ });++ test('--url - reads the URL from stdin and passes it only to the orchestrator', async () => {+ const r = await run(['--to', 'postgres', '--url', '-', '--plan', '--json'], fakeApi(), { stdin: `${SECRET_URL}\n` });+ expect(r.code).toBe(0);+ expect(r.api.calls[0]!.opts!.url).toBe(SECRET_URL);+ expect(r.stdout + r.stderr).not.toContain('s3cret-pw');+ });++ test('--url-env naming an unset variable is a usage error (exit 2)', async () => {+ const r = await run(['--to', 'postgres', '--url-env', 'NOPE_URL', '--plan', '--json'], fakeApi(), { env: {} });+ expect(r.code).toBe(2);+ expect(JSON.parse(r.stdout).code).toBe('invalid_params');+ });++ test('run-scoped verbs need no target flags', async () => {+ const status = await run(['--status', '--json']);+ expect(status.code).toBe(0);+ expect(JSON.parse(status.stdout)).toMatchObject({ state: 'copying', runId: 'run-1' });+ expect((await run(['--resume', '--json'])).api.calls.map(c => c.fn)).toEqual(['resume']);+ const rb = await run(['--rollback-to-source', '--json']);+ expect(JSON.parse(rb.stdout)).toMatchObject({ status: 'abandoned' });+ });++ test('exit-code map: drain timeout 11 (blocked 1), in progress 75, SIGINT 130, refusal 1', async () => {+ const drain = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw drainTimeoutError({ timeoutSec: 60, blockers: [{ kind: 'request', id: 'r', detail: 'running', needsUser: false }] }); } }));+ expect(drain.code).toBe(11);+ expect(JSON.parse(drain.stdout).resume_command).toEqual(['gbrain', 'migrate', '--resume', '--drain-timeout', '120']);+ const blocked = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw drainTimeoutError({ timeoutSec: 60, blockers: [{ kind: 'writer_admin_lock', id: 'l', detail: 'locked', argv: ['gbrain', 'sources', 'writer', 'unlock'], needsUser: true }] }); } }));+ expect(blocked.code).toBe(1);- const orchestratorBlocked = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw drainRefusal([{ kind: 'dangling_reference', id: 'oauth_clients.c1', detail: 'bound to a missing source', argv: ['gbrain', 'auth', 'revoke-client', 'c1'], needsUser: true }], 60_000); } }));++ const orchestratorBlocked = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw drainTimeoutError({ blockers: [{ kind: 'dangling_reference', id: 'oauth_clients.c1', detail: 'bound to a missing source', argv: ['gbrain', 'auth', 'revoke-client', 'c1'], needsUser: true }], timeoutSec: 60 }); } }));+ expect(orchestratorBlocked.code).toBe(1);- const orchestratorProgressing = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw drainRefusal([{ kind: 'request', id: 'r', detail: 'running', needsUser: false }], 60_000); } }));++ const orchestratorProgressing = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw drainTimeoutError({ blockers: [{ kind: 'request', id: 'r', detail: 'running', needsUser: false }], timeoutSec: 60 }); } }));+ expect(orchestratorProgressing.code).toBe(11);+ const busy = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw inProgressError({ pid: 9 }); } }));+ expect(busy.code).toBe(75);+ const ctrl = new AbortController();+ const sigint = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { ctrl.abort(); throw new Error('stopped at batch boundary'); } }), { signal: ctrl.signal });+ expect(sigint.code).toBe(130);+ expect(JSON.parse(sigint.stdout)).toMatchObject({ code: 'interrupted', resume_command: ['gbrain', 'migrate', '--resume'] });+ const refused = await run(['--resume', '--json'], fakeApi({ resumeGraduation: async () => { throw opError('graduation_target_not_empty', 'not empty', 'pick another'); } }));+ expect(refused.code).toBe(1);+ });++ test('migrate.graduation=false refuses the plan instead of silently running the legacy copier', async () => {+ const optedOut = mkdtempSync(join(tmpdir(), 'gbrain-grad-optout-'));+ mkdirSync(join(optedOut, '.gbrain'));+ writeFileSync(join(optedOut, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', migrate: { graduation: false } }));+ try {+ const code = await withEnv({ GBRAIN_HOME: optedOut }, () => runMigrateGraduation(['--to', 'postgres', '--plan', '--json'],+ { api: fakeApi(), env: {}, out: () => {}, err: () => {}, progress: silentProgress, signal: new AbortController().signal }));+ expect(code).toBe(2);+ } finally {+ rmSync(optedOut, { recursive: true, force: true });+ }+ });+ });