Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
graduation(G3): migrate graduation CLI (pre-connect route, plan/consent/run/status/resume/rollback, exit map), error builders + registry rows, serve start/handoff/identity guard, doctor graduation findings, engine status block
garrytan6f464433908e
diff --git a/src/cli.ts b/src/cli.tsindex ad39bb129f..56e047d5f4 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2062,6 +2062,14 @@ async function routeEngineFreeSubcommands(command: string, args: string[]): Promconst { tryRunConfigEngineFree } = await import('./commands/config.ts');if (await tryRunConfigEngineFree(args)) return true;}+ // Engine graduation (PGLite -> Postgres) owns its connections: --plan and+ // --status migrate neither schema, and the run holds the source's kernel+ // lock itself. Everything else (`migrate embeddings`, `--to pglite`, the+ // migrate.graduation=false opt-out) falls through to the post-connect record.+ if (command === 'migrate') {+ const { tryRunMigrateGraduation } = await import('./commands/migrate-graduation.ts');+ if (await tryRunMigrateGraduation(args)) return true;+ }if (command === 'mcp') {const { runMcp, mcpNeedsEngine } = await import('./commands/mcp.ts');if (!mcpNeedsEngine(args)) { await runMcp(args); return true; }@@ -2570,6 +2578,12 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Brlet engine: BrainEngine;// F4: a stdio serve with no brain / a missing or repair-failed brain / unreadable config// completes the MCP handshake in status-only mode instead of exiting (connectEngine exits).+ // Engine graduation (§6.4): a serve (re)launched while a run owns the host brain exits 75 with graduation_in_progress.+ if (command === 'serve' && (dbMarkerBrainId() ?? 'host') === 'host') {+ const guard = await import('./core/persistence/graduation-serve-guard.ts');+ const running = guard.serveGraduationStartRefusal();+ if (running) process.exit(guard.writeServeGraduationEnvelope(running));+ }const serveStatus = command === 'serve' ? await import('./commands/serve-status.ts') : null;const serveStatusEligible = !!serveStatus?.statusModeEligible(args, (dbMarkerBrainId() ?? 'host') === 'host');const preConnectReason = serveStatusEligible ? serveStatus!.preConnectStatusReason() : null;@@ -2629,6 +2643,8 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Brconsole.error(`${formatDbMarker(d)}\n${d.message}\n${d.remediation} Run: gbrain db-repair`);} catch { /* marker is best-effort; degraded serve still starts */ }const { createDegradedEngine } = await import('./core/degraded-engine.ts');+ const { engineIdentity, exitOnEngineIdentityChange } = await import('./core/persistence/graduation-serve-guard.ts');+ const startIdentity = engineIdentity();const degraded = createDegradedEngine({initialError: serveConnectError,// Guarded reconnect: connectEngine's no-config path calls@@ -2638,6 +2654,7 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Br// through connectMountEngine before loadConfig() and needs no host// config, so the guard must not brick a mount serve's recovery.reconnect: async () => {+ if ((dbMarkerBrainId() ?? 'host') === 'host') exitOnEngineIdentityChange(startIdentity);if ((dbMarkerBrainId() ?? 'host') === 'host' && !loadConfig()) {throw new Error('No brain configured (config.json missing or unreadable). Run: gbrain init');}@@ -2960,7 +2977,7 @@ SETUPengine status [--json] [--probe] Which engine + URL source, engine-freedb-repair [--yes] [--json] Diagnose/fix Postgres access, engine-free(--yes --apply-rewrites for config rewrites)- migrate --to <supabase|pglite> Transfer brain between engines+ migrate --to <postgres|pglite> Move the brain between engines (PGLite -> Postgres graduates: plan, then --yes --expect)migrate embeddings --to <p:model> Re-embed onto another embedding providerembeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)upgrade Self-updatediff --git a/src/cli/commands/migrate.ts b/src/cli/commands/migrate.tsindex 9d6821cd49..254a6cbdf4 100644--- a/src/cli/commands/migrate.ts+++ b/src/cli/commands/migrate.ts@@ -10,18 +10,25 @@ import type { BrainEngine } from '../../core/engine.ts';export async function run(engine: BrainEngine, args: string[]): Promise<void> {// #3390: `gbrain migrate embeddings --to <provider:model>` — the// provider-agnostic embedding migration. Everything else stays the- // engine-transfer path (`migrate --to <supabase|pglite>`).+ // engine-transfer path (`migrate --to <postgres|supabase|pglite>`; PGLite -> Postgres+ // graduation is routed before connect in src/cli.ts).if (args[0] === 'embeddings') {const { runMigrateEmbeddings } = await import('../../commands/migrate-embeddings.ts');await runMigrateEmbeddings(engine, args.slice(1));return;}if (args.includes('--help') || args.includes('-h')) {- console.log('Usage: gbrain migrate --to <supabase|pglite> [--url <url>] [--path <path>] [--force]');+ const { GRADUATION_USAGE } = await import('../../commands/migrate-graduation.ts');+ console.log(GRADUATION_USAGE);+ console.log(' gbrain migrate --to pglite [--path <path>] [--force]');console.log(' gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes]');console.log('');- console.log('The first form transfers the brain between engines; the second re-embeds');- console.log('onto a different embedding provider (run `gbrain migrate embeddings --help`).');+ console.log('PGLite -> Postgres graduates the brain: without --yes it prints the plan and exits 3;');+ console.log('the run (--yes --expect <plan_hash>) copies every table, verifies it, and only then');+ console.log('switches engines. --to supabase is an alias of --to postgres. Postgres -> PGLite uses');+ console.log('the legacy copier. `gbrain config set migrate.graduation false` opts out of graduation.');+ console.log('Guide: docs/guides/move-to-postgres.md. The last form re-embeds onto a different');+ console.log('embedding provider (run `gbrain migrate embeddings --help`).');return;}const { runMigrateEngine } = await import('../../commands/migrate-engine.ts');diff --git a/src/commands/config.ts b/src/commands/config.tsindex c761e7aaa1..18034d4767 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -63,6 +63,8 @@ const FILE_PLANE_DOTTED_KEYS: ReadonlySet<string> = new Set(['mcp.instructions',// #5232: the CLI resolves its write wait before choosing a transport, engine-free.'persistence.write_wait_ms',+ // Engine graduation opt-out: the pre-connect migrate router reads it engine-free.+ 'migrate.graduation',]);/** #5489: every self_upgrade.* reader (cli.ts startup check, autopilot,@@ -104,7 +106,7 @@ async function unsetFilePlaneKey(key: string): Promise<boolean> {const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');const cfg = loadConfigFileOnly();const dot = key.indexOf('.');- const top = key.slice(0, dot) as 'push' | 'hooks' | 'backup' | 'mcp' | 'self_upgrade' | 'persistence';+ const top = key.slice(0, dot) as 'push' | 'hooks' | 'backup' | 'mcp' | 'self_upgrade' | 'persistence' | 'migrate';const leaf = key.slice(dot + 1);const branch = cfg?.[top] as Record<string, unknown> | undefined;if (!cfg || !branch || !(leaf in branch)) return false;@@ -241,6 +243,7 @@ export async function handleDbPlaneRoutedKeys(key: string, value: string): Promiprocess.exit(1);}const priorEngine = cfg.engine;+ const priorPath = typeof cfg.database_path === 'string' ? cfg.database_path : null;if (key === 'database_url') {cfg.database_url = value;cfg.engine = 'postgres';@@ -252,7 +255,12 @@ export async function handleDbPlaneRoutedKeys(key: string, value: string): Promi}saveConfig(cfg);console.log(`Set ${key} = ${redactConfigValue(key, value)} (file plane: ~/.gbrain/config.json; engine inferred: ${cfg.engine})`);- if (priorEngine && priorEngine !== cfg.engine) {+ const { gbrainPath } = await import('../core/config.ts');+ const { inspectGraduationPath } = await import('../core/persistence/graduation-custody.ts');+ const graduated = priorEngine === 'pglite' && key === 'database_url' && inspectGraduationPath(priorPath ?? gbrainPath('brain.pglite')).state === 'graduated';+ if (graduated) {+ console.error('[config] note: this brain was moved to Postgres by engine graduation; this config now points at it. Restart any MCP client that runs gbrain serve from this config.');+ } else if (priorEngine && priorEngine !== cfg.engine) {// Pointing at the other engine's plane is a legitimate re-point, but it// does NOT move data — say so, or the flip reads as a lossless switch.console.error(@@ -433,6 +441,12 @@ async function setFilePlaneKey(key: string, value: string, tail: string[]): Promconsole.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);} else if (key === 'persistence.write_wait_ms') {await setFileWriteWait(cfg, value, saveConfig);+ } else if (key === 'migrate.graduation') {+ const on = isConfigTruthy(value);+ cfg.migrate = { ...(cfg.migrate ?? {}), graduation: on };+ saveConfig(cfg);+ console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);+ if (!on) console.log('PGLite -> Postgres moves now use the legacy copier, which refuses brains with write history. Turn graduation back on: gbrain config unset migrate.graduation');} else if (key === 'backup.check_interval_days') {const n = Number.parseInt(value, 10);if (!Number.isFinite(n) || n < 1) {diff --git a/src/commands/doctor/checks/engine-fit.ts b/src/commands/doctor/checks/engine-fit.tsindex ca13e9fa7e..7fe50c58c7 100644--- a/src/commands/doctor/checks/engine-fit.ts+++ b/src/commands/doctor/checks/engine-fit.ts@@ -10,8 +10,9 @@* the SAME reason for the SAME brain_id count (diagnose/refused rows and* cross-brain rows never sum toward one threshold).*- * Both remediations are guidance text, never a hardcoded run_command —- * `gbrain migrate --to supabase` needs a --url only the operator has.+ * pglite_scale's fix is the read-only graduation plan (`gbrain migrate --to+ * postgres --plan --json`, which proposes a target when none is given) and+ * names the stay-on-PGLite alternative, `gbrain mcp expose`.*/import type { BrainEngine } from '../../../core/engine.ts';@@ -21,6 +22,9 @@ import { readReceipts } from '../../../core/db-repair-receipts.ts';/** Pages-only, warn-only (CEO-review E2 pinned semantics). */export const PGLITE_SCALE_PAGE_THRESHOLD = 1000;+/** The read-only graduation plan pglite_scale points at. */+export const PGLITE_SCALE_PLAN_ARGV = ['gbrain', 'migrate', '--to', 'postgres', '--plan', '--json'];+export async function pgliteScaleCheck(engine: BrainEngine): Promise<Check | null> {if (engine.kind !== 'pglite') return null;try {@@ -32,7 +36,13 @@ export async function pgliteScaleCheck(engine: BrainEngine): Promise<Check | nulmessage:`PGLite brain has ${stats.page_count} pages (threshold ${PGLITE_SCALE_PAGE_THRESHOLD}). ` +`Postgres gives faster search and concurrent access at this size. ` +- `Move when ready: gbrain migrate --to supabase --url <postgres-conn> (the postgres-adopt skill walks it).`,+ `Preview the move (read-only): gbrain migrate --to postgres --plan --json; or stay on PGLite and share it with other machines: gbrain mcp expose.`,+ fix: {+ argv: PGLITE_SCALE_PLAN_ARGV, consent: [], actor: 'agent', requires_exclusive: false,+ verify: { argv: ['gbrain', 'doctor', '--only', 'pglite_scale', '--json'] }, docs: 'docs/guides/move-to-postgres.md',+ why: `At ${stats.page_count} pages Postgres searches faster and serves several machines at once. The plan is read-only: it lists what moves, what stays, the blockers and the exact run command (export the user's Postgres URL as GBRAIN_TARGET_URL and add --url-env GBRAIN_TARGET_URL; without one it proposes a target). Staying on PGLite is fine too: \`gbrain mcp expose\` shares this brain without moving it.`,+ user_message: `Your brain has ${stats.page_count} pages, the size where Postgres gets faster and lets several machines share it. Should I preview a move to Postgres (nothing changes yet), or keep it on this computer and share it over MCP with gbrain mcp expose?`,+ },};}return { name: 'pglite_scale', status: 'ok', message: `PGLite at ${stats.page_count} pages — comfortable below the ${PGLITE_SCALE_PAGE_THRESHOLD}-page threshold` };diff --git a/src/commands/doctor/checks/engine-graduation.ts b/src/commands/doctor/checks/engine-graduation.tsnew file mode 100644index 0000000000..bb913148dc--- /dev/null+++ b/src/commands/doctor/checks/engine-graduation.ts@@ -0,0 +1,42 @@+/**+ * Engine graduation doctor findings (filesystem only: the manifest, the+ * intent marker and the tombstone; never a lock attempt, never a connect).+ *+ * - graduation_interrupted (fail): a manifest or intent marker is in a+ * non-terminal state and no live run owns it (or a stray brain sits at+ * the graduated path). Fix: `gbrain migrate --resume`, rollback named.+ * The run named by GBRAIN_GRADUATION_RUN (the verify step's own doctor+ * child) is exempt.+ * - A live run reports `ok` with its PID; a brain that never graduated+ * emits nothing.+ *+ * The retained `.graduated-*` copy is reported by pglite_leftovers.+ */+import type { Check } from '../../doctor.ts';+import { inspectGraduationPath } from '../../../core/persistence/graduation-custody.ts';+import { interruptedError, splitBrainError } from '../../../core/persistence/graduation-errors.ts';+import {+ TERMINAL_MANIFEST_STATES, hostPgliteDataDir, readGraduationManifestSummary, type GraduationManifestSummary,+} from '../../../core/persistence/graduation-serve-guard.ts';+import type { GraduationPathState } from '../../../core/persistence/engine-graduation.types.ts';++export function graduationStateCheck(opts: { env?: NodeJS.ProcessEnv; home?: string; manifest?: GraduationManifestSummary | null; path?: GraduationPathState | null } = {}): Check | null {+ const env = opts.env ?? process.env;+ const manifest = opts.manifest !== undefined ? opts.manifest : readGraduationManifestSummary(opts.home);+ const dataDir = manifest?.dataDir ?? hostPgliteDataDir();+ const path = opts.path !== undefined ? opts.path : dataDir ? inspectGraduationPath(dataDir) : null;+ const runId = manifest?.runId ?? path?.marker?.runId;+ const state = manifest?.state ?? path?.marker?.state;+ if (!runId || !state) return null;+ if (env.GBRAIN_GRADUATION_RUN && env.GBRAIN_GRADUATION_RUN === runId) return null;+ if (path?.state === 'in_progress') {+ return { name: 'graduation_interrupted', status: 'ok', message: `Engine graduation ${runId} is running (PID ${path.marker?.pid}, ${state}).`, details: { run_id: runId, state, live: true } };+ }+ if (path?.state === 'split_brain') {+ const e = splitBrainError({ sourcePath: path.dataDir, strayPath: path.dataDir });+ return { name: 'graduation_interrupted', status: 'fail', message: e.message, fix: e.fix, details: { run_id: runId, state, split_brain: true } };+ }+ if (TERMINAL_MANIFEST_STATES.has(state) && path?.state !== 'interrupted') return null;+ const e = interruptedError({ runId, state, ...(dataDir ? { dataDir } : {}) });+ return { name: 'graduation_interrupted', status: 'fail', message: `${e.message} ${e.why}`, fix: e.fix, details: { run_id: runId, state, live: false } };+}diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.tsindex 4f7116055c..9a782cab99 100644--- a/src/commands/doctor/checks/local-audits.ts+++ b/src/commands/doctor/checks/local-audits.ts@@ -433,28 +433,50 @@ async function runHomeDirInWorktree(ctx: DoctorContext): Promise<Check[]> {const durableEngine = (JSON.parse(readFileSync(join(gbrainPath(), 'config.json'), 'utf8')) as { engine?: unknown }).engine;- const { assessPgliteLeftovers } = await import('../../../core/pglite-leftovers-check.ts');+ const { assessPgliteLeftovers, SIZE_WALK_MAX_ENTRIES } = await import('../../../core/pglite-leftovers-check.ts');+ const { readGraduationManifestSummary, TERMINAL_MANIFEST_STATES } = await import('../../../core/persistence/graduation-serve-guard.ts');+ const manifest = readGraduationManifestSummary();const leftovers = assessPgliteLeftovers(typeof durableEngine === 'string' ? durableEngine : undefined,gbrainPath(),+ SIZE_WALK_MAX_ENTRIES,+ manifest ? { inFlight: !TERMINAL_MANIFEST_STATES.has(manifest.state), retainedPath: `${manifest.dataDir}.graduated-${manifest.runId}` } : null,);if (leftovers.status !== 'skip') {+ const copy = leftovers.retained?.[0];checks.push({name: 'pglite_leftovers',status: leftovers.status,message: leftovers.message,+ ...(copy ? {+ details: { retained: leftovers.retained },+ fix: {+ argv: ['rm', '-rf', copy.path], consent: ['destructive'], actor: 'agent', requires_exclusive: false,+ verify: { argv: ['gbrain', 'doctor', '--only', 'pglite_leftovers', '--json'] }, docs: 'docs/guides/move-to-postgres.md#after-the-move',+ why: `${copy.path} is the PGLite brain engine graduation moved to Postgres; it still holds private memory and token hashes. Deleting it frees the disk and ends the option to roll back.`,+ user_message: `After moving your brain to Postgres, gbrain kept the old local copy at ${copy.path}. It still contains your private memory and access-token hashes. Should I delete it? You could then no longer roll back to it.`,+ },+ } : {}),});}} catch {// Best-effort filesystem-hygiene check; never block doctor (a missing/// unparseable config.json lands here and skips, same fail-open posture).}+ // Engine graduation state (filesystem only; src/commands/doctor/checks/engine-graduation.ts).+ try {+ const { graduationStateCheck } = await import('./engine-graduation.ts');+ const graduation = graduationStateCheck();+ if (graduation) checks.push(graduation);+ } catch {+ // Best-effort: a malformed manifest or marker never blocks doctor.+ }return checks;}export const homeDirInWorktreeEntry: DoctorEntry = {name: 'home_dir_in_worktree',- emits: ['home_dir_in_worktree', 'npm_squat', 'pglite_leftovers'],+ emits: ['home_dir_in_worktree', 'npm_squat', 'pglite_leftovers', 'graduation_interrupted'],run: runHomeDirInWorktree,};diff --git a/src/commands/engine-status.ts b/src/commands/engine-status.tsindex f532b7b165..9e4297eac6 100644--- a/src/commands/engine-status.ts+++ b/src/commands/engine-status.ts@@ -17,6 +17,9 @@* note) instead of hanging ~30s on the lock and misreporting a broken brain.*/+import { inspectGraduationPath } from '../core/persistence/graduation-custody.ts';+import { readGraduationManifestSummary } from '../core/persistence/graduation-serve-guard.ts';+import type { GraduationPathState } from '../core/persistence/engine-graduation.types.ts';import { existsSync } from 'node:fs';import {@@ -123,10 +126,41 @@ interface EngineStatusReport {direct_pool_size: number | null;};pglite_lock?: { held: boolean; serve?: boolean; pid?: number; subcommand?: string };+ /** Engine graduation (file reads only): path state, manifest state, marker, tombstone, redacted target. */+ graduation?: GraduationStatusBlock;config_diagnosis?: PgAccessDiagnosis;probe?: ProbeResult;}+interface GraduationStatusBlock {+ state: GraduationPathState['state'];+ data_dir: string;+ run_id: string | null;+ manifest_state: string | null;+ marker: { state: string; pid: number; updated_at: string } | null;+ tombstone: { moved_to: string; graduated_at: string } | null;+ target: string | null;+}++/** Null on a brain that never graduated (no manifest, marker or tombstone). */+function graduationBlock(dataDir: string | null): GraduationStatusBlock | null {+ const manifest = readGraduationManifestSummary();+ const dir = manifest?.dataDir ?? dataDir;+ if (!dir) return null;+ const path = inspectGraduationPath(dir);+ if (!manifest && path.state === 'none' && !path.marker) return null;+ const t = manifest?.target ?? path.tombstone?.target ?? path.marker?.target;+ return {+ state: path.state,+ data_dir: dir,+ run_id: manifest?.runId ?? path.marker?.runId ?? path.tombstone?.runId ?? null,+ manifest_state: manifest?.state ?? null,+ marker: path.marker ? { state: path.marker.state, pid: path.marker.pid, updated_at: path.marker.updatedAt } : null,+ tombstone: path.tombstone ? { moved_to: path.tombstone.movedTo, graduated_at: path.tombstone.graduatedAt } : null,+ target: path.tombstone?.targetDisplayUrl ?? (t ? `postgresql://${t.host}:${t.port}/${t.database}` : null),+ };+}+function fileEngine(fileCfg: GBrainConfig | null): 'postgres' | 'pglite' | null {if (!fileCfg) return null;if (fileCfg.engine) return fileCfg.engine;@@ -298,6 +332,8 @@ export async function runEngineStatus(args: string[]): Promise<number> {const lock = inspectLockHolder(dataDir ?? undefined);report.pglite_lock = { held: lock.held, serve: lock.serve, pid: lock.pid, subcommand: lock.subcommand };}+ const graduation = graduationBlock(cfg?.engine === 'pglite' ? dataDir : null);+ if (graduation) report.graduation = graduation;if (!cfg && !thin) {report.config_diagnosis = diagnoseDbConfig({ source, envShadowed: shadowed, brainId }) ?? undefined;@@ -357,6 +393,9 @@ function printHuman(r: EngineStatusReport): void {if (r.pglite_lock?.held) {lines.push(`Lock: held by live ${r.pglite_lock.serve ? 'serve' : r.pglite_lock.subcommand ?? 'process'} (pid ${r.pglite_lock.pid ?? '?'})`);}+ if (r.graduation) {+ lines.push(`Graduation: ${r.graduation.state}${r.graduation.manifest_state ? ` (run ${r.graduation.run_id}, ${r.graduation.manifest_state})` : ''}${r.graduation.target ? ` -> ${r.graduation.target}` : ''}`);+ }if (r.config_diagnosis) {lines.push(`Status: ${r.config_diagnosis.reason} — ${r.config_diagnosis.remediation}`);}diff --git a/src/commands/init-prefer-postgres.ts b/src/commands/init-prefer-postgres.tsindex 556b5c5a5c..9fe48efa5a 100644--- a/src/commands/init-prefer-postgres.ts+++ b/src/commands/init-prefer-postgres.ts@@ -170,7 +170,7 @@ export async function runPreferPostgresLadder(o: PreferPostgresOpts): Promise<vo'[prefer-postgres] a brain is already configured — refusing to re-run the ladder over it.\n' +' Inspect: gbrain engine status --probe\n' +' Access broken? gbrain db-repair\n' +- ' Move PGLite → PG: gbrain migrate --to supabase --url <conn> (the postgres-adopt skill walks it)\n' ++ ' Move PGLite → PG: gbrain migrate --to postgres --url-env GBRAIN_TARGET_URL --plan (the postgres-adopt skill walks it)\n' +' Really start over: gbrain init --url <conn> (explicit target, no ladder)',);process.exit(1);@@ -387,7 +387,7 @@ export async function runPreferPostgresLadder(o: PreferPostgresOpts): Promise<vo// Rung 5 — PGLite, the zero-config floor. Terminal; no silent anything.if (!rung) {- note('falling back to PGLite. Upgrade later: gbrain migrate --to supabase --url <postgres-conn> (docs/ENGINES.md; the postgres-adopt skill walks it).');+ note('falling back to PGLite. Upgrade later: gbrain migrate --to postgres --plan (docs/guides/move-to-postgres.md; the postgres-adopt skill walks it).');await withStdoutToStderr(o.jsonOutput, () => initPGLite({jsonOutput: false,apiKey: o.apiKey ?? undefined,diff --git a/src/commands/init.ts b/src/commands/init.tsindex d5450e8916..2714861039 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -1333,7 +1333,7 @@ function printMemoryVerbsQuickstart(opts: { emptyBrain?: boolean; onPglite?: booconsole.log('More: ' +(opts.emptyBrain ? 'bulk-load notes `gbrain import <dir>` · ' : '') +- (opts.onPglite ? 'scale up `gbrain migrate --to supabase` · ' : '') ++ (opts.onPglite ? 'scale up `gbrain migrate --to postgres --plan` · ' : '') +'health `gbrain doctor`',);}diff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.tsindex 1166d64828..b723a7cf50 100644--- a/src/commands/migrate-engine.ts+++ b/src/commands/migrate-engine.ts@@ -3,7 +3,7 @@ import { assertLegacyEngineMigration, assertUnmanagedCanonicalWriter } from '../* Engine migration: transfer brain data between PGLite and Postgres.** Usage:- * gbrain migrate --to supabase [--url <connection_string>]+ * gbrain migrate --to supabase [--url <connection_string>] (PGLite -> Postgres: graduation, src/commands/migrate-graduation.ts)* gbrain migrate --to pglite [--path <db_path>]* gbrain migrate --to <engine> --force (overwrite non-empty target)*/@@ -826,8 +826,31 @@ export async function quiesceAutopilot(engine?: BrainEngine): Promise<(() => voireturn resume;}+/**+ * PGLite -> Postgres reaches this legacy copier only when graduation is not+ * routed (src/commands/migrate-graduation.ts routesToGraduation): opted out+ * with migrate.graduation=false, or Windows. On Windows a brain with write+ * history gets graduation's platform refusal; a history-free brain copies here.+ */+async function assertWindowsGraduationPlatform(sourceEngine: BrainEngine, opts: MigrateOpts, platform: NodeJS.Platform = process.platform): Promise<void> {+ if (platform !== 'win32' || sourceEngine.kind !== 'pglite' || opts.targetEngine !== 'postgres') return;+ const { graduationOptedOut } = await import('./migrate-graduation.ts');+ if (graduationOptedOut(loadConfig())) return;+ const tables = ['persistence_requests', 'fact_withdrawals', 'persistence_worktrees'];+ const present = await sourceEngine.executeRaw<{ name: string }>(+ `SELECT table_name AS name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = ANY($1::text[])`, [tables]);+ for (const { name } of present) {+ const [row] = await sourceEngine.executeRaw<{ present: boolean }>(`SELECT EXISTS(SELECT 1 FROM ${name}) AS present`);+ if (row?.present) {+ const { unsupportedPlatformError } = await import('../core/persistence/graduation-errors.ts');+ throw unsupportedPlatformError({ platform: 'Windows' });+ }+ }+}+export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]): Promise<void> {const opts = parseArgs(args);+ await assertWindowsGraduationPlatform(sourceEngine, opts);await assertUnmanagedCanonicalWriter(sourceEngine, 'engine migration');await assertLegacyEngineMigration(sourceEngine);const config = loadConfig();diff --git a/src/commands/migrate-graduation.ts b/src/commands/migrate-graduation.tsnew file mode 100644index 0000000000..1a2772df6c--- /dev/null+++ b/src/commands/migrate-graduation.ts@@ -0,0 +1,424 @@+/**+ * `gbrain migrate` engine graduation (PGLite -> Postgres): the CLI over the+ * orchestrator in src/core/persistence/engine-graduation.ts.+ *+ * Dispatched before connectEngine() (src/cli.ts routeEngineFreeSubcommands):+ * the orchestrator owns both connections, so `--plan` and `--status` migrate+ * neither schema, and the run holds the source's kernel lock itself.+ *+ * gbrain migrate --to postgres|supabase [--url <url> | --url - | --url-env <VAR>]+ * (no --yes) the plan as a confirmation_required payload, exit 3+ * --plan | --dry-run the read-only plan, exit 0+ * --yes --expect <hash> the run; ends with the target doctor result+ * gbrain migrate --status | --resume | --rollback-to-source (the run in the manifest)+ *+ * Exit codes: 0 graduated / plan shown; 3 confirmation_required; 1 refusals;+ * 2 usage; 11 resumable drain stop; 75 graduation_in_progress; 130 SIGINT.+ * `--json` prints one document on stdout; progress goes to stderr.+ */+import { cliRenderContext, shellQuote, type Effect } from '../core/agent-output.ts';+import { buildConsentRefusal, isConsentRefusal, printConsentRefusal, requireConsent, type ConsentRequest } from '../core/consent.ts';+import { loadConfigFileOnly, type GBrainConfig } from '../core/config.ts';+import { cliOptsToProgressOptions, getCliOptions } from '../core/cli-options.ts';+import { setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';+import { readStdinBounded } from '../core/interaction.ts';+import { OperationError, opError } from '../core/ops/contract.ts';+import { createProgress, type ProgressReporter } from '../core/progress.ts';+import type {+ GraduationCommandOptions, GraduationPhase, GraduationPlan, GraduationProgressSink, GraduationReceipt,+ GraduationRollbackResult, GraduationStatusDoc, GraduationTargetSpelling, TriggerBypass,+} from '../core/persistence/engine-graduation.types.ts';+import { DEFAULT_TARGET_URL_ENV, planArgv, resumeArgv, statusArgv } from '../core/persistence/graduation-errors.ts';+import { writeCliError } from '../cli/cli-error.ts';++export type GraduationMode = 'plan' | 'run' | 'status' | 'resume' | 'rollback';++export interface GraduationArgs {+ mode: GraduationMode;+ /** The spelling typed after --to (absent on run-scoped verbs without it). */+ to?: GraduationTargetSpelling;+ url?: string;+ urlFromStdin: boolean;+ urlEnv?: string;+ drainTimeoutSec: number;+ drainTimeoutGiven: boolean;+ triggerBypass?: TriggerBypass;+ batchSize?: number;+ force: boolean;+ yes: boolean;+ expect?: string;+ json: boolean;+}++export const DEFAULT_DRAIN_TIMEOUT_SEC = 60;++/** The orchestrator surface the CLI calls (a test seam; production imports engine-graduation.ts). */+export interface GraduationApi {+ planGraduation(opts: GraduationCommandOptions): Promise<GraduationPlan>;+ runGraduation(opts: GraduationCommandOptions): Promise<GraduationReceipt>;+ graduationStatus(): Promise<GraduationStatusDoc>;+ resumeGraduation(opts: GraduationCommandOptions): Promise<GraduationReceipt>;+ rollbackGraduation(opts: GraduationCommandOptions): Promise<GraduationRollbackResult>;+}++export interface GraduationCliDeps {+ api?: GraduationApi;+ env?: NodeJS.ProcessEnv;+ /** One stdout document / human text. */+ out?: (text: string) => void;+ /** Human status lines (stderr). */+ err?: (text: string) => void;+ progress?: ProgressReporter;+ readStdin?: () => Promise<string | null>;+ /** SIGINT wiring; tests pass their own controller. */+ signal?: AbortSignal;+ /** Error writer (default writeCliError); `legacy` keys join the --json envelope. */+ writeError?: (e: unknown, opts: { json: boolean; legacy?: Record<string, unknown> }) => number;+}++export const GRADUATION_USAGE = [+ 'Usage: gbrain migrate --to postgres|supabase [--url <url> | --url - | --url-env <VAR>] [--plan | --dry-run] [--yes --expect <plan_hash>]',+ ' [--drain-timeout <seconds>] [--trigger-bypass replica|disable-trigger] [--batch-size <n>] [--force] [--json]',+ ' gbrain migrate --status [--json]',+ ' gbrain migrate --resume [--drain-timeout <seconds>] [--url-env <VAR>] [--json]',+ ' gbrain migrate --rollback-to-source [--yes --expect <hash>] [--json]',+].join('\n');++const MODE_FLAGS: ReadonlyArray<[string, GraduationMode]> = [+ ['--plan', 'plan'], ['--dry-run', 'plan'], ['--status', 'status'], ['--resume', 'resume'], ['--rollback-to-source', 'rollback'],+];++function usage(message: string, suggestion = `Run \`gbrain migrate --help\` for the accepted forms.`): OperationError {+ return opError('invalid_params', message, suggestion, {+ fix: { argv: ['gbrain', 'migrate', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'The help lists every graduation flag.' },+ });+}++function flagValue(args: readonly string[], name: string): string | undefined {+ for (let i = 0; i < args.length; i++) {+ if (args[i] === name) {+ const v = args[i + 1];+ if (v === undefined || (v.startsWith('--') && v !== '-')) throw usage(`${name} needs a value.`);+ return v;+ }+ if (args[i]!.startsWith(`${name}=`)) return args[i]!.slice(name.length + 1);+ }+ return undefined;+}++function positiveInt(raw: string | undefined, name: string): number | undefined {+ if (raw === undefined) return undefined;+ if (!/^\d+$/.test(raw) || Number(raw) <= 0 || !Number.isSafeInteger(Number(raw))) throw usage(`${name} must be a positive whole number (got "${raw}").`);+ return Number(raw);+}++export function parseGraduationArgs(args: readonly string[]): GraduationArgs {+ const modes = MODE_FLAGS.filter(([f]) => args.includes(f));+ const distinct = [...new Set(modes.map(([, m]) => m))];+ if (distinct.length > 1) throw usage(`${modes.map(([f]) => f).join(' and ')} cannot be combined; pick one.`);+ const mode: GraduationMode = distinct[0] ?? 'run';+ const toRaw = flagValue(args, '--to');+ if (toRaw !== undefined && toRaw !== 'postgres' && toRaw !== 'supabase') {+ throw usage(`Engine graduation moves a PGLite brain to Postgres; --to ${toRaw} is not a graduation target.`,+ toRaw === 'pglite'+ ? 'A Postgres -> PGLite move uses the legacy copier and has no plan, status, resume or rollback: run `gbrain migrate --to pglite` without them.'+ : 'Use --to postgres (alias supabase).');+ }+ if ((mode === 'plan' || mode === 'run') && toRaw === undefined) throw usage('Name the target engine: --to postgres (alias supabase).');+ const urlRaw = flagValue(args, '--url');+ const urlEnv = flagValue(args, '--url-env');+ if (urlRaw !== undefined && urlEnv !== undefined) throw usage('--url and --url-env cannot be combined; prefer --url-env so the URL never appears in a command line.');+ if (mode === 'status' && (args.includes('--yes') || args.includes('--force'))) throw usage('--status is read-only; it takes no --yes or --force.');+ const bypass = flagValue(args, '--trigger-bypass');+ if (bypass !== undefined && bypass !== 'replica' && bypass !== 'disable-trigger') throw usage(`--trigger-bypass takes replica or disable-trigger (got "${bypass}").`);+ const drain = positiveInt(flagValue(args, '--drain-timeout'), '--drain-timeout');+ return {+ mode,+ ...(toRaw ? { to: toRaw } : {}),+ ...(urlRaw !== undefined && urlRaw !== '-' ? { url: urlRaw } : {}),+ urlFromStdin: urlRaw === '-',+ ...(urlEnv !== undefined ? { urlEnv } : {}),+ drainTimeoutSec: drain ?? DEFAULT_DRAIN_TIMEOUT_SEC,+ drainTimeoutGiven: drain !== undefined,+ ...(bypass ? { triggerBypass: bypass === 'replica' ? 'session_replication_role' : 'disable_trigger' } : {}),+ ...(flagValue(args, '--batch-size') !== undefined ? { batchSize: positiveInt(flagValue(args, '--batch-size'), '--batch-size') } : {}),+ force: args.includes('--force'),+ yes: args.includes('--yes'),+ ...(flagValue(args, '--expect') !== undefined ? { expect: flagValue(args, '--expect') } : {}),+ json: args.includes('--json'),+ };+}++/** `migrate.graduation` (file plane): only an explicit false opts out. */+export function graduationOptedOut(cfg: GBrainConfig | null): boolean {+ const v = (cfg as { migrate?: { graduation?: unknown } } | null)?.migrate?.graduation;+ return v === false || v === 'false' || v === '0' || v === 'off' || v === 'no';+}++/**+ * Whether this `gbrain migrate` invocation is graduation's. Run-scoped verbs+ * and the plan always are; a bare `--to postgres|supabase` is when the+ * durable (file) config is PGLite, graduation is not opted out, and the host+ * is not Windows (history-free Windows brains keep the legacy copier).+ */+export function routesToGraduation(args: readonly string[], fileCfg: GBrainConfig | null, platform: NodeJS.Platform = process.platform): boolean {+ if (args[0] === 'embeddings' || args.includes('--help') || args.includes('-h')) return false;+ if (MODE_FLAGS.some(([f]) => args.includes(f))) return true;+ const toIdx = args.indexOf('--to');+ const to = toIdx >= 0 ? args[toIdx + 1] : args.find(a => a.startsWith('--to='))?.slice(5);+ if (to !== 'postgres' && to !== 'supabase') return false;+ if (!fileCfg || (fileCfg.engine ?? 'pglite') !== 'pglite' || fileCfg.database_url) return false;+ if (graduationOptedOut(fileCfg)) return false;+ return platform !== 'win32';+}++/** What leaves this computer and what stays (the confirmation, success output and guide name both). */+export const WHAT_MOVES: readonly string[] = [+ 'pages, facts, takes, versions, links and timeline', 'embeddings', 'transcripts and paid model caches',+ 'request history, withdrawals and attribution', 'access-token and OAuth rows (hashes only)',+];+export const WHAT_STAYS: readonly string[] = [+ 'file storage object bytes', 'git worktrees and their host bindings', 'the MCP endpoint and OAuth issuer URL',+ 'the retained PGLite copy (<path>.graduated-<run_id>), which still holds private memory and token hashes',+];++const CREDENTIALS_NOTE = 'Existing access tokens, OAuth clients and local writer credentials stay valid on Postgres.';+const MCP_RESTART_NOTE = 'A gbrain serve handed the brain over during the move: restart your MCP client (or its gbrain server entry) so it reconnects to Postgres.';++function spellingOf(a: GraduationArgs): { to: GraduationTargetSpelling; urlEnv: string } {+ return { to: a.to ?? 'postgres', urlEnv: a.urlEnv ?? DEFAULT_TARGET_URL_ENV };+}++/** The escape hatches that enter the plan hash, echoed into every emitted command. */+function hatchArgs(a: GraduationArgs): string[] {+ return [+ ...(a.drainTimeoutGiven ? ['--drain-timeout', String(a.drainTimeoutSec)] : []),+ ...(a.triggerBypass ? ['--trigger-bypass', a.triggerBypass === 'session_replication_role' ? 'replica' : 'disable-trigger'] : []),+ ...(a.batchSize ? ['--batch-size', String(a.batchSize)] : []),+ ...(a.force ? ['--force'] : []),+ ];+}++function progressSink(p: ProgressReporter): { sink: GraduationProgressSink; done: () => void } {+ let phase: ProgressReporter | null = null;+ let table: ProgressReporter | null = null;+ const closeTable = () => { table?.finish(); table = null; };+ const closePhase = () => { closeTable(); phase?.finish(); phase = null; };+ return {+ sink: {+ phase(name: GraduationPhase, total?: number) { closePhase(); phase = p.child(`migrate.graduation.${name}`, total); phase.start(`migrate.graduation.${name}`, total); },+ table(relation: string, rows: number) { closeTable(); table = (phase ?? p).child(`table.${relation}`, rows); table.start(`table.${relation}`, rows); },+ batch(_relation: string, rows: number) { table?.tick(rows); },+ },+ done: closePhase,+ };+}++function displayHost(plan: GraduationPlan): string {+ return plan.routes.main || `${plan.target.host}:${plan.target.port}/${plan.target.database}`;+}++function planLines(plan: GraduationPlan, next: string): string {+ const carry = plan.tables.filter(t => t.class === 'carry' || t.class === 'rebind');+ const rows = carry.reduce((n, t) => n + t.rows, 0);+ const other = (c: string) => plan.tables.filter(t => t.class === c).map(t => t.relation);+ const lines = [+ `Move this PGLite brain to Postgres at ${displayHost(plan)}`,+ ` Source: ${plan.source.dataDir} (brain ${plan.source.brainId})${plan.sourceMeasured === 'at_run_start' ? ' — counts measured at run start (a live serve holds it)' : ''}`,+ ` Carry: ${carry.length} tables, ${rows} rows (keys preserved)`,+ ...(other('rebuild').length ? [` Rebuild: ${other('rebuild').join(', ')}`] : []),+ ...(other('discard').length ? [` Discard: ${other('discard').join(', ')}`] : []),+ ` Triggers: ${plan.triggerBypass ?? 'not probed'}`,+ ` Estimate: ${Math.ceil(plan.estimateSeconds.total)}s (copy ${Math.ceil(plan.estimateSeconds.copy)}s, verify ${Math.ceil(plan.estimateSeconds.verify)}s, doctor ${Math.ceil(plan.estimateSeconds.doctor)}s)`,+ ` Moves: ${WHAT_MOVES.join('; ')}`,+ ` Stays: ${WHAT_STAYS.join('; ')}`,+ ];+ for (const b of plan.blockers) lines.push(` Blocker: ${b.kind} ${b.id}: ${b.detail}${b.argv?.length ? ` — ${shellQuote([...b.argv])}` : ''}`);+ lines.push(` plan_hash ${plan.planHash}`, `Next: ${next}`);+ return `${lines.join('\n')}\n`;+}++function consentRequest(a: GraduationArgs, plan: GraduationPlan, args: readonly string[]): ConsentRequest {+ const s = spellingOf(a);+ const host = displayHost(plan);+ const people = plan.blockers.filter(b => b.needsUser);+ const before = people.length ? ` Before it can run: ${people.map(b => b.detail).join(' ')}` : '';+ const effects: Effect[] = ['egress', 'destructive'];+ return {+ command: 'migrate', effects, actor: 'agent',+ what: 'Moving this brain to Postgres',+ why: `The brain's database (${WHAT_MOVES.join('; ')}) is copied to ${host}, verified table by table, and only then made authoritative; the PGLite data dir is renamed aside and a tombstone takes its place.`,+ risk: `Data leaves this computer for ${host}. Until a rollback, the PGLite copy is read-only history; rolling back after the move drops what changed on Postgres.`,+ user_message: `Move this brain to Postgres at ${host}? That copies ${WHAT_MOVES.join(', ')}. Staying on this computer: ${WHAT_STAYS.join(', ')}.${before}`,+ argv: ['gbrain', 'migrate', '--to', s.to, '--url-env', s.urlEnv, ...hatchArgs(a)],+ preview_argv: planArgv(s, hatchArgs(a)),+ plan_hash: plan.planHash,+ args,+ };+}++function orchestratorOptions(a: GraduationArgs, url: string | undefined, extra: Partial<GraduationCommandOptions>): GraduationCommandOptions {+ return {+ to: a.to ?? 'postgres',+ ...(url !== undefined ? { url } : {}),+ ...(a.urlEnv !== undefined ? { urlEnv: a.urlEnv } : {}),+ drainTimeoutMs: a.drainTimeoutSec * 1000,+ ...(a.triggerBypass ? { triggerBypass: a.triggerBypass } : {}),+ ...(a.batchSize ? { batchSize: a.batchSize } : {}),+ force: a.force,+ yes: a.yes,+ ...(a.expect ? { expectPlanHash: a.expect } : {}),+ ...extra,+ };+}++function successDoc(receipt: GraduationReceipt) {+ return {+ schema_version: 1 as const,+ status: 'graduated' as const,+ run_id: receipt.runId,+ target: receipt.targetDisplayUrl ?? null,+ retained_path: receipt.retainedPath ?? null,+ doctor: receipt.doctor ?? null,+ receipt,+ credentials: CREDENTIALS_NOTE,+ next_steps: [{ argv: ['gbrain', 'mcp', 'expose'], command: 'gbrain mcp expose', why: 'Share this brain with agents on other machines (multi-machine use).' }],+ ...(receipt.serveHandoff ? { mcp_client_restart: MCP_RESTART_NOTE } : {}),+ };+}++function successLines(receipt: GraduationReceipt): string {+ const rows = receipt.tables.reduce((n, t) => n + t.rows, 0);+ const failing = receipt.doctor?.target ?? [];+ const seconds = Object.values(receipt.timings).reduce((n, v) => n + v, 0) / 1000;+ return [+ `Graduated to Postgres${receipt.targetDisplayUrl ? ` at ${receipt.targetDisplayUrl}` : ''} (run ${receipt.runId}${seconds ? `, ${seconds.toFixed(0)}s` : ''}).`,+ ` Copied ${receipt.tables.length} tables, ${rows} rows; verify passed; replay probe: ${receipt.replay.status}.`,+ ` Target doctor: ${failing.length ? `failing checks: ${failing.join(', ')}` : 'no failing checks'}.`,+ ...(receipt.retainedPath ? [` Retained PGLite copy: ${receipt.retainedPath} (still holds private memory and token hashes; deleting it is your call; gbrain doctor reports it).`] : []),+ ` ${CREDENTIALS_NOTE}`,+ ' Next: share this brain with other machines: gbrain mcp expose',+ ...(receipt.serveHandoff ? [` ${MCP_RESTART_NOTE}`] : []),+ ].join('\n') + '\n';+}++function statusLines(doc: GraduationStatusDoc): string {+ if (doc.state === 'none') return 'No engine graduation on record.\n';+ const done = doc.tables.filter(t => t.state === 'copied' || t.state === 'verified').length;+ return [+ `Engine graduation ${doc.runId}: ${doc.state}${doc.liveRun ? ` (running, PID ${doc.liveRun.pid})` : ''}`,+ ...(doc.source ? [` Source: ${doc.source.dataDir} (brain ${doc.source.brainId})`] : []),+ ...(doc.target ? [` Target: ${doc.target.displayUrl} (row ${doc.target.row ?? 'absent'}${doc.target.reachable ? '' : ', unreachable'})`] : []),+ ...(doc.tables.length ? [` Tables: ${done}/${doc.tables.length} copied`] : []),+ ...(doc.splitBrain ?? []).map(p => ` Split brain: ${p.path} (brain ${p.brainId ?? 'unknown'}, ${p.rows} rows, newest write ${p.newestWriteAt ?? 'unknown'})`),+ ...(doc.nextArgv ? [`Next: ${shellQuote([...doc.nextArgv])}`] : []),+ ].join('\n') + '\n';+}++async function resolveUrl(a: GraduationArgs, deps: GraduationCliDeps): Promise<string | undefined> {+ const env = deps.env ?? process.env;+ if (a.urlEnv !== undefined && !env[a.urlEnv]) {+ throw usage(`${a.urlEnv} is not set; --url-env names the environment variable that holds the target URL.`,+ `Export the Postgres connection string as ${a.urlEnv} in this shell, then run the same command again.`);+ }+ if (!a.urlFromStdin) return a.url;+ const text = deps.readStdin ? await deps.readStdin() : await (async () => {+ const r = await readStdinBounded({ maxBytes: 64 * 1024 });+ return r.kind === 'data' ? r.text : null;+ })();+ const url = text?.trim();+ if (!url) throw usage('--url - reads the target URL from stdin, and stdin was empty.', `Pipe the URL in, or export it and use --url-env ${DEFAULT_TARGET_URL_ENV}.`);+ return url;+}++/** Run one graduation invocation; returns the exit code (output already written). */+export async function runMigrateGraduation(args: readonly string[], deps: GraduationCliDeps = {}): Promise<number> {+ const json = args.includes('--json');+ const out = deps.out ?? ((t: string) => { void writeJsonDocument(t.replace(/\n$/, ''), s => { process.stdout.write(`${s}\n`); }); });+ const err = deps.err ?? ((t: string) => { process.stderr.write(t); });+ const emit = (doc: unknown, human: string) => { if (json) out(`${JSON.stringify(doc, null, 2)}\n`); else out(human); };+ const controller = new AbortController();+ const onSigint = () => {+ if (controller.signal.aborted) return;+ err('Interrupt received: stopping at the next batch boundary (the move stays resumable).\n');+ controller.abort();+ };+ const signal = deps.signal ?? controller.signal;+ if (!deps.signal) process.on('SIGINT', onSigint);+ const progress = deps.progress ?? createProgress(cliOptsToProgressOptions(getCliOptions()));+ const { sink, done } = progressSink(progress);+ try {+ const a = parseGraduationArgs(args);+ if ((a.mode === 'plan' || a.mode === 'run') && graduationOptedOut(loadConfigFileOnly())) {+ throw usage('Engine graduation is turned off on this machine (migrate.graduation = false), so there is no plan to show.',+ 'Turn it back on with `gbrain config unset migrate.graduation`, or run the legacy copier with `gbrain migrate --to postgres --url <url>` (it refuses brains with write history).');+ }+ const api = deps.api ?? await import('../core/persistence/engine-graduation.ts');+ if (a.mode === 'status') {+ const doc = await api.graduationStatus();+ emit(doc, statusLines(doc));+ return 0;+ }+ const url = await resolveUrl(a, deps);+ const opts = orchestratorOptions(a, url, { progress: sink, signal });+ if (a.mode === 'plan') {+ const plan = await api.planGraduation(opts);+ const next = shellQuote(['gbrain', 'migrate', '--to', spellingOf(a).to, '--url-env', spellingOf(a).urlEnv, ...hatchArgs(a), '--yes', '--expect', plan.planHash]);+ emit({ schema_version: 1, status: 'plan', plan, what_moves: WHAT_MOVES, what_stays: WHAT_STAYS, next: { command: next } }, planLines(plan, next));+ return 0;+ }+ if (a.mode === 'run' && !(a.yes && a.expect)) {+ const plan = await api.planGraduation(opts);+ const req = consentRequest(a, plan, args);+ try {+ await requireConsent(req, { interactive: false, preapprovals: {} });+ } catch (e) {+ if (!isConsentRefusal(e)) throw e;+ Object.assign(e.consent, { plan, blockers: plan.blockers, what_moves: WHAT_MOVES, what_stays: WHAT_STAYS });+ if (!json) err(planLines(plan, e.consent.fix.command ?? ''));+ return printConsentRefusal(e, { json });+ }+ throw buildConsentRefusal(req, cliRenderContext());+ }+ if (a.mode === 'rollback') {+ const result = await api.rollbackGraduation(opts);+ emit({ schema_version: 1, status: result.state, restored_path: result.restoredPath, dropped: result.dropped },+ `Rolled back: ${result.state === 'abandoned' ? 'the Postgres copy was abandoned; the PGLite brain never stopped being authoritative' : `the PGLite brain at ${result.restoredPath} is authoritative again`}.${result.dropped.length ? ` Dropped operational rows: ${result.dropped.map(d => `${d.relation} (${d.rows})`).join(', ')}.` : ''}\n`);+ return 0;+ }+ const receipt = a.mode === 'resume' ? await api.resumeGraduation(opts) : await api.runGraduation(opts);+ done();+ emit(successDoc(receipt), successLines(receipt));+ return 0;+ } catch (e) {+ done();+ return writeGraduationError(e, signal.aborted, json, deps.writeError ?? ((err, o) => writeCliError(err, 'migrate', o)));+ } finally {+ if (!deps.signal) process.removeListener('SIGINT', onSigint);+ }+}++/** Render a graduation failure; applies the per-reason exit overrides (SIGINT 130, blocked drain 1). */+function writeGraduationError(e: unknown, aborted: boolean, json: boolean,+ write: (e: unknown, opts: { json: boolean; legacy?: Record<string, unknown> }) => number): number {+ if (aborted && !(e instanceof OperationError && e.code === 'interrupted')) {+ const err = opError('interrupted', 'The move stopped at a batch boundary after an interrupt; it is resumable.',+ 'Ask the user whether to continue; `gbrain migrate --resume` picks up where it stopped.',+ { why: 'SIGINT stops the copy between batches and records the checkpoint, so nothing is half-written.',+ fix: { argv: resumeArgv(), consent: [], actor: 'agent', requires_exclusive: true, verify: { argv: statusArgv() },+ why: 'Continues from the recorded checkpoint.', user_message: 'The move to Postgres was paused. Should I continue it?' } });+ return write(err, { json, ...(json ? { legacy: { resume_command: resumeArgv() } } : {}) });+ }+ if (e instanceof OperationError && e.code === 'graduation_drain_timeout') {+ const code = write(e, { json, ...(json ? { legacy: { resume_command: e.fix?.argv ?? resumeArgv() } } : {}) });+ return e.reason === 'blocked' ? 1 : code;+ }+ return write(e, { json });+}++/** Pre-connect route from src/cli.ts: true when graduation handled this invocation. */+export async function tryRunMigrateGraduation(args: string[]): Promise<boolean> {+ if (!routesToGraduation(args, loadConfigFileOnly())) return false;+ setCliExitVerdict(await runMigrateGraduation(args));+ return true;+}diff --git a/src/commands/serve-status.ts b/src/commands/serve-status.tsindex 8e0934468a..e25cf4b947 100644--- a/src/commands/serve-status.ts+++ b/src/commands/serve-status.ts@@ -30,7 +30,7 @@ export function statusModeEligible(args: readonly string[], hostBrain: boolean):export function preConnectStatusReason(): StatusReason | null {if (!loadConfig()) return 'no_brain';const probed = probeStatus();- return probed && (probed.reason === 'missing_brain' || probed.reason === 'repair_failed') ? probed.reason : null;+ return probed && (probed.reason === 'missing_brain' || probed.reason === 'repair_failed' || probed.reason === 'engine_graduated') ? probed.reason : null;}/** Map a connect failure to a status reason; null when status mode does not apply. */@@ -47,10 +47,16 @@ export async function runStatusModeServe(): Promise<void> {const state = initialStatusState(reason);const { createDegradedEngine } = await import('../core/degraded-engine.ts');+ // Engine graduation (§6.4): re-resolve config on each reconnect and exit for relaunch on an engine change.+ const { engineIdentity, exitOnEngineIdentityChange } = await import('../core/persistence/graduation-serve-guard.ts');+ const startIdentity = engineIdentity();const kind = loadConfig()?.engine === 'postgres' ? 'postgres' : 'pglite';const engine = markStatusModeEngine(createDegradedEngine({initialError: initialError ?? new Error(statusHeadline(state)),- reconnect: () => gatedReconnect(state, connect),+ reconnect: () => {+ exitOnEngineIdentityChange(startIdentity, { startedGraduated: state.reason === 'engine_graduated' });+ return gatedReconnect(state, connect);+ },// A PGLite open + pending migrations can take longer than the degraded default.callerWaitMs: 20_000,kind,diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 3dd36fd4b8..3baf51128d 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -8,6 +8,7 @@ import { VERB_NAMES } from '../core/verbs.ts';import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';import { onForwardProgress } from '../core/forward-progress.ts';+import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';import {installLoopStallWatchdog,resolveServeStallWatchdogMs,@@ -66,6 +67,8 @@ const IDLE_SWEEP_INTERVAL_MS = 10 * 60_000;// Small per-run budget for idle sweeps: the serve must snap back to// serving tool calls the moment the client wakes up.const IDLE_SWEEP_BUDGET_MS = 3_000;+/** How often a PGLite stdio serve checks for a graduation run's intent marker (a stat; plan: at most every 2 s). */+const GRADUATION_HANDOFF_POLL_MS = 2_000;export interface ServeOptions {// Test seam — defaults to the live process. The lifecycle plumbing reads@@ -499,6 +502,8 @@ function installStdioLifecycle(let shuttingDown = false;let parentWatchdog: unknown = null;let idleSweepTimer: unknown = null;+ let graduationHandoffTimer: unknown = null;+ let shutdownExitCode = 0;let activateIdleActivityTracking = (): void => {};const beginShutdown = (reason: string): void => {if (shuttingDown) return;@@ -518,6 +523,10 @@ function installStdioLifecycle(deps.clearInterval(idleSweepTimer);idleSweepTimer = null;}+ if (graduationHandoffTimer !== null) {+ deps.clearInterval(graduationHandoffTimer);+ graduationHandoffTimer = null;+ }deps.log(`GBrain MCP server: graceful exit (${reason})`);@@ -567,10 +576,25 @@ function installStdioLifecycle(}).finally(() => {if (deadline) clearTimeout(deadline);- deps.exit(0);+ deps.exit(shutdownExitCode);});};+ // Engine graduation hand-off (§13): a live run's intent marker asks the PGLite+ // serve that holds the brain to finish, release the lock and exit 75 so the+ // run can take the brain; a relaunched serve then exits the same way.+ if (engine.kind === 'pglite') {+ graduationHandoffTimer = deps.setInterval(() => {+ if (shuttingDown || isEngineDegradedForServe(engine)) return;+ const request = graduationHandoffRequested();+ if (!request) return;+ deps.log(`GBrain MCP server: an engine graduation run asked for this brain; handing it over.`);+ shutdownExitCode = writeServeGraduationEnvelope(request, (s) => deps.log(s.trimEnd()));+ drainThenShutdown('graduation-handoff');+ }, GRADUATION_HANDOFF_POLL_MS);+ (graduationHandoffTimer as { unref?: () => void } | null)?.unref?.();+ }+// Signal-based termination. SIGTERM: daemon ask. SIGINT: user Ctrl-C.// SIGHUP: terminal disconnect / daemon-style "reload" channels — Aragorn// observed real-world hosts (Claude Desktop on macOS, hermes-agentdiff --git a/src/commands/storage.ts b/src/commands/storage.tsindex 9bef2726db..166db2aed7 100644--- a/src/commands/storage.ts+++ b/src/commands/storage.ts@@ -146,7 +146,7 @@ function warnIfPGLite(engine: BrainEngine): void {`Note: storage tiering has limited effect on PGLite — pages live in your ` +`local database file regardless of tier. The .gitignore management still ` +`keeps bulk content out of git history. To get full tiering, migrate to ` +- `Postgres with \`gbrain migrate --to supabase\`.`,+ `Postgres with \`gbrain migrate --to postgres --plan\`.`,);}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 742267af39..452add3d8b 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -43,10 +43,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],- 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],+ 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],@@ -65,20 +65,20 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--version', '--yes'],+ 'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--plan', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--url-env', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],- 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],+ 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-migrate', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status', '--to'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],@@ -100,7 +100,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],'repair': ['--all', '--apply', '--brain', '--diff', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--only', '--remediate', '--remediation-plan', '--skip', '--source', '--stale', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],@@ -112,7 +112,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],- 'serve': ['--access', '--apply-rewrites', '--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--fail-fast', '--help', '--http', '--json', '--log-full-params', '--oauth-request', '--operations', '--port', '--prefer-postgres', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--tools-json', '--url', '--yes'],+ 'serve': ['--access', '--apply-rewrites', '--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--harness', '--help', '--http', '--json', '--log-full-params', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--tools-json', '--url', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],@@ -120,9 +120,9 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'smoke-test': ['--brain', '--help', '--json', '--source'],'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],- 'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],+ 'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/config.ts b/src/core/config.tsindex 60c1fb60d9..7ec614e81a 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -71,6 +71,8 @@ export interface GBrainConfig {backup?: { check_enabled?: boolean | string; check_interval_days?: number | string };/** #5232: CLI write wait in ms (file plane; persistence/write-wait.ts). */persistence?: { write_wait_ms?: number | string };+ /** Engine graduation opt-out (`migrate.graduation false` uses the legacy copier); file plane, read pre-connect. */+ migrate?: { graduation?: boolean };/** A4 user preapprovals (file plane only; set by the trusted local CLI; read by core/consent.ts). */consent?: { preapprove?: { paid?: { max_usd_per_run?: number }; persistent_install?: boolean } };database_url?: string;@@ -1646,6 +1648,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes','persistence.receipt_retention_days', 'persistence.unbound_write', // #5254: persistence/unbound-source.ts'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts+ 'migrate.graduation', // file plane, src/commands/migrate-graduation.ts (engine graduation opt-out)'consent.preapprove.paid.max_usd_per_run', 'consent.preapprove.persistent_install', // A4: file plane, core/consent.ts// F4b: PGLite row-delta ANALYZE (src/core/planner-stats.ts); F4a: get_health memo TTL (src/core/health-memo.ts, 0 disables).'planner.auto_analyze', 'planner.first_read_budget_ms', 'import.analyze_every_pages', 'health.cache_ttl_ms',diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex a3d3ec27b3..2e1a5734f2 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -240,6 +240,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['pglite_scale','db_repair_recurrence','pglite_leftovers',+ // Engine graduation (PGLite -> Postgres) interrupted / split brain.+ 'graduation_interrupted','pgvector','postgres_cancellation_driver','plugin_lane_collision',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 1ff419a60e..9c8ac0e2b0 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -124,6 +124,7 @@ export const CODES = {embedding_unavailable: { class: 'unavailable', summary: "The provider returned an incomplete embedding batch." },embedding_unconfigured: { class: 'host_only', summary: "The selected brain has no verifiable text embedding model and dimensions." },embedding_width_mismatch: { class: 'caller', summary: "The embedding model cannot produce the width of the brain's vector column; nothing was changed." },+ engine_graduated: { class: 'caller', summary: "A client opened a PGLite brain that moved to Postgres; its old path holds a tombstone.", docs: 'docs/guides/move-to-postgres.md#graduated-datastore' },export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },extraction_failed: { class: 'server', summary: "The accepted atom extraction produced malformed output." },extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },@@ -141,6 +142,21 @@ export const CODES = {git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },git_unavailable: { class: 'retryable', summary: "A git command did not complete." },+ graduation_drain_timeout: { class: 'retryable', summary: "Queued or running writes did not drain within --drain-timeout; the move stopped before copying and the source is unchanged.", docs: 'docs/guides/move-to-postgres.md#drain', reasons: ['progressing', 'blocked'], exit: 11 },+ graduation_embedding_dimension_mismatch: { class: 'caller', summary: "An existing, non-empty target database has a different embedding column layout than the brain being moved.", docs: 'docs/guides/move-to-postgres.md#embeddings' },+ graduation_foreign_host_binding: { class: 'host_only', summary: "A source's worktree is owned by another host, so this host cannot move it to Postgres.", docs: 'docs/guides/move-to-postgres.md#hosts' },+ graduation_in_progress: { class: 'retryable', summary: "Another process is moving this brain to Postgres; neither engine may be opened until it finishes.", docs: 'docs/guides/move-to-postgres.md#in-progress', exit: 75 },+ graduation_interrupted: { class: 'unavailable', summary: "An engine graduation stopped before it finished and no process owns it.", docs: 'docs/guides/move-to-postgres.md#resume' },+ graduation_rollback_writes_lost: { class: 'consent', summary: "Rolling back to PGLite would drop changes made on Postgres since the move.", docs: 'docs/guides/move-to-postgres.md#rollback', reasons: ['user_data', 'security_changes'] },+ graduation_source_writer_held: { class: 'host_only', summary: "A live serve or daemon holds the PGLite brain and did not hand it over to the move.", docs: 'docs/ENGINES.md#graduation-writer-held' },+ graduation_split_brain: { class: 'unavailable', summary: "A different brain appeared at the graduated brain's old path; the target is withheld from authority until the user decides.", docs: 'docs/guides/move-to-postgres.md#split-brain' },+ graduation_target_auth_failed: { class: 'caller', summary: "The target database rejected the credentials recorded for this move.", docs: 'docs/guides/move-to-postgres.md#credentials' },+ graduation_target_ddl_unreachable: { class: 'unavailable', summary: "The target's direct (schema) connection is unreachable or names a different database than its main URL.", docs: 'docs/guides/move-to-postgres.md#ddl-connection' },+ graduation_target_not_empty: { class: 'caller', summary: "The target database already holds data that is not this move's.", docs: 'docs/guides/move-to-postgres.md#target-not-empty' },+ graduation_target_unsupported: { class: 'caller', summary: "The target database is missing a prerequisite (server version, vector extension with halfvec, CREATE privilege or a matching column).", docs: 'docs/guides/move-to-postgres.md#target-requirements', reasons: ['server_version', 'vector', 'halfvec', 'create_privilege', 'column', 'env_override'] },+ graduation_unclassified_table: { class: 'server', summary: "A database has a relation the graduation inventory does not classify, so moving it could lose data.", docs: 'docs/guides/move-to-postgres.md#inventory', reasons: ['newer_target', 'missing_row'] },+ graduation_unsupported_platform: { class: 'host_only', summary: "Moving a brain with write history to Postgres is not available on this platform yet.", docs: 'docs/guides/move-to-postgres.md#platforms' },+ graduation_verify_failed: { class: 'server', summary: "The moved copy did not verify against the source; the target stays fenced and the source stays authoritative.", docs: 'docs/guides/move-to-postgres.md#verify', reasons: ['count', 'digest', 'sequence', 'fk', 'trigger', 'relation_set', 'replay', 'doctor'] },graph_incomplete: { class: 'server', summary: "Source relationship reconciliation is incomplete." },held_out_overlaps_benchmark: { class: 'caller', summary: "Held out overlaps benchmark." },held_out_required_for_bundled: { class: 'caller', summary: "Held out required for bundled." },diff --git a/src/core/persistence/graduation-errors.ts b/src/core/persistence/graduation-errors.tsnew file mode 100644index 0000000000..53e5ae59b0--- /dev/null+++ b/src/core/persistence/graduation-errors.ts@@ -0,0 +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_target' | 'missing_row'; spelling?: GraduationCommandSpelling }): OperationError {+ const list = opts.relations.join(', ');+ const docs = GRADUATION_DOCS.graduation_unclassified_table;+ if (opts.cause === 'newer_target') {+ 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_target', 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_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 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.` } });+}++/** `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 --git a/src/core/persistence/graduation-serve-guard.ts b/src/core/persistence/graduation-serve-guard.tsnew file mode 100644index 0000000000..02c124eb10--- /dev/null+++ b/src/core/persistence/graduation-serve-guard.ts@@ -0,0 +1,126 @@+/**+ * 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 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 });+}++/** 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);+ }+}++/** 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 --git a/src/core/pglite-leftovers-check.ts b/src/core/pglite-leftovers-check.tsindex 8ed0474da3..bc565cda39 100644--- a/src/core/pglite-leftovers-check.ts+++ b/src/core/pglite-leftovers-check.ts@@ -54,6 +54,19 @@ export interface PgliteLeftoversAssessment {status: 'ok' | 'warn' | 'skip';message: string;leftovers: PgliteLeftoverDir[];+ /** Engine graduation's retained source copies (`<path>.graduated-<run_id>`). */+ retained?: PgliteLeftoverDir[];+}++/** Engine graduation's retained copy of a moved brain: `<data dir>.graduated-<run_id>`. */+export const GRADUATED_COPY_RE = /\.graduated-[A-Za-z0-9_-]+$/;++/** What graduation's manifest tells this check (file read by the caller). */+export interface GraduationLeftoverContext {+ /** The manifest state is non-terminal: a move is in flight or interrupted. */+ inFlight: boolean;+ /** The retained copy path the manifest records (it can live outside the gbrain home). */+ retainedPath?: string;}/**@@ -68,8 +81,9 @@ export const SIZE_WALK_MAX_ENTRIES = 20_000;* survives an interrupted run and is cleared only on clean completion. */export const MIGRATE_MANIFEST_NAME = 'migrate-manifest.json';-/** True only for the one directory the engines themselves create: the old- * store `brain.pglite`. gbrain never creates `brain.pglite.*` siblings+/** True only for the one directory the legacy copier leaves: the old+ * store `brain.pglite` (engine graduation's `<path>.graduated-<run_id>`+ * copies are matched separately by GRADUATED_COPY_RE). gbrain never creates `brain.pglite.*` siblings* (no pre-migrate copies, no backups) — those all have unknown provenance* and are out of scope. */export function isMigrationLeftoverName(name: string): boolean {@@ -167,10 +181,18 @@ export function assessPgliteLeftovers(engineKind: string | null | undefined,gbrainHome: string,maxEntries: number = SIZE_WALK_MAX_ENTRIES,+ graduation: GraduationLeftoverContext | null = null,): PgliteLeftoversAssessment {if (engineKind !== 'postgres') {return { status: 'skip', message: '', leftovers: [] };}+ if (graduation?.inFlight) {+ return {+ status: 'skip',+ message: 'An engine graduation is in flight or interrupted; its PGLite source and retained copy are not leftovers until it finishes.',+ leftovers: [],+ };+ }if (existsSync(join(gbrainHome, MIGRATE_MANIFEST_NAME))) {return {status: 'skip',@@ -181,6 +203,7 @@ export function assessPgliteLeftovers(};}let names: string[] = [];+ const retainedPaths = new Set<string>();const budget = { entries: maxEntries };try {const handle = opendirSync(gbrainHome);@@ -192,6 +215,8 @@ export function assessPgliteLeftovers(// a store this check can claim ownership of.if (entry.isDirectory() && !entry.isSymbolicLink() && isMigrationLeftoverName(entry.name)) {names.push(entry.name);+ } else if (entry.isDirectory() && !entry.isSymbolicLink() && GRADUATED_COPY_RE.test(entry.name)) {+ retainedPaths.add(join(gbrainHome, entry.name));}}} finally {@@ -200,9 +225,15 @@ export function assessPgliteLeftovers(} catch {return { status: 'skip', message: '', leftovers: [] };}- const leftovers: PgliteLeftoverDir[] = [];- for (const name of names.sort()) {- const p = join(gbrainHome, name);+ if (graduation?.retainedPath) {+ try {+ const st = lstatSync(graduation.retainedPath);+ if (st.isDirectory() && !st.isSymbolicLink()) retainedPaths.add(graduation.retainedPath);+ } catch {+ // the user already deleted it — nothing to report+ }+ }+ const measure = (p: string): PgliteLeftoverDir => {let mtime: string | null = null;try {const st = lstatSync(p);@@ -211,7 +242,22 @@ export function assessPgliteLeftovers(// stat raced a concurrent delete — still report the dir, without a date}const { bytes, incomplete } = walkSize(p, budget);- leftovers.push({ path: p, approx_bytes: bytes, size_incomplete: incomplete, dir_mtime: mtime });+ return { path: p, approx_bytes: bytes, size_incomplete: incomplete, dir_mtime: mtime };+ };+ const leftovers: PgliteLeftoverDir[] = names.sort().map(name => measure(join(gbrainHome, name)));+ const retained: PgliteLeftoverDir[] = [...retainedPaths].sort().map(measure);+ if (retained.length > 0) {+ const listing = retained.map(l => `${l.path} (${l.size_incomplete ? '>=' : ''}${humanBytes(l.approx_bytes, l.size_incomplete)})`).join('; ');+ const legacy = leftovers.length ? ` The legacy copier's old store also remains: ${leftovers.map(l => l.path).join('; ')}.` : '';+ return {+ status: 'warn',+ message:+ `Engine graduation kept the PGLite brain it moved to Postgres: ${listing}. It still holds private ` ++ `memory and access-token hashes, and it is what a rollback to PGLite restores. Deleting it is the ` ++ `user's call; afterwards a rollback is no longer possible.${legacy}`,+ leftovers,+ retained,+ };}if (leftovers.length === 0) {return {diff --git a/src/mcp/status-mode.ts b/src/mcp/status-mode.tsindex 04bfc1d4dc..3eee688dac 100644--- a/src/mcp/status-mode.ts+++ b/src/mcp/status-mode.ts@@ -23,9 +23,11 @@ import { configPath, gbrainPath, loadConfig, type GBrainConfig } from '../core/cimport { inspectLockHolder, peekLock } from '../core/pglite-lock.ts';import { HANDS_OFF_BRAIN_FILES, readRepairFailedMarker, type RepairFailedMarker } from '../core/pglite-repair.ts';import { resetReadinessMemo } from '../core/readiness.ts';+import { engineGraduatedFor, graduationStatusReason } from '../core/persistence/graduation-serve-guard.ts';+import { inspectGraduationPath } from '../core/persistence/graduation-custody.ts';export const STATUS_TOOL_NAME = 'gbrain_status';-export type StatusReason = 'lock_held' | 'no_brain' | 'config_unreadable' | 'missing_brain' | 'brain_unopenable' | 'repair_failed';+export type StatusReason = 'lock_held' | 'no_brain' | 'config_unreadable' | 'missing_brain' | 'brain_unopenable' | 'repair_failed' | 'engine_graduated';export interface StatusModeState {reason: StatusReason;@@ -72,6 +74,8 @@ export function probeStatus(): Omit<StatusModeState, 'recovered'> | null {if (!dataDir) return null;// A configured brain that is not there (unmounted drive, moved folder) is never recreated empty here.if (!existsSync(dataDir)) return { reason: 'missing_brain', config_path: cfgPath, brain_path: dataDir, checked_at: now };+ // A graduated brain's old path is a tombstone file: answer engine_graduated, never open or recreate it.+ if (graduationStatusReason(cfg)) return { reason: 'engine_graduated', config_path: cfgPath, brain_path: dataDir, checked_at: now };const marker = readRepairFailedMarker(dataDir);if (marker) return { reason: 'repair_failed', config_path: cfgPath, brain_path: dataDir, checked_at: now, repair_failed: marker };const holder = inspectLockHolder(dataDir);@@ -126,6 +130,7 @@ export function statusHeadline(state: StatusModeState): string {if (state.reason === 'config_unreadable') return `The gbrain config at ${state.config_path} exists but cannot be read (invalid JSON or unreadable), so this server cannot open a brain.`;if (state.reason === 'brain_unopenable') return `The brain at ${state.brain_path ?? 'its configured path'} exists, but its writer lock file next to it cannot be opened (a read-only or unmounted drive, or permissions), so this server cannot open it.`;if (state.reason === 'missing_brain') return `The brain configured in ${state.config_path} is not at ${state.brain_path ?? 'its configured path'} (an unmounted drive or a moved folder?), so this server cannot open it. Nothing was created there.`;+ if (state.reason === 'engine_graduated') return `This brain moved to Postgres; ${state.brain_path ?? 'its old PGLite path'} is a tombstone, and this server's config still points at it.`;if (state.reason === 'repair_failed') return `The brain at ${state.brain_path ?? 'its data directory'} is damaged and gbrain's automatic repair failed, so gbrain refuses to open it until the user decides how to recover.`;return `No gbrain brain is set up on this machine yet (no config at ${state.config_path}), so this server has no brain to open.`;}@@ -169,6 +174,10 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;}] : undefined,};}+ if (state.reason === 'engine_graduated' && state.brain_path) {+ const fix = engineGraduatedFor(inspectGraduationPath(state.brain_path), 'stdio').fix!;+ return { fix, user_message: fix.user_message ?? statusHeadline(state) };+ }if (state.reason === 'repair_failed') {const user_message = `Your gbrain brain at ${state.brain_path ?? 'its data directory'} is damaged and gbrain's automatic repair did not fix it, so gbrain has stopped opening it to keep it from getting worse. In a terminal you can preview the repair with \`gbrain pglite-repair --dry-run\` and run the one it prints after you agree, or restore the brain from a backup. Nobody should copy, move or edit the brain files by hand.`;return {diff --git a/test/graduation-errors.test.ts b/test/graduation-errors.test.tsnew file mode 100644index 0000000000..4e80a63119--- /dev/null+++ b/test/graduation-errors.test.ts@@ -0,0 +1,175 @@+/**+ * Engine graduation error contract (plan §8): one row per+ * GRADUATION_ERROR_CODES entry. Each refusal renders `why`, the expected+ * `fix.next`, a real argv (none only for `report`), a read-only+ * `fix.verify`, the registry row and exit code, and a docs anchor that+ * exists. Every emitted gbrain argv names a real command, uses only flags+ * that command accepts, and `gbrain migrate` argvs parse to the intended+ * graduation mode.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { cliRenderContext, toAgentError, type RenderedAction } from '../src/core/agent-output.ts';+import { CODES } from '../src/core/error-registry.ts';+import { exitCodeForCode } from '../src/core/error-catalogue.ts';+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';+import { CLI_COMMANDS } from '../src/cli/command-table.ts';+import type { OperationError } from '../src/core/ops/contract.ts';+import { GRADUATION_ERROR_CODES, type GraduationErrorCode } from '../src/core/persistence/engine-graduation.types.ts';+import {+ GRADUATION_DOCS, drainTimeoutError, embeddingDimensionMismatchError, engineGraduatedError, foreignHostBindingError,+ inProgressError, interruptedError, rollbackWritesLostError, sourceWriterHeldError, splitBrainError, targetAuthFailedError,+ targetDdlUnreachableError, targetNotEmptyError, targetUnsupportedError, unclassifiedTableError, unsupportedPlatformError,+ verifyFailedError,+} from '../src/core/persistence/graduation-errors.ts';+import { parseGraduationArgs, type GraduationMode } from '../src/commands/migrate-graduation.ts';++const ROOT = join(import.meta.dir, '..');+const tombstone = { targetDisplayUrl: 'postgresql://db.acme-example.test:5432/brain', movedTo: '/home/alice-example/.gbrain/brain.pglite.graduated-run1', runId: 'run1' };++interface Row {+ code: GraduationErrorCode;+ label: string;+ build: () => OperationError;+ next: RenderedAction['next'];+ exit: number;+ /** For `gbrain migrate` fix argvs: the mode it must parse to. */+ mode?: GraduationMode;+}++const ROWS: Row[] = [+ { code: 'graduation_source_writer_held', label: 'live stdio serve', next: 'tell_user_to_run', exit: 1,+ build: () => sourceWriterHeldError({ owner: { pid: 4242, transport: 'stdio', is_self: false }, rerun: ['gbrain', 'migrate', '--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL'] }) },+ { code: 'graduation_source_writer_held', label: 'daemon, no serve owner', next: 'tell_user_to_run', exit: 1, mode: 'run',+ build: () => sourceWriterHeldError({ owner: null, pid: 99, subcommand: 'autopilot', rerun: ['gbrain', 'migrate', '--to', 'supabase', '--url-env', 'GBRAIN_TARGET_URL'] }) },+ { code: 'graduation_unclassified_table', label: 'newer target', next: 'tell_user_to_run', exit: 1,+ build: () => unclassifiedTableError({ relations: ['future_table'], side: 'target', cause: 'newer_target' }) },+ { code: 'graduation_unclassified_table', label: 'missing inventory row', next: 'report', exit: 1,+ build: () => unclassifiedTableError({ relations: ['new_table'], side: 'source', cause: 'missing_row' }) },+ { code: 'graduation_embedding_dimension_mismatch', label: 'existing target', next: 'ask_user', exit: 1, mode: 'plan',+ build: () => embeddingDimensionMismatchError({ column: 'content_chunks.embedding', source: 'vector(1536)', target: 'vector(768)', host: 'db.acme-example.test' }) },+ { code: 'graduation_drain_timeout', label: 'blockers progressing', next: 'run', exit: 11, mode: 'resume',+ build: () => drainTimeoutError({ timeoutSec: 60, blockers: [{ kind: 'request', id: 'r1', detail: 'request r1 is running', needsUser: false }] }) },+ { code: 'graduation_drain_timeout', label: 'blocker needs a person', next: 'tell_user_to_run', exit: 11,+ build: () => drainTimeoutError({ timeoutSec: 60, blockers: [{ kind: 'writer_admin_lock', id: 'lock', detail: 'The writer admin lock is set.', argv: ['gbrain', 'sources', 'writer', 'unlock'], needsUser: true }] }) },+ { code: 'graduation_target_not_empty', label: 'foreign target', next: 'ask_user', exit: 1, mode: 'plan',+ build: () => targetNotEmptyError({ host: 'db.acme-example.test', tables: [{ relation: 'pages', rows: 12 }] }) },+ { code: 'graduation_foreign_host_binding', label: 'two-host transfer', next: 'tell_user_to_run', exit: 1,+ build: () => foreignHostBindingError({ sourceId: 'notes', ownerHost: 'host-b' }) },+ { code: 'graduation_verify_failed', label: 'first mismatch', next: 'run', exit: 1, mode: 'resume',+ build: () => verifyFailedError({ repeated: false, failures: [{ relation: 'pages', kind: 'digest', firstKey: '42', column: 'body', detail: 'pages digest differs' }] }) },+ { code: 'graduation_verify_failed', label: 'repeated mismatch', next: 'report', exit: 1,+ build: () => verifyFailedError({ repeated: true, failures: [{ relation: 'pages', kind: 'digest', detail: 'pages digest differs' }] }) },+ { code: 'graduation_interrupted', label: 'crashed run', next: 'run', exit: 1, mode: 'resume',+ build: () => interruptedError({ runId: 'run1', state: 'copying', dataDir: '/tmp/brain.pglite' }) },+ { code: 'graduation_in_progress', label: 'live run', next: 'wait', exit: 75, mode: 'status',+ build: () => inProgressError({ runId: 'run1', state: 'copying', pid: 7 }) },+ { code: 'graduation_split_brain', label: 'stray brain', next: 'ask_user', exit: 1, mode: 'resume',+ build: () => splitBrainError({ sourcePath: '/tmp/brain.pglite', strayPath: '/tmp/brain.pglite', strayRows: 3 }) },+ { code: 'graduation_rollback_writes_lost', label: 'confirmable page loss', next: 'ask_user', exit: 1, mode: 'rollback',+ build: () => rollbackWritesLostError({ final: false, planHash: 'ph_abc', losses: [{ relation: 'pages', rows: 2 }] }) },+ { code: 'graduation_rollback_writes_lost', label: 'withdrawal on target: final', next: 'report', exit: 1,+ build: () => rollbackWritesLostError({ final: true, losses: [{ relation: 'fact_withdrawals', rows: 1 }] }) },+ { code: 'graduation_target_auth_failed', label: 'password rotated', next: 'ask_user', exit: 1, mode: 'resume',+ build: () => targetAuthFailedError({ host: 'db.acme-example.test' }) },+ { code: 'graduation_target_ddl_unreachable', label: 'IPv6-only direct host', next: 'ask_user', exit: 1, mode: 'plan',+ build: () => targetDdlUnreachableError({ host: 'pooler.acme-example.test', ddlHost: 'db.acme-example.test' }) },+ { code: 'graduation_target_unsupported', label: 'no vector extension', next: 'ask_user', exit: 1, mode: 'plan',+ build: () => targetUnsupportedError({ requirement: 'vector', detail: 'the vector extension is not installed', host: 'db.acme-example.test' }) },+ { code: 'graduation_unsupported_platform', label: 'Windows with history', next: 'ask_user', exit: 1,+ build: () => unsupportedPlatformError({ platform: 'Windows' }) },+ { code: 'engine_graduated', label: 'graduating host (manifest past cutover)', next: 'run', exit: 1, mode: 'resume',+ build: () => engineGraduatedError({ tombstone, dataDir: '/tmp/brain.pglite', graduatingHost: true }) },+ { code: 'engine_graduated', label: 'stale CLI on another machine', next: 'tell_user_to_run', exit: 1,+ build: () => engineGraduatedError({ tombstone, dataDir: '/tmp/brain.pglite', graduatingHost: false, transport: 'cli' }) },+ { code: 'engine_graduated', label: 'stale MCP server config', next: 'tell_user_to_run', exit: 1,+ build: () => engineGraduatedError({ tombstone, dataDir: '/tmp/brain.pglite', graduatingHost: false, transport: 'stdio' }) },+];++function anchorsOf(path: string): Set<string> {+ const text = readFileSync(join(ROOT, path), 'utf8');+ const out = new Set<string>();+ for (const [, h] of text.matchAll(/^#{1,6}\s+(.+)$/gm)) out.add(h!.trim().toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-'));+ for (const [, id] of text.matchAll(/<a id="([^"]+)"><\/a>/g)) out.add(id!);+ return out;+}++const READ_ONLY_VERIFY = [/^gbrain migrate --status --json$/, /^gbrain migrate --to (postgres|supabase) --url-env \S+ --plan --json$/, /^gbrain doctor( |$)/, /^gbrain sources status /];++function assertArgvRunnable(argv: readonly string[], label: string): void {+ if (argv[0] !== 'gbrain') return;+ const command = argv[1]!;+ expect(CLI_COMMANDS.some(c => c.name === command) || command === 'sources', `${label}: unknown command ${command}`).toBe(true);+ const accepted = CLI_FLAG_REGISTRY[command];+ if (!accepted) return;+ for (const a of argv.slice(2)) {+ if (a.startsWith('--')) expect(accepted, `${label}: ${command} does not accept ${a}`).toContain(a.split('=')[0]!);+ }+}++describe('graduation error contract', () => {+ test('every GRADUATION_ERROR_CODES entry has a registry row, a docs anchor and at least one fixture row', () => {+ for (const code of GRADUATION_ERROR_CODES) {+ const entry = (CODES as Record<string, { docs?: string }>)[code];+ expect(entry, `${code}: no registry row`).toBeDefined();+ expect(entry!.docs).toBe(GRADUATION_DOCS[code]);+ const [path, anchor] = GRADUATION_DOCS[code].split('#');+ expect(anchorsOf(path!).has(anchor!), `${code}: ${GRADUATION_DOCS[code]} anchor missing`).toBe(true);+ expect(ROWS.some(r => r.code === code), `${code}: no fixture row`).toBe(true);+ }+ });++ for (const row of ROWS) {+ test(`${row.code} (${row.label}) renders why, fix.next=${row.next}, argv and a read-only verify`, () => {+ const e = row.build();+ expect(e.code).toBe(row.code);+ const env = toAgentError(e, { transport: 'cli', command: 'migrate', render: cliRenderContext() });+ expect(env.code).toBe(row.code);+ expect(env.why?.length ?? 0).toBeGreaterThan(20);+ expect(env.suggestion.length).toBeGreaterThan(10);+ expect(env.docs).toContain(GRADUATION_DOCS[row.code].split('#')[1]!);+ const fix = env.fix!;+ expect(fix, 'every graduation refusal carries a fix').toBeDefined();+ expect(fix.next).toBe(row.next);+ if (row.next === 'report') expect(fix.argv).toBeUndefined();+ else expect(fix.argv?.length ?? 0).toBeGreaterThan(0);+ expect(fix.verify?.argv, 'read-only verify').toBeDefined();+ expect(READ_ONLY_VERIFY.some(re => re.test(fix.verify!.argv!.join(' '))), `verify not read-only: ${fix.verify!.argv!.join(' ')}`).toBe(true);+ expect(exitCodeForCode(row.code)).toBe(row.exit);+ if (fix.next === 'ask_user' || fix.next === 'tell_user_to_run') expect(fix.user_message ?? fix.then?.user_message ?? env.suggestion).toBeTruthy();+ for (const step of [fix, fix.then].filter(Boolean) as RenderedAction[]) {+ if (step.argv) assertArgvRunnable(step.argv, `${row.code} fix`);+ if (step.verify?.argv) assertArgvRunnable(step.verify.argv, `${row.code} verify`);+ }+ if (row.mode) {+ expect(fix.argv![1]).toBe('migrate');+ expect(parseGraduationArgs(fix.argv!.slice(2)).mode).toBe(row.mode);+ }+ const verifyArgv = fix.verify!.argv!;+ if (verifyArgv[1] === 'migrate') expect(['status', 'plan']).toContain(parseGraduationArgs(verifyArgv.slice(2)).mode);+ });+ }++ test('no refusal text or argv carries a URL password', () => {+ for (const row of ROWS) {+ const text = JSON.stringify(toAgentError(row.build(), { transport: 'cli', command: 'migrate', render: cliRenderContext() }));+ expect(text).not.toMatch(/postgres(ql)?:\/\/[^\s/@"]+:[^\s/@"]+@/);+ }+ });++ test('a stale MCP config fix names the client restart; a stale CLI fix is one config command', () => {+ const mcp = engineGraduatedError({ tombstone, dataDir: '/tmp/brain.pglite', graduatingHost: false, transport: 'stdio' });+ expect(mcp.fix!.why).toContain('restart');+ const cli = engineGraduatedError({ tombstone, dataDir: '/tmp/brain.pglite', graduatingHost: false, transport: 'cli' });+ expect(cli.fix!.argv).toEqual(['gbrain', 'config', 'set', 'database_url', '<target_url>']);+ expect(cli.fix!.inputs?.[0]?.name).toBe('target_url');+ expect(cli.fix!.then).toBeUndefined();+ });++ test('a final rollback refusal offers no approval command', () => {+ const e = rollbackWritesLostError({ final: true, losses: [{ relation: 'oauth_tokens', rows: 1 }] });+ expect(e.fix!.argv).toBeUndefined();+ expect(JSON.stringify(e.fix)).not.toContain('--yes');+ });+});diff --git a/test/graduation-serve-guard.serial.test.ts b/test/graduation-serve-guard.serial.test.tsnew file mode 100644index 0000000000..521383f50a--- /dev/null+++ b/test/graduation-serve-guard.serial.test.ts@@ -0,0 +1,154 @@+/**+ * Engine graduation and long-lived clients (plan §6.4): a serve relaunched+ * during a run exits 75 with graduation_in_progress (a real `gbrain serve`+ * child), a stale config pointing at a tombstone gets status-only+ * `engine_graduated` with its one-step fix, a status-only/degraded serve+ * exits for relaunch when the engine identity changes, the resident serve+ * hand-off fires only for another live run, doctor's graduation finding and+ * pglite_leftovers report the run and the retained copy, and+ * `gbrain engine status --json` shows the graduation state. File fixtures+ * follow the plan's marker and tombstone formats.+ */+import { afterEach, beforeEach, 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 type { IntentMarker, Tombstone } from '../src/core/persistence/engine-graduation.types.ts';+import {+ engineIdentity, exitOnEngineIdentityChange, graduationHandoffRequested, graduationStatusReason, serveGraduationStartRefusal,+} from '../src/core/persistence/graduation-serve-guard.ts';+import { probeStatus, statusPayload, initialStatusState } from '../src/mcp/status-mode.ts';+import { graduationStateCheck } from '../src/commands/doctor/checks/engine-graduation.ts';+import { assessPgliteLeftovers } from '../src/core/pglite-leftovers-check.ts';++const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const target = { id: 'tid', host: 'db.acme-example.test', port: 5432, database: 'brain', user: 'alice' };+let home: string;+let dataDir: string;++function deadPid(): number {+ return Bun.spawnSync(['true']).pid;+}++function writeConfig(cfg: Record<string, unknown>): void {+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(cfg));+}++function writeMarker(over: Partial<IntentMarker>): void {+ const m: IntentMarker = { runId: 'run-1', state: 'copying', pid: process.ppid, bootId: null, pidNs: null, processStart: null, target, updatedAt: new Date().toISOString(), ...over };+ writeFileSync(`${dataDir}.gbrain-graduation.json`, JSON.stringify(m));+}++function writeTombstone(): void {+ rmSync(dataDir, { recursive: true, force: true });+ const t: Tombstone = { kind: 'gbrain-engine-graduated', runId: 'run-1', brainId: 'b1', movedTo: `${dataDir}.graduated-run-1`, target,+ targetDisplayUrl: 'postgresql://alice:***@db.acme-example.test:5432/brain', graduatedAt: new Date().toISOString(), fixArgv: ['gbrain', 'migrate', '--resume'] };+ writeFileSync(dataDir, JSON.stringify(t));+ mkdirSync(`${dataDir}.graduated-run-1`, { recursive: true });+ writeFileSync(join(`${dataDir}.graduated-run-1`, 'PG_VERSION'), '17');+}++const inHome = <T>(fn: () => T | Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_GRADUATION_RUN: undefined, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, fn);++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-grad-serve-'));+ mkdirSync(join(home, '.gbrain'));+ dataDir = join(home, '.gbrain', 'brain.pglite');+ mkdirSync(dataDir);+ writeConfig({ engine: 'pglite', database_path: dataDir });+});+afterEach(() => { rmSync(home, { recursive: true, force: true }); });++describe('serve start during a run', () => {+ test('a live run marker refuses with graduation_in_progress; a dead one or none does not', () => inHome(() => {+ expect(serveGraduationStartRefusal()).toBeNull();+ writeMarker({ pid: deadPid() });+ expect(serveGraduationStartRefusal()).toBeNull();+ writeMarker({});+ expect(serveGraduationStartRefusal()?.code).toBe('graduation_in_progress');+ expect(graduationHandoffRequested()?.code).toBe('graduation_in_progress');+ writeMarker({ pid: process.pid });+ expect(graduationHandoffRequested(), 'the run itself never hands off to itself').toBeNull();+ }));++ test('a relaunched `gbrain serve` exits 75 with the envelope and touches nothing', async () => {+ writeMarker({ pid: process.pid });+ const proc = Bun.spawn(['bun', CLI, 'serve'], {+ env: { ...process.env, GBRAIN_HOME: home, GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_NO_UPDATE_CHECK: '1' },+ stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',+ });+ const code = await proc.exited;+ const stderr = await new Response(proc.stderr).text();+ expect(code).toBe(75);+ const envelope = JSON.parse(stderr.slice(stderr.indexOf('{')));+ expect(envelope.code).toBe('graduation_in_progress');+ expect(envelope.fix.next).toBe('wait');+ expect(Bun.file(join(dataDir, 'PG_VERSION')).size).toBe(0);+ }, 60_000);+});++describe('stale config after cutover', () => {+ test('a tombstoned path is status-only engine_graduated with the config fix', () => inHome(() => {+ writeTombstone();+ expect(graduationStatusReason()?.reason).toBe('engine_graduated');+ expect(probeStatus()?.reason).toBe('engine_graduated');+ const payload = statusPayload(initialStatusState('engine_graduated')) as { reason: string; fix: { argv?: string[]; next: string }; user_message: string };+ expect(payload.reason).toBe('engine_graduated');+ expect(payload.fix.argv).toEqual(['gbrain', 'config', 'set', 'database_url', '<target_url>']);+ expect(payload.fix.next).toBe('tell_user_to_run');+ expect(payload.user_message).toContain('restart');+ }));++ test('identity change, a new tombstone or a run start exits the status/degraded serve for relaunch', () => inHome(() => {+ const start = engineIdentity();+ const exits: number[] = [];+ const opts = { exit: (c: number) => { exits.push(c); }, log: () => {} };+ exitOnEngineIdentityChange(start, opts);+ expect(exits).toEqual([]);+ writeTombstone();+ exitOnEngineIdentityChange(start, opts);+ expect(exits).toEqual([75]);+ exitOnEngineIdentityChange(start, { ...opts, startedGraduated: true });+ expect(exits).toEqual([75]);+ writeConfig({ engine: 'postgres', database_url: 'postgresql://alice:[email protected]:5432/brain' });+ exitOnEngineIdentityChange(start, { ...opts, startedGraduated: true });+ expect(exits).toEqual([75, 75]);+ exitOnEngineIdentityChange(null, opts);+ expect(exits, 'a serve that started with no config recovers in place').toEqual([75, 75]);+ }));+});++describe('doctor and engine status', () => {+ test('graduation_interrupted fails for a dead run, is ok for a live one, exempts the verify child, silent otherwise', () => inHome(() => {+ expect(graduationStateCheck()).toBeNull();+ writeMarker({ pid: deadPid() });+ const failing = graduationStateCheck()!;+ expect(failing).toMatchObject({ name: 'graduation_interrupted', status: 'fail' });+ expect((failing.fix as { argv?: string[] }).argv).toEqual(['gbrain', 'migrate', '--resume']);+ expect(graduationStateCheck({ env: { GBRAIN_GRADUATION_RUN: 'run-1' } })).toBeNull();+ writeMarker({});+ expect(graduationStateCheck()).toMatchObject({ status: 'ok' });+ }));++ test('pglite_leftovers reports the retained copy with size and stays silent mid-run', () => {+ writeTombstone();+ const a = assessPgliteLeftovers('postgres', join(home, '.gbrain'));+ expect(a.status).toBe('warn');+ expect(a.retained?.[0]?.path).toBe(`${dataDir}.graduated-run-1`);+ expect(a.message).toContain('private memory and access-token hashes');+ expect(assessPgliteLeftovers('postgres', join(home, '.gbrain'), undefined, { inFlight: true }).status).toBe('skip');+ expect(assessPgliteLeftovers('pglite', join(home, '.gbrain')).status).toBe('skip');+ });++ test('engine status --json carries the graduation block', async () => {+ writeTombstone();+ const proc = Bun.spawn(['bun', CLI, 'engine', 'status', '--json'], {+ env: { ...process.env, GBRAIN_HOME: home, GBRAIN_DATABASE_URL: '', DATABASE_URL: '', GBRAIN_NO_UPDATE_CHECK: '1' }, stdout: 'pipe', stderr: 'pipe',+ });+ await proc.exited;+ const report = JSON.parse(await new Response(proc.stdout).text());+ expect(report.graduation).toMatchObject({ state: 'graduated', run_id: 'run-1', tombstone: { moved_to: `${dataDir}.graduated-run-1` } });+ expect(JSON.stringify(report)).not.toContain(':pw@');+ }, 60_000);+});diff --git a/test/migrate-graduation-cli.serial.test.ts b/test/migrate-graduation-cli.serial.test.tsnew file mode 100644index 0000000000..7246685600--- /dev/null+++ b/test/migrate-graduation-cli.serial.test.ts@@ -0,0 +1,247 @@+/**+ * `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 {+ 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 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 });+ }+ });+});