Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(graduation): crash, fault and client suites against the custody boundaries

garrytan31d4080b8e1f
diff --git a/scripts/persistence/graduation-fixture.ts b/scripts/persistence/graduation-fixture.ts
index 58e41a7e09..2d30b3bb52 100644
--- a/scripts/persistence/graduation-fixture.ts
+++ b/scripts/persistence/graduation-fixture.ts
@@ -78,8 +78,11 @@ export interface GraduationFixture {
}
const REPO = resolve(import.meta.dir, '..', '..');
-const KEY_FILES = ['scripts/persistence/graduation-fixture.ts', 'scripts/persistence/history-fixture.ts', 'scripts/persistence/ops.ts',
- 'test/fixtures/graduation/legacy-brain.ts', 'test/fixtures/graduation/expected.json'];
+/** Files whose bytes decide what a build produces, per kind (the cache key covers exactly these). */
+const KEY_FILES: Record<GraduationFixtureKind, readonly string[]> = {
+ history: ['scripts/persistence/graduation-fixture.ts', 'scripts/persistence/history-fixture.ts', 'scripts/persistence/ops.ts'],
+ legacy: ['scripts/persistence/graduation-fixture.ts', 'scripts/persistence/ops.ts', 'test/fixtures/graduation/legacy-brain.ts', 'test/fixtures/graduation/expected.json'],
+};
const PROVIDER_KEYS = /^(OPENAI|ANTHROPIC|VOYAGE|GEMINI|GOOGLE|TYPESAFE|JEV_TYPESAFE|OPENROUTER|GROQ|MISTRAL|COHERE|DEEPSEEK|XAI)_/;
function normalized(opts: GraduationFixtureOptions) {
@@ -91,7 +94,7 @@ function normalized(opts: GraduationFixtureOptions) {
export async function graduationFixtureKey(opts: GraduationFixtureOptions): Promise<string> {
const { LATEST_VERSION } = await import('../../src/core/migrate.ts');
const hash = createHash('sha256');
- for (const file of KEY_FILES) hash.update(file).update(readFileSync(join(REPO, file)));
+ for (const file of KEY_FILES[opts.kind]) hash.update(file).update(readFileSync(join(REPO, file)));
hash.update(JSON.stringify({ schema: LATEST_VERSION, ...normalized(opts) }));
return hash.digest('hex').slice(0, 32);
}
@@ -160,7 +163,6 @@ export async function rehomeFixture(dir: string): Promise<void> {
const metaPath = join(dir, 'fixture.json');
const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
const from: string = meta.builtAt;
- if (from === dir) return;
const swap = (text: string) => text.split(from).join(dir);
const files: string[] = [];
walk(dir, path => { if (path.endsWith('.json') && statSync(path).size <= 65_536) files.push(path); });
@@ -197,11 +199,31 @@ export async function rehomeFixture(dir: string): Promise<void> {
await tx.executeRaw(`UPDATE persistence_host_bindings SET local_path=replace(local_path,$1,$2),coordination_path=replace(coordination_path,$1,$2)
WHERE local_path LIKE $3 OR coordination_path LIKE $3`, [from, dir, `${from}%`]);
});
+ await markSourcesSynced(engine);
} finally { await engine.disconnect(); }
meta.builtAt = dir;
writeFileSync(metaPath, JSON.stringify(meta, null, 2));
}
+/**
+ * Record every checkout-backed source as synced now at its current Git HEAD and
+ * chunker version, as a user's routinely synced brain is. Doctor's
+ * sync_freshness is wall-clock based, so a cached fixture is refreshed on each
+ * restore; otherwise the source doctor (a graduation plan blocker) fails.
+ */
+async function markSourcesSynced(engine: import('../../src/core/engine.ts').BrainEngine): Promise<void> {
+ const { CHUNKER_VERSION } = await import('../../src/core/chunkers/code.ts');
+ const sources = await engine.executeRaw<{ id: string; local_path: string }>('SELECT id,local_path FROM sources WHERE local_path IS NOT NULL');
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.write_sources',$1,true)", [JSON.stringify(sources.map(source => source.id))]);
+ for (const source of sources) {
+ const head = Bun.spawnSync(['git', '-C', source.local_path, 'rev-parse', 'HEAD'], { stdout: 'pipe', stderr: 'pipe' });
+ await tx.executeRaw('UPDATE sources SET last_sync_at=now(),last_commit=$2,chunker_version=$3 WHERE id=$1',
+ [source.id, head.exitCode === 0 ? head.stdout.toString().trim() : null, String(CHUNKER_VERSION)]);
+ }
+ });
+}
+
function dirBytes(path: string): number {
let total = 0;
for (const entry of readdirSync(path, { withFileTypes: true })) {
@@ -266,6 +288,7 @@ async function buildChild(spec: { kind: GraduationFixtureKind; key: string; dir:
} finally {
await disposePersistenceConsumer(engine);
}
+ await markSourcesSynced(engine);
const buildMs = Math.round(performance.now() - started);
const report = await reportFor(engine, spec.kind, dataDir, buildMs);
await engine.disconnect();
diff --git a/src/core/persistence/engine-graduation.types.ts b/src/core/persistence/engine-graduation.types.ts
index bf90114460..cc6eaff09a 100644
--- a/src/core/persistence/engine-graduation.types.ts
+++ b/src/core/persistence/engine-graduation.types.ts
@@ -280,3 +280,37 @@ export const GRADUATION_ERROR_CODES = [
'engine_graduated',
] as const;
export type GraduationErrorCode = typeof GRADUATION_ERROR_CODES[number];
+
+/**
+ * Custody boundaries, in run order, that the orchestrator announces with
+ * `graduationBoundary(name)` right after the step's durable write commits.
+ * The crash suite (test/e2e/graduation-crash.test.ts) SIGKILLs the real CLI
+ * at each one, and the zero-mutation suite pauses there to poll --status.
+ * `table_copied` fires after each table's copy transaction commits and
+ * `batch_copied` after each committed batch inside a table, both with
+ * `detail.relation`.
+ */
+export const GRADUATION_RUN_BOUNDARIES = [
+ 'quiesced', 'drain_started', 'drained', 'target_fenced', 'batch_copied', 'table_copied', 'copied', 'verified',
+ 'source_cutover', 'source_closed', 'moved_aside', 'tombstoned', 'authoritative', 'config_flipped', 'registry_rewritten', 'graduated',
+] as const;
+/** Rollback substeps after cutover, in order (§13 rollback custody). */
+export const GRADUATION_ROLLBACK_BOUNDARIES = [
+ 'rollback_fenced', 'rollback_approved', 'source_restoring', 'tombstone_removed', 'renamed_back', 'config_restored', 'rolled_back',
+] as const;
+export type GraduationBoundary = typeof GRADUATION_RUN_BOUNDARIES[number] | typeof GRADUATION_ROLLBACK_BOUNDARIES[number];
+export interface GraduationBoundaryDetail { runId?: string; relation?: string; batch?: number }
+export interface GraduationHooks {
+ boundary?(name: GraduationBoundary, detail: GraduationBoundaryDetail): Promise<void> | void;
+}
+/**
+ * Test-only registration point: a crash-test preload (test/helpers/graduation-hooks-preload.ts)
+ * stores hooks under this symbol before the CLI starts. Production code never sets it.
+ */
+export const GRADUATION_HOOKS = Symbol.for('gbrain.graduation.hooks');
+
+/** Announce a custody boundary; a no-op unless a test registered hooks. */
+export async function graduationBoundary(name: GraduationBoundary, detail: GraduationBoundaryDetail = {}): Promise<void> {
+ const hooks = (globalThis as Record<symbol, GraduationHooks | undefined>)[GRADUATION_HOOKS];
+ await hooks?.boundary?.(name, detail);
+}
diff --git a/test/e2e/graduation-clients.test.ts b/test/e2e/graduation-clients.test.ts
new file mode 100644
index 0000000000..045897998f
--- /dev/null
+++ b/test/e2e/graduation-clients.test.ts
@@ -0,0 +1,302 @@
+/**
+ * Engine graduation versus every other client of the brain: older released
+ * binaries, a `gbrain serve` respawned mid-copy, a resident serve that must
+ * hand the source over, and stale CLI or MCP configurations after cutover.
+ *
+ * Protects: §3.3 and §6.4 of the plan plus §13 CEO/DX (tombstone, marker
+ * hand-off, split-brain detection, database fence, one-step stale-client fix).
+ * - An older release pointed at the tombstoned path fails (EEXIST/ENOTDIR)
+ * and never creates a fresh empty brain there. This half runs before the
+ * orchestrator lands, against a tombstone written to the Tombstone contract.
+ * - In the rename-to-tombstone window an older release can create a stray
+ * brain; the next `--resume` refuses with `graduation_split_brain` and the
+ * target stays non-authoritative.
+ * - A write by an older release in a lock gap before the tombstone reaches
+ * the target on resume (source digests re-checked).
+ * - An older release configured with the target URL cannot write while the
+ * target is fenced (copying, and between verify and cutover).
+ * - A respawned stdio or HTTP serve exits with `graduation_in_progress`,
+ * writes nothing and takes no lock; a resident serve hands off within 30 s.
+ * - A stale CLI config and a stale MCP config each recover by running the
+ * refusal's fix once.
+ * Not covered elsewhere: these are the only multi-process client tests.
+ * Older binaries are built once per tag (test/helpers/graduation-e2e.ts
+ * `olderReleaseBinary`, cached under GBRAIN_OLDER_RELEASE_DIR).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync, constants } from 'node:fs';
+import { dirname, join } from 'node:path';
+import type { Tombstone } from '../../src/core/persistence/engine-graduation.types.ts';
+import {
+ codeOf, custodyPaths, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, GRADUATION_LANDED, graduationTest, mcpStdioSession, olderReleaseBinary,
+ previousReleaseTags, release, REPO, startGbrain, stateDigest, TARGET_ENV, waitForEvent, type GbrainResult,
+} from '../helpers/graduation-e2e.ts';
+import { configuredEngine, expectGraduated, legacyCase, planAndRun, scratchRoot, targetRowState, withTarget, type Case } from '../helpers/graduation-scenarios.ts';
+
+const cases: Case[] = [];
+let older: { tag: string; binary: string }[] = [];
+let olderError: string | null = null;
+
+beforeAll(() => {
+ try { older = previousReleaseTags(2).map(tag => ({ tag, binary: olderReleaseBinary(tag) })); }
+ catch (error) { olderError = String(error); }
+}, 900_000);
+
+afterAll(async () => {
+ for (const c of cases) await c.target.close().catch(() => {});
+ rmSync(scratchRoot, { recursive: true, force: true });
+});
+
+async function fresh(name: string): Promise<Case> {
+ const c = await legacyCase(name);
+ cases.push(c);
+ return c;
+}
+
+/** A second GBRAIN_HOME whose copied config still routes to the PGLite path (a stale client on this machine). */
+function staleHome(c: Case): string {
+ const home = join(c.fx.dir, 'stale-home');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: c.fx.dataDir, embedding_disabled: true }, null, 2), { mode: 0o600 });
+ return home;
+}
+
+/** `gbrain` on PATH for running a refusal's shell `fix.command` exactly as an agent would. */
+function shimPath(c: Case): string {
+ const bin = join(c.fx.dir, 'shim-bin');
+ mkdirSync(bin, { recursive: true });
+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec "${process.execPath}" --no-env-file "${join(REPO, 'src', 'cli.ts')}" "$@"\n`);
+ chmodSync(join(bin, 'gbrain'), 0o755);
+ return `${bin}:${process.env.PATH}`;
+}
+
+/** Run a refusal's fix once: `fix.argv` through the CLI, or the shell `fix.command`. */
+async function runFix(fix: Record<string, any>, home: string, c: Case): Promise<GbrainResult> {
+ const env = { [TARGET_ENV]: c.target.url, PATH: shimPath(c) };
+ if (Array.isArray(fix.argv) && fix.argv[0] === 'gbrain') return gbrain(fix.argv.slice(1), { home, env });
+ expect(typeof fix.command).toBe('string');
+ const child = Bun.spawn(['sh', '-c', fix.command], { env: { ...process.env, ...env, HOME: home, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '' }, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
+ await child.exited;
+ return { code: child.exitCode ?? -1, signal: null, stdout, stderr, json: null, ms: 0 };
+}
+
+/** The Tombstone contract written by hand (O_EXCL, 0600, fsync file + parent), for the pre-integration half. */
+function handTombstone(c: Case, runId: string): void {
+ const movedTo = `${c.fx.dataDir}.graduated-${runId}`;
+ renameSync(c.fx.dataDir, movedTo);
+ const tombstone: Tombstone = { kind: 'gbrain-engine-graduated', runId, brainId: c.before.brainId, movedTo,
+ target: { id: 'hand-written', host: '127.0.0.1', port: 5432, database: 'gbrain_test', user: 'postgres' },
+ targetDisplayUrl: 'postgresql://[email protected]:5432/gbrain_test', graduatedAt: new Date().toISOString(),
+ fixArgv: ['gbrain', 'config', 'set', 'database_url', '$GBRAIN_TARGET_URL'] };
+ const fd = openSync(c.fx.dataDir, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
+ try { writeSync(fd, JSON.stringify(tombstone)); fsyncSync(fd); } finally { closeSync(fd); }
+ const parent = openSync(dirname(c.fx.dataDir), 'r');
+ try { fsyncSync(parent); } finally { closeSync(parent); }
+}
+
+async function olderRun(binary: string, home: string, argv: string[], stdin?: string): Promise<GbrainResult> {
+ return gbrain(argv, { home, binary, stdin, timeoutMs: 120_000 });
+}
+
+describe.skipIf(!DATABASE_URL)('graduation: older released binaries', () => {
+ test('older releases refuse a tombstoned path and never create a data dir there', async () => {
+ expect(olderError).toBeNull();
+ expect(older.length).toBe(2);
+ const c = await fresh('older-tombstone');
+ if (GRADUATION_LANDED) {
+ const { argv, env } = await planAndRun(c);
+ expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);
+ } else {
+ handTombstone(c, 'hand-run');
+ }
+ const home = staleHome(c);
+ const tombstoneBytes = readFileSync(c.fx.dataDir);
+ const retained = custodyPaths(c.fx.dataDir).graduated;
+ expect(retained.length).toBe(1);
+ const retainedBefore = await stateDigest(retained[0]);
+ for (const { tag, binary } of older) {
+ for (const [argv, stdin] of [[['query', 'acme'], undefined], [['put', 'notes/older-write', '--source', 'default'], 'older binary write\n']] as const) {
+ const r = await olderRun(binary, home, [...argv], stdin);
+ expect({ tag, argv: argv[0], failed: r.code !== 0 }).toEqual({ tag, argv: argv[0], failed: true });
+ expect(`${r.stdout}${r.stderr}`).toMatch(/EEXIST|ENOTDIR|engine_graduated/);
+ expect(statSync(c.fx.dataDir).isFile()).toBe(true);
+ expect(readFileSync(c.fx.dataDir).equals(tombstoneBytes)).toBe(true);
+ }
+ }
+ expect(digestChanges(retainedBefore, await stateDigest(retained[0]))).toEqual([]);
+ }, 900_000);
+
+ graduationTest('an older release in the rename-to-tombstone window: a stray brain is reported as split brain and the target stays withheld', async () => {
+ const c = await fresh('older-window');
+ const { argv, env } = await planAndRun(c);
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['moved_aside'] } });
+ await waitForEvent(c.events, e => e.event === 'paused', child);
+ child.kill('SIGKILL');
+ await child.exited;
+ const home = staleHome(c);
+ const stray = await olderRun(older[0].binary, home, ['put', 'notes/stray', '--source', 'default'], 'stray brain write\n');
+ const createdStray = custodyPaths(c.fx.dataDir).dataDirIsDirectory;
+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 });
+ if (createdStray) {
+ expect(resumed.code).toBe(1);
+ expect(codeOf(resumed.json)).toBe('graduation_split_brain');
+ expect(fixOf(resumed.json)?.next).toBe('ask_user');
+ expect(await targetRowState(c.target.url)).not.toBe('authoritative');
+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });
+ const text = JSON.stringify(status.json);
+ expect(text).toContain(c.fx.dataDir);
+ expect(text).toContain('.graduated-');
+ } else {
+ expect(stray.code).not.toBe(0);
+ expect(resumed.code).toBe(0);
+ await expectGraduated(c, 'window without a stray brain');
+ }
+ }, 900_000);
+
+ graduationTest('an older release after the tombstone fails EEXIST; resume completes', async () => {
+ const c = await fresh('older-after-tombstone');
+ const { argv, env } = await planAndRun(c);
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['tombstoned'] } });
+ await waitForEvent(c.events, e => e.event === 'paused', child);
+ child.kill('SIGKILL');
+ await child.exited;
+ for (const { binary } of older) {
+ const r = await olderRun(binary, staleHome(c), ['query', 'acme']);
+ expect(r.code).not.toBe(0);
+ expect(statSync(c.fx.dataDir).isFile()).toBe(true);
+ }
+ expect((await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 })).code).toBe(0);
+ await expectGraduated(c, 'after tombstone kill');
+ }, 900_000);
+
+ for (const boundary of ['verified', 'source_closed'] as const) {
+ graduationTest(`an older-release write to the source in the lock gap after ${boundary} reaches the target on resume`, async () => {
+ const c = await fresh(`older-gap-${boundary}`);
+ const { argv, env } = await planAndRun(c);
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: [boundary] } });
+ await waitForEvent(c.events, e => e.event === 'paused', child);
+ child.kill('SIGKILL');
+ await child.exited;
+ const write = await olderRun(older[0].binary, c.fx.home, ['put', 'notes/lock-gap-write', '--source', 'default'], 'written by an older release in the lock gap\n');
+ expect({ code: write.code, stderr: write.code === 0 ? '' : write.stderr.slice(-1500) }).toEqual({ code: 0, stderr: '' });
+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 900_000 });
+ expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+ await withTarget(c.target.url, async t => {
+ const [row] = await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id='default' AND slug='notes/lock-gap-write'`);
+ expect(Number(row.n)).toBe(1);
+ });
+ expect(configuredEngine(c.fx).engine).toBe('postgres');
+ }, 900_000);
+ }
+
+ graduationTest('an older release configured with the target URL cannot write while the target is fenced', async () => {
+ const c = await fresh('older-vs-fence');
+ const { argv, env } = await planAndRun(c, { extra: ['--batch-size', '2'] });
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['batch_copied@pages', 'verified'] } });
+ for (const ordinal of [1, 2]) {
+ const paused = await waitForEvent(c.events, e => e.event === 'paused' && e.ordinal === ordinal, child);
+ const before = await stateDigest(join(c.fx.dir, 'nonexistent'), c.target.url);
+ const probeHome = join(c.fx.dir, `older-target-${ordinal}`);
+ const r = await olderRun(older[0].binary, probeHome, ['put', 'notes/fenced', '--source', 'default'], 'must not land\n');
+ expect({ boundary: paused.boundary, failed: r.code !== 0 }).toEqual({ boundary: paused.boundary, failed: true });
+ expect(digestChanges(before, await stateDigest(join(c.fx.dir, 'nonexistent'), c.target.url))).toEqual([]);
+ release(c.events, ordinal);
+ }
+ const done = await child.exited;
+ expect(done.code).toBe(0);
+ await expectGraduated(c, 'after fenced probes');
+ }, 900_000);
+});
+
+describe.skipIf(!DATABASE_URL)('graduation: serve processes', () => {
+ graduationTest('a serve respawned mid-copy (stdio and http) exits with graduation_in_progress, writes nothing, takes no lock', async () => {
+ const c = await fresh('respawn-serve');
+ const { argv, env } = await planAndRun(c, { extra: ['--batch-size', '2'] });
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['batch_copied@pages'] } });
+ const paused = await waitForEvent(c.events, e => e.event === 'paused', child);
+ const watched = async () => {
+ const d = await stateDigest(c.fx.dataDir, c.target.url);
+ for (const path of [`${c.fx.dataDir}.gbrain-graduation.json`, join(c.fx.home, '.gbrain', 'graduation-manifest.json'), join(c.fx.home, '.gbrain', 'config.json')]) {
+ d.files[path] = existsSync(path) ? readFileSync(path, 'utf8') : '(absent)';
+ }
+ return d;
+ };
+ const before = await watched();
+ const stdio = await mcpStdioSession({ home: c.fx.home, timeoutMs: 60_000 });
+ const stdioExit = await Promise.race([stdio.exited, Bun.sleep(45_000).then(() => null)]);
+ expect(stdioExit).not.toBeNull();
+ expect(stdioExit!.code).not.toBe(0);
+ expect(`${stdioExit!.stdout}${stdioExit!.stderr}`).toContain('graduation_in_progress');
+ const http = await gbrain(['serve', '--http', '--port', String(freePort())], { home: c.fx.home, timeoutMs: 60_000 });
+ expect(http.code).not.toBe(0);
+ expect(http.signal).toBeNull();
+ expect(`${http.stdout}${http.stderr}`).toContain('graduation_in_progress');
+ expect(digestChanges(before, await watched())).toEqual([]);
+ release(c.events, paused.ordinal!);
+ const done = await child.exited;
+ expect({ code: done.code, stderr: done.code === 0 ? '' : done.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+ await expectGraduated(c, 'after respawned serves');
+ }, 900_000);
+
+ graduationTest('a resident stdio serve hands the source over through the intent marker; no manual stop', async () => {
+ const c = await fresh('live-serve');
+ const serve = await mcpStdioSession({ home: c.fx.home, timeoutMs: 900_000 });
+ const before = await serve.call('get_page', { slug: 'people/alice-example', source_id: 'default' });
+ expect(before?.error).toBeUndefined();
+ const { argv, env } = await planAndRun(c);
+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });
+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+ const served = await Promise.race([serve.exited, Bun.sleep(30_000).then(() => null)]);
+ expect(served).not.toBeNull();
+ expect(`${served!.stdout}${served!.stderr}`).toContain('graduation_in_progress');
+ expect(JSON.stringify(run.json)).toMatch(/restart|mcp/i);
+ await expectGraduated(c, 'after live-serve hand-off');
+ const relaunched = await mcpStdioSession({ home: c.fx.home });
+ const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });
+ await relaunched.close();
+ expect(after?.error).toBeUndefined();
+ }, 900_000);
+});
+
+describe.skipIf(!DATABASE_URL)('graduation: stale clients recover in one step', () => {
+ graduationTest('a stale CLI config gets engine_graduated with a fix that works when run once', async () => {
+ const c = await fresh('stale-cli');
+ const { argv, env } = await planAndRun(c);
+ expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);
+ const home = staleHome(c);
+ const refused = await gbrain(['query', 'acme', '--json'], { home });
+ expect(refused.code).not.toBe(0);
+ expect(codeOf(refused.json)).toBe('engine_graduated');
+ const fix = fixOf(refused.json)!;
+ expect(['run', 'tell_user_to_run']).toContain(fix.next);
+ expect(JSON.stringify(fix)).not.toContain(new URL(c.target.url).password);
+ const fixed = await runFix(fix, home, c);
+ expect({ code: fixed.code, stderr: fixed.code === 0 ? '' : fixed.stderr.slice(-1500) }).toEqual({ code: 0, stderr: '' });
+ const retried = await gbrain(['get', 'people/alice-example', '--source', 'default'], { home });
+ expect({ code: retried.code, stderr: retried.code === 0 ? '' : retried.stderr.slice(-1500) }).toEqual({ code: 0, stderr: '' });
+ expect(retried.stdout).toContain('Alice-example');
+ }, 900_000);
+
+ graduationTest('a stale MCP server config surfaces engine_graduated through the MCP host and recovers after one fix', async () => {
+ const c = await fresh('stale-mcp');
+ const { argv, env } = await planAndRun(c);
+ expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);
+ const home = staleHome(c);
+ const stale = await mcpStdioSession({ home });
+ const reply = await stale.call('get_page', { slug: 'people/alice-example', source_id: 'default' });
+ const exited = await stale.close();
+ const text = `${JSON.stringify(reply)}${exited.stdout}${exited.stderr}`;
+ expect(text).toContain('engine_graduated');
+ const match = /\{[^{}]*"next"\s*:\s*"(?:run|tell_user_to_run)"[^{}]*\}/.exec(text.replace(/\\"/g, '"'));
+ expect(match).not.toBeNull();
+ const fixed = await runFix(JSON.parse(match![0]), home, c);
+ expect(fixed.code).toBe(0);
+ const relaunched = await mcpStdioSession({ home });
+ const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });
+ await relaunched.close();
+ expect(after?.error).toBeUndefined();
+ expect(JSON.stringify(after)).toContain('Alice-example');
+ }, 900_000);
+});
+
diff --git a/test/e2e/graduation-crash.test.ts b/test/e2e/graduation-crash.test.ts
new file mode 100644
index 0000000000..f8c3f05ea0
--- /dev/null
+++ b/test/e2e/graduation-crash.test.ts
@@ -0,0 +1,214 @@
+/**
+ * Engine graduation crash custody (PGLite -> Postgres 16).
+ *
+ * Protects: "exactly one authoritative engine at every instant, across
+ * crashes" (plan §3.3, §6.2, §13). The real CLI run is SIGKILLed at every
+ * custody boundary it announces (quiesce, drain, fence, mid-table and
+ * table-boundary copy, verify, each cutover sub-step, around the routing flip)
+ * and at every rollback substep. After each kill: no instant with two
+ * writable engines; `--status` reports without mutating; a clean process with
+ * no target environment variable resumes from the 0600 manifest; the end
+ * state is graduated (or rolled back) with every expected.json expectation,
+ * one row per request id, the queued request replaying its stored outcome,
+ * and a green target doctor.
+ * Regressions it catches: a step whose durable write is not ordered before
+ * its effect (e.g. tombstone before rename, authority before tombstone),
+ * reconciliation that restarts from routing instead of the manifest, a
+ * resume that re-runs terminal requests, a rollback that strands the live
+ * brain or restores authority after approval.
+ * Not covered elsewhere: the orchestrator's unit tests run in-process without
+ * kills. Production seam: `graduationBoundary()` hooks, inert unless the
+ * crash preload registers them.
+ * Runtime: about 40 s per case; run with GBRAIN_E2E_FILE_TIMEOUT=3600.
+ */
+import { afterAll, describe, expect } from 'bun:test';
+import { rmSync } from 'node:fs';
+import { GRADUATION_ROLLBACK_BOUNDARIES, GRADUATION_RUN_BOUNDARIES } from '../../src/core/persistence/engine-graduation.types.ts';
+import { codeOf, DATABASE_URL, fixOf, gbrain, graduationTest, planHashOf, readEvents, startGbrain, stateOf, TARGET_ENV, waitForEvent } from '../helpers/graduation-e2e.ts';
+import {
+ authority, configuredEngine, expectAtMostOneWriter, expectGraduated, legacyCase, manifestState, planAndRun, rollback, scratchRoot,
+ targetFenceTriggers, targetRowState, withSource, withTarget, type Case,
+} from '../helpers/graduation-scenarios.ts';
+
+const cases: Case[] = [];
+afterAll(async () => {
+ for (const c of cases) await c.target.close().catch(() => {});
+ rmSync(scratchRoot, { recursive: true, force: true });
+});
+
+async function fresh(name: string): Promise<Case> {
+ const c = await legacyCase(name);
+ cases.push(c);
+ return c;
+}
+
+/** Start the confirmed run paused at `pause`, wait for it, SIGKILL it. */
+async function killAt(c: Case, pause: string, extra: string[] = []): Promise<void> {
+ const { argv, env } = await planAndRun(c, { extra });
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: [pause] }, timeoutMs: 600_000 });
+ await waitForEvent(c.events, e => e.event === 'paused', child);
+ child.kill('SIGKILL');
+ const result = await child.exited;
+ expect(result.signal).toBe('SIGKILL');
+}
+
+/** Graduate to completion with no kill. */
+async function graduate(c: Case): Promise<void> {
+ const { argv, env } = await planAndRun(c);
+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });
+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+}
+
+/** Start the rollback as an agent would (confirming with the hash if asked), paused at `boundary`, then SIGKILL it. */
+async function killRollbackAt(c: Case, boundary: string): Promise<void> {
+ const hooks = { events: c.events, pause: [boundary] };
+ let child = startGbrain(['migrate', '--rollback-to-source', '--json'], { home: c.fx.home, hooks });
+ const paused = await waitForEvent(c.events, e => e.event === 'paused', child).then(() => true, () => false);
+ if (!paused) {
+ const first = await child.exited;
+ expect(first.code).toBe(3);
+ child = startGbrain(['migrate', '--rollback-to-source', '--yes', '--expect', String(planHashOf(first.json)), '--json'], { home: c.fx.home, hooks });
+ await waitForEvent(c.events, e => e.event === 'paused' && e.boundary === boundary, child);
+ }
+ child.kill('SIGKILL');
+ await child.exited;
+}
+
+/** Every run boundary, with the copy boundaries pinned to a multi-batch table (pages at --batch-size 2). */
+const RUN_KILLS: { pause: string; label: string }[] = GRADUATION_RUN_BOUNDARIES.map(b =>
+ b === 'batch_copied' ? { pause: 'batch_copied@pages', label: 'mid-table (first committed batch of pages)' }
+ : b === 'table_copied' ? { pause: 'table_copied@pages', label: 'table boundary (pages committed)' }
+ : { pause: b, label: b });
+
+describe.skipIf(!DATABASE_URL)('graduation: SIGKILL at every custody boundary', () => {
+ for (const { pause, label } of RUN_KILLS) {
+ graduationTest(`kill at ${label}: at most one writer, status read-only, clean-process resume graduates`, async () => {
+ const c = await fresh(`kill-${pause.replace(/[@]/g, '-')}`);
+ await killAt(c, pause, ['--batch-size', '2']);
+ expect(readEvents(c.events).filter(e => e.event === 'boundary').at(-1)?.boundary).toBe(pause.split('@')[0]);
+ await expectAtMostOneWriter(c, `after kill at ${pause}`);
+
+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });
+ expect(status.code).toBe(0);
+ expect(stateOf(status.json)).not.toBe('graduated');
+
+ // No target URL in the environment: resume reads the 0600 manifest's recorded identities.
+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, env: { [TARGET_ENV]: undefined }, timeoutMs: 900_000 });
+ expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+ await expectGraduated(c, `kill at ${pause}`);
+ }, 900_000);
+ }
+
+ graduationTest('kill after authority, a target client writes before the routing flip, resume keeps the write and finishes routing', async () => {
+ const c = await fresh('first-write-before-flip');
+ await killAt(c, 'authoritative');
+ expect(configuredEngine(c.fx).engine).toBe('pglite');
+ const a = await authority(c);
+ expect({ source: a.source, target: a.target }).toEqual({ source: false, target: true });
+ // Another client already configured with the target URL (a second machine) writes first.
+ const other = `${c.fx.dir}/other-client`;
+ const put = await gbrain(['put', 'notes/first-post-cutover', '--source', 'default'],
+ { home: other, env: { GBRAIN_DATABASE_URL: c.target.url }, stdin: '---\ntype: note\ntitle: First post-cutover write\n---\n\nWritten on the target before routing flipped.\n' });
+ expect({ code: put.code, stderr: put.code === 0 ? '' : put.stderr.slice(-2000) }).toEqual({ code: 0, stderr: '' });
+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 });
+ expect(resumed.code).toBe(0);
+ expect(configuredEngine(c.fx).engine).toBe('postgres');
+ await withTarget(c.target.url, async t => {
+ const [page] = await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id='default' AND slug='notes/first-post-cutover' AND deleted_at IS NULL`);
+ expect(Number(page.n)).toBe(1);
+ });
+ }, 900_000);
+
+ graduationTest('SIGKILL right after the first post-cutover write commits: the write survives, rollback lists it as user data', async () => {
+ const c = await fresh('first-write-kill');
+ await graduate(c);
+ const writer = startGbrain(['put', 'notes/killed-after-commit', '--source', 'default'],
+ { home: c.fx.home, stdin: '---\ntype: note\ntitle: Killed after commit\n---\n\nCommitted, then the writer died.\n' });
+ const deadline = Date.now() + 120_000;
+ for (;;) {
+ const committed = await withTarget(c.target.url, t => t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests
+ WHERE slug='notes/killed-after-commit' AND state='committed'`));
+ if (Number(committed[0].n) === 1) break;
+ if (Date.now() > deadline) throw new Error('the post-cutover write never committed');
+ await Bun.sleep(10);
+ }
+ writer.kill('SIGKILL');
+ await writer.exited;
+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });
+ expect(stateOf(status.json)).toBe('graduated');
+ const refused = await gbrain(['migrate', '--rollback-to-source', '--json'], { home: c.fx.home });
+ expect(refused.code).toBe(3);
+ expect(codeOf(refused.json)).toBe('graduation_rollback_writes_lost');
+ expect(fixOf(refused.json)?.next).toBe('ask_user');
+ expect(JSON.stringify(refused.json)).toContain('pages');
+ // The refusal returned the target to authority; a normal client still writes.
+ expect(await targetRowState(c.target.url)).toBe('authoritative');
+ const put = await gbrain(['put', 'notes/after-refusal', '--source', 'default'], { home: c.fx.home, stdin: 'after refusal\n' });
+ expect(put.code).toBe(0);
+ }, 900_000);
+});
+
+describe.skipIf(!DATABASE_URL)('graduation: SIGKILL at every rollback substep', () => {
+ for (const boundary of GRADUATION_ROLLBACK_BOUNDARIES) {
+ graduationTest(`kill at ${boundary}: reconciliation ${boundary === 'rollback_fenced' ? 'restores target authority' : 'rolls forward to the source'}`, async () => {
+ const c = await fresh(`rollback-${boundary}`);
+ await graduate(c);
+ await killRollbackAt(c, boundary);
+ await expectAtMostOneWriter(c, `after kill at ${boundary}`);
+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });
+ expect(status.code).toBe(0);
+
+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 });
+ expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+ const a = await authority(c);
+ if (boundary === 'rollback_fenced') {
+ // Not yet approved: the live brain stays on the target.
+ expect({ source: a.source, target: a.target }).toEqual({ source: false, target: true });
+ expect(configuredEngine(c.fx).engine).toBe('postgres');
+ const put = await gbrain(['put', 'notes/after-fenced-crash', '--source', 'default'], { home: c.fx.home, stdin: 'still live\n' });
+ expect(put.code).toBe(0);
+ } else {
+ // Approved: never back to target authority; the source is live again.
+ expect({ source: a.source, target: a.target }).toEqual({ source: true, target: false });
+ expect(configuredEngine(c.fx).engine).toBe('pglite');
+ expect(await targetFenceTriggers(c.target.url)).toBeGreaterThan(0);
+ expect(manifestState(c.fx)).toBe('rolled_back');
+ const put = await gbrain(['put', 'notes/after-rollback', '--source', 'default'], { home: c.fx.home, stdin: 'back on pglite\n' });
+ expect(put.code).toBe(0);
+ await withSource(c.fx, async source => {
+ const [row] = await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE slug IN ('notes/queued-request','notes/after-rollback')`);
+ expect(Number(row.n)).toBe(2);
+ });
+ }
+ }, 900_000);
+ }
+
+ graduationTest('a target fact withdrawal or token revocation makes rollback refuse finally, even with --yes', async () => {
+ const c = await fresh('rollback-security');
+ await graduate(c);
+ const revoke = await gbrain(['auth', 'revoke', 'legacy-fixture-live'], { home: c.fx.home });
+ expect(revoke.code).toBe(0);
+ const { first } = await rollback(c, { confirm: false });
+ expect(first.code).toBe(1);
+ expect(codeOf(first.json)).toBe('graduation_rollback_writes_lost');
+ expect(fixOf(first.json)?.next).toBe('report');
+ const forced = await gbrain(['migrate', '--rollback-to-source', '--yes', '--expect', 'any', '--json'], { home: c.fx.home });
+ expect(forced.code).not.toBe(0);
+ expect(await targetRowState(c.target.url)).toBe('authoritative');
+ expect(await targetFenceTriggers(c.target.url)).toBe(0);
+ expect(configuredEngine(c.fx).engine).toBe('postgres');
+ }, 900_000);
+
+ graduationTest('rollback with no post-cutover writes restores the source exactly and leaves the target fenced', async () => {
+ const c = await fresh('rollback-clean');
+ await graduate(c);
+ const { first, confirmed } = await rollback(c);
+ expect((confirmed ?? first).code).toBe(0);
+ const a = await authority(c);
+ expect({ source: a.source, target: a.target }).toEqual({ source: true, target: false });
+ expect(await targetFenceTriggers(c.target.url)).toBeGreaterThan(0);
+ const blocked = await withTarget(c.target.url, t => t.executeRaw(`INSERT INTO config(key,value) VALUES('graduation.stray','x')`).then(() => 'written', e => String(e)));
+ expect(blocked).toContain('graduation');
+ }, 900_000);
+});
+
diff --git a/test/e2e/graduation-faults.test.ts b/test/e2e/graduation-faults.test.ts
new file mode 100644
index 0000000000..d267a9b73f
--- /dev/null
+++ b/test/e2e/graduation-faults.test.ts
@@ -0,0 +1,148 @@
+/**
+ * Engine graduation under target faults: disk full mid-copy, a password
+ * rotated between the run and `--resume`, and a DDL route that names another
+ * database.
+ *
+ * Protects: §13 Eng "Extra tests" and "Dual target routes", §13 DX "Secrets
+ * never leave the private files". A target that runs out of space mid-copy
+ * stops with the source untouched and authoritative, and `--resume` after
+ * space returns finishes with verify green. A rotated password refuses with
+ * `graduation_target_auth_failed` (ask_user, rerun with `--url-env`), the new
+ * URL for the same identity resumes, and no stdout, stderr, JSON document,
+ * marker or tombstone byte ever contains either password.
+ * Regressions it catches: a copy that commits partial tables as complete,
+ * a resume that treats the same database as a new target after rotation
+ * (identity hash including the password), a password echoed into fix argv,
+ * or DDL issued through a route that was never proven to be the same database.
+ * Not covered elsewhere: no other suite fills a real Postgres disk.
+ * The ENOSPC case starts its own pgvector/pgvector:pg16 container with a
+ * 64 MiB tmpfs tablespace and needs Docker; it is skipped visibly without it.
+ */
+import { afterAll, describe, expect } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { rmSync } from 'node:fs';
+import postgres from '#postgres';
+import {
+ codeOf, DATABASE_URL, fixOf, gbrain, graduationTest, graduationTestIf, hostedRoleTarget, passwordLeaks, passwordOf, startGbrain, stateOf,
+ TARGET_ENV, release, waitForEvent, type GbrainResult, type TargetDb,
+} from '../helpers/graduation-e2e.ts';
+import { authority, expectGraduated, legacyCase, planAndRun, scratchRoot, targetRowState, type Case } from '../helpers/graduation-scenarios.ts';
+
+const cleanups: (() => Promise<void>)[] = [];
+afterAll(async () => {
+ for (const cleanup of cleanups.reverse()) await cleanup().catch(() => {});
+ rmSync(scratchRoot, { recursive: true, force: true });
+});
+
+const docker = (...args: string[]) => {
+ const r = Bun.spawnSync(['docker', ...args], { stdout: 'pipe', stderr: 'pipe' });
+ return { code: r.exitCode, out: r.stdout.toString().trim(), err: r.stderr.toString() };
+};
+const dockerAvailable = !!Bun.which('docker') && docker('info', '--format', '{{.ServerVersion}}').code === 0;
+
+/** A disposable pg16 server whose target database lives on a 64 MiB tmpfs tablespace. */
+async function tmpfsTarget(): Promise<TargetDb & { container: string; fill(leaveKb: number): void; drain(): void }> {
+ const container = `gbrain-graduation-enospc-${randomUUID().slice(0, 8)}`;
+ const started = docker('run', '-d', '--name', container, '--tmpfs', '/small:rw,size=64m,mode=1777', '-e', 'POSTGRES_PASSWORD=postgres',
+ '-e', 'POSTGRES_DB=gbrain_test', '-p', '127.0.0.1::5432', 'pgvector/pgvector:pg16');
+ if (started.code !== 0) throw new Error(`docker run: ${started.err}`);
+ cleanups.push(async () => { docker('rm', '-f', container); });
+ const port = docker('port', container, '5432/tcp').out.split(':').pop();
+ for (let i = 0; i < 120 && docker('exec', container, 'pg_isready', '-U', 'postgres').code !== 0; i++) await Bun.sleep(500);
+ await Bun.sleep(1000);
+ docker('exec', '-u', 'postgres', container, 'mkdir', '-p', '/small/ts');
+ const admin = `postgresql://postgres:[email protected]:${port}/gbrain_test`;
+ const database = 'gbrain_test_graduation_enospc';
+ const sql = postgres(admin, { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ await sql.unsafe(`CREATE TABLESPACE small LOCATION '/small/ts'`);
+ await sql.unsafe(`CREATE DATABASE ${database} TABLESPACE small`);
+ } finally { await sql.end(); }
+ return {
+ container, database, admin, url: `postgresql://postgres:[email protected]:${port}/${database}`,
+ fill(leaveKb: number) {
+ const r = docker('exec', container, 'sh', '-c',
+ `avail=$(df -k /small | tail -1 | awk '{print $4}'); fallocate -l $(( (avail - ${leaveKb}) * 1024 )) /small/ballast && df -k /small | tail -1`);
+ if (r.code !== 0) throw new Error(`fill: ${r.err}`);
+ },
+ drain() { docker('exec', container, 'rm', '-f', '/small/ballast'); },
+ close: async () => { docker('rm', '-f', container); },
+ };
+}
+
+describe.skipIf(!DATABASE_URL)('graduation: target faults', () => {
+ graduationTestIf(!dockerAvailable)('ENOSPC mid-copy stops with the source authoritative; resume after space returns graduates', async () => {
+ const target = await tmpfsTarget();
+ const c = await legacyCase('enospc', target);
+ const { argv, env } = await planAndRun(c);
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['target_fenced'] } });
+ const paused = await waitForEvent(c.events, e => e.event === 'paused', child);
+ target.fill(128);
+ release(c.events, paused.ordinal!);
+ const failed = await child.exited;
+ expect(failed.code).not.toBe(0);
+ expect(`${failed.stdout}${failed.stderr}`).toMatch(/No space left on device|disk_full|53100|could not extend/i);
+ const a = await authority(c);
+ expect(a.target).toBe(false);
+ expect(['copying', 'verify_failed', null]).toContain(await targetRowState(c.target.url));
+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });
+ expect(status.code).toBe(0);
+ expect(stateOf(status.json)).not.toBe('graduated');
+
+ target.drain();
+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 900_000 });
+ expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+ await expectGraduated(c, 'after ENOSPC resume');
+ }, 900_000);
+
+ graduationTest('password rotated between the run and --resume: typed refusal, then --url-env resumes; no byte leaks either password', async () => {
+ const hosted = await hostedRoleTarget();
+ cleanups.push(() => hosted.close());
+ const c = await legacyCase('rotation', hosted);
+ const oldUrl = hosted.url;
+ const results: GbrainResult[] = [];
+ const { argv, env, plan } = await planAndRun(c, { url: oldUrl });
+ results.push(plan);
+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['table_copied@pages'] } });
+ await waitForEvent(c.events, e => e.event === 'paused', child);
+ child.kill('SIGKILL');
+ results.push(await child.exited);
+
+ const newUrl = await hosted.rotatePassword();
+ const refused = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home });
+ results.push(refused);
+ expect(refused.code).toBe(1);
+ expect(codeOf(refused.json)).toBe('graduation_target_auth_failed');
+ expect(fixOf(refused.json)?.next).toBe('ask_user');
+ expect(JSON.stringify(fixOf(refused.json))).toContain('--url-env');
+
+ const resumed = await gbrain(['migrate', '--resume', '--url-env', TARGET_ENV, '--json'], { home: c.fx.home, env: { [TARGET_ENV]: newUrl }, timeoutMs: 900_000 });
+ results.push(resumed);
+ expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });
+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });
+ results.push(status);
+ await expectGraduated({ ...c, target: { ...hosted, url: newUrl } }, 'after rotation');
+ expect(passwordLeaks(passwordOf(oldUrl), results, c.fx.dir)).toEqual([]);
+ expect(passwordLeaks(passwordOf(newUrl), results, c.fx.dir)).toEqual([]);
+ // The hosted role cannot SET session_replication_role, so the receipt names the fallback.
+ expect(JSON.stringify(status.json)).toContain('disable_trigger');
+ }, 900_000);
+
+ graduationTest('a DDL route that names another database refuses before any DDL', async () => {
+ const c = await legacyCase('ddl-mismatch');
+ const elsewhere = await legacyCase('ddl-elsewhere');
+ cleanups.push(() => c.target.close(), () => elsewhere.target.close());
+ const plan = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--plan', '--json'],
+ { home: c.fx.home, env: { [TARGET_ENV]: c.target.url, GBRAIN_DIRECT_DATABASE_URL: elsewhere.target.url } });
+ const run = plan.code === 0
+ ? await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', String(plan.json?.plan_hash ?? plan.json?.planHash), '--json'],
+ { home: c.fx.home, env: { [TARGET_ENV]: c.target.url, GBRAIN_DIRECT_DATABASE_URL: elsewhere.target.url } })
+ : plan;
+ expect(codeOf(run.json)).toBe('graduation_target_ddl_unreachable');
+ expect(fixOf(run.json)?.next).toBe('ask_user');
+ expect(await targetRowState(c.target.url)).toBeNull();
+ expect(await targetRowState(elsewhere.target.url)).toBeNull();
+ const a = await authority(c);
+ expect(a.source).toBe(true);
+ }, 600_000);
+});
diff --git a/test/helpers/graduation-e2e.ts b/test/helpers/graduation-e2e.ts
new file mode 100644
index 0000000000..b6be8ddc81
--- /dev/null
+++ b/test/helpers/graduation-e2e.ts
@@ -0,0 +1,431 @@
+/**
+ * Shared machinery for the engine graduation E2E suites (PGLite -> Postgres).
+ *
+ * Everything drives the real CLI (`bun src/cli.ts migrate ...`) in child
+ * processes with an isolated HOME/GBRAIN_HOME, so the CLI's own connect path,
+ * kernel lock and exit codes are what the tests observe. Crash and pause
+ * points come from test/helpers/graduation-hooks-preload.ts, loaded with
+ * `bun --preload`, which stops the child at a named custody boundary.
+ *
+ * Contract reads (plan hash, code, fix argv, state) go through the accessors
+ * below so a field-name change in the CLI's JSON is fixed in one place.
+ */
+import { test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { existsSync, lstatSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+
+export const REPO = resolve(import.meta.dir, '..', '..');
+export const CLI = join(REPO, 'src', 'cli.ts');
+export const PRELOAD = join(REPO, 'test', 'helpers', 'graduation-hooks-preload.ts');
+
+/**
+ * Graduation lands in parallel lanes (G2a orchestrator, G3 CLI). Until the
+ * orchestrator module exists, suites that need it register as `test.todo`
+ * (visible in every report, never silently skipped). Infrastructure checks
+ * that need only Postgres run either way.
+ */
+export const GRADUATION_LANDED = existsSync(join(REPO, 'src', 'core', 'persistence', 'engine-graduation.ts'));
+export const graduationTest: typeof test = GRADUATION_LANDED ? test : (test.todo as unknown as typeof test);
+/** `graduationTest` with an extra visible skip condition (e.g. Docker unavailable). */
+export function graduationTestIf(skip: boolean): typeof test {
+ return GRADUATION_LANDED ? test.skipIf(skip) as typeof test : graduationTest;
+}
+export const DATABASE_URL = process.env.DATABASE_URL;
+
+const PROVIDER_KEYS = /^(OPENAI|ANTHROPIC|VOYAGE|GEMINI|GOOGLE|TYPESAFE|JEV_TYPESAFE|OPENROUTER|GROQ|MISTRAL|COHERE|DEEPSEEK|XAI)_/;
+
+export interface GbrainResult { code: number; signal: string | null; stdout: string; stderr: string; json: Record<string, any> | null; ms: number }
+export interface GbrainOpts {
+ home: string;
+ env?: Record<string, string | undefined>;
+ timeoutMs?: number;
+ /** Load the boundary-hook preload; `pause` names boundaries to stop at. */
+ hooks?: { events: string; pause?: string[] };
+ stdin?: string;
+ /** Run another binary (an older release) instead of `bun src/cli.ts`. */
+ binary?: string;
+}
+
+function childEnv(opts: GbrainOpts): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !PROVIDER_KEYS.test(k)) env[k] = v;
+ delete env.DATABASE_URL; delete env.GBRAIN_DATABASE_URL; delete env.GBRAIN_DIRECT_DATABASE_URL; delete env.GBRAIN_REMOTE_CLIENT_SECRET;
+ Object.assign(env, { HOME: opts.home, GBRAIN_HOME: opts.home, GBRAIN_SKIP_STARTUP_HOOKS: '1', NO_COLOR: '1' });
+ if (opts.hooks) {
+ env.GBRAIN_TEST_GRADUATION_EVENTS = opts.hooks.events;
+ env.GBRAIN_TEST_GRADUATION_PAUSE = (opts.hooks.pause ?? []).join(',');
+ }
+ for (const [k, v] of Object.entries(opts.env ?? {})) { if (v === undefined) delete env[k]; else env[k] = v; }
+ return env;
+}
+
+function command(argv: string[], opts: GbrainOpts): string[] {
+ if (opts.binary) return [opts.binary, ...argv];
+ return [process.execPath, '--no-env-file', ...(opts.hooks ? ['--preload', PRELOAD] : []), CLI, ...argv];
+}
+
+/** The last top-level JSON document on stdout (the `--json` contract prints exactly one). */
+export function jsonDoc(stdout: string): Record<string, any> | null {
+ const text = stdout.trim();
+ if (!text) return null;
+ try { return JSON.parse(text); } catch {}
+ const start = text.lastIndexOf('\n{');
+ try { return JSON.parse(start >= 0 ? text.slice(start + 1) : text); } catch { return null; }
+}
+
+export interface GbrainChild {
+ pid: number;
+ exited: Promise<GbrainResult>;
+ kill(signal?: NodeJS.Signals): void;
+}
+
+export function startGbrain(argv: string[], opts: GbrainOpts): GbrainChild {
+ const started = Date.now();
+ const child = Bun.spawn(command(argv, opts), { cwd: REPO, env: childEnv(opts), stdin: opts.stdin === undefined ? 'ignore' : new TextEncoder().encode(opts.stdin),
+ stdout: 'pipe', stderr: 'pipe' });
+ const timer = setTimeout(() => child.kill('SIGKILL'), opts.timeoutMs ?? 600_000);
+ const exited = (async () => {
+ const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
+ await child.exited;
+ clearTimeout(timer);
+ return { code: child.exitCode ?? -1, signal: child.signalCode ?? null, stdout, stderr, json: jsonDoc(stdout), ms: Date.now() - started };
+ })();
+ return { pid: child.pid, exited, kill: (signal = 'SIGKILL') => { if (child.exitCode === null) child.kill(signal); } };
+}
+
+export async function gbrain(argv: string[], opts: GbrainOpts): Promise<GbrainResult> {
+ return startGbrain(argv, opts).exited;
+}
+
+// ── Boundary events ───────────────────────────────────────────────────────────
+
+export interface BoundaryEvent { event: 'boundary' | 'paused' | 'released'; boundary: string; detail: Record<string, unknown>; pid: number; at: number; ordinal?: number }
+
+export function readEvents(path: string): BoundaryEvent[] {
+ if (!existsSync(path)) return [];
+ return readFileSync(path, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line));
+}
+
+/** Wait for a `paused` event (or any event matching `match`) while the child lives. */
+export async function waitForEvent(path: string, match: (e: BoundaryEvent) => boolean, child: GbrainChild, timeoutMs = 300_000): Promise<BoundaryEvent> {
+ const deadline = Date.now() + timeoutMs;
+ let done = false;
+ let result: GbrainResult | null = null;
+ child.exited.then(r => { done = true; result = r; });
+ for (;;) {
+ const hit = readEvents(path).find(match);
+ if (hit) return hit;
+ if (done) throw new Error(`child exited (${result!.code}/${result!.signal}) before the expected boundary\nstdout:${result!.stdout.slice(-2000)}\nstderr:${result!.stderr.slice(-4000)}`);
+ if (Date.now() > deadline) throw new Error(`timed out waiting for a boundary in ${path}`);
+ await Bun.sleep(25);
+ }
+}
+
+export function release(path: string, ordinal: number): void {
+ writeFileSync(`${path}.release.${ordinal}`, '');
+}
+
+// ── Contract accessors (one place to fix if the CLI's JSON names move) ───────
+
+export const planHashOf = (doc: Record<string, any> | null): string | undefined =>
+ doc?.plan_hash ?? doc?.planHash ?? doc?.plan?.plan_hash ?? doc?.plan?.planHash ?? doc?.data?.plan_hash;
+export const codeOf = (doc: Record<string, any> | null): string | undefined => doc?.code ?? doc?.error?.code ?? doc?.error;
+export const fixOf = (doc: Record<string, any> | null): Record<string, any> | undefined => doc?.fix ?? doc?.error?.fix;
+export const stateOf = (doc: Record<string, any> | null): string | undefined =>
+ doc?.state ?? doc?.graduation?.state ?? doc?.manifest?.state ?? doc?.status?.state;
+
+// ── Postgres targets ──────────────────────────────────────────────────────────
+
+export interface TargetDb { url: string; database: string; admin: string; close(): Promise<void> }
+
+function withDatabase(url: string, database: string, user?: { name: string; password: string }): string {
+ const u = new URL(url);
+ u.pathname = `/${database}`;
+ if (user) { u.username = user.name; u.password = user.password; }
+ return u.toString();
+}
+
+/** A brand-new empty database (no gbrain schema) on the E2E server. */
+export async function emptyTarget(adminUrl = DATABASE_URL!): Promise<TargetDb> {
+ assertSafeE2eDatabaseUrl(adminUrl);
+ const database = `gbrain_test_graduation_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
+ const admin = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try { await admin.unsafe(`CREATE DATABASE ${database}`); } finally { await admin.end(); }
+ return { url: withDatabase(adminUrl, database), database, admin: adminUrl, close: () => dropDatabase(adminUrl, database) };
+}
+
+export async function dropDatabase(adminUrl: string, database: string): Promise<void> {
+ const admin = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); } finally { await admin.end(); }
+}
+
+/**
+ * A hosted-style target: a NOSUPERUSER LOGIN role that owns an empty database
+ * whose `vector` extension the administrator created (as managed providers
+ * do). The role cannot `SET session_replication_role`, so the copy must use
+ * the `DISABLE TRIGGER USER` fallback.
+ */
+export async function hostedRoleTarget(adminUrl = DATABASE_URL!): Promise<TargetDb & { role: string; rotatePassword(): Promise<string> }> {
+ assertSafeE2eDatabaseUrl(adminUrl);
+ const suffix = randomUUID().replace(/-/g, '').slice(0, 16);
+ const role = `gbrain_hosted_${suffix}`;
+ const database = `gbrain_test_graduation_hosted_${suffix}`;
+ let password = `hosted-${randomUUID()}`;
+ const admin = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ await admin.unsafe(`CREATE ROLE ${role} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '${password}'`);
+ await admin.unsafe(`CREATE DATABASE ${database} OWNER ${role}`);
+ } finally { await admin.end(); }
+ const owned = postgres(withDatabase(adminUrl, database), { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ await owned.unsafe('CREATE EXTENSION IF NOT EXISTS vector');
+ await owned.unsafe('CREATE EXTENSION IF NOT EXISTS pg_trgm');
+ await owned.unsafe(`GRANT ALL ON SCHEMA public TO ${role}`);
+ } finally { await owned.end(); }
+ return {
+ role, database, admin: adminUrl,
+ get url() { return withDatabase(adminUrl, database, { name: role, password }); },
+ async rotatePassword() {
+ password = `rotated-${randomUUID()}`;
+ const a = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try { await a.unsafe(`ALTER ROLE ${role} PASSWORD '${password}'`); } finally { await a.end(); }
+ return withDatabase(adminUrl, database, { name: role, password });
+ },
+ async close() {
+ await dropDatabase(adminUrl, database);
+ const a = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try { await a.unsafe(`DROP ROLE IF EXISTS ${role}`); } finally { await a.end(); }
+ },
+ } as TargetDb & { role: string; rotatePassword(): Promise<string> };
+}
+
+/** The same database reached through the transaction-mode pooler (GBRAIN_PGBOUNCER_URL), or null when no pooler is configured. */
+export function pooledUrl(target: TargetDb): string | null {
+ const pooler = process.env.GBRAIN_PGBOUNCER_URL;
+ return pooler ? withDatabase(pooler, target.database) : null;
+}
+
+// ── Zero-mutation digests ─────────────────────────────────────────────────────
+
+export interface StateDigest { files: Record<string, string>; target: Record<string, string> }
+
+function digestFiles(root: string, out: Record<string, string>): void {
+ if (!existsSync(root)) return;
+ const info = lstatSync(root);
+ if (info.isSymbolicLink()) { out[root] = `link`; return; }
+ if (info.isFile()) { out[root] = `${info.mode.toString(8)}:${createHash('sha256').update(readFileSync(root)).digest('hex')}`; return; }
+ if (!info.isDirectory()) return;
+ out[root] = `dir:${info.mode.toString(8)}`;
+ for (const name of readdirSync(root).sort()) digestFiles(join(root, name), out);
+}
+
+/**
+ * Every file under the fixture directory (home, config, manifest, intent
+ * marker, tombstone, data dir and its siblings) plus, when a target URL is
+ * given, every target relation's rows, sequences and trigger enablement.
+ */
+export async function stateDigest(fixtureDir: string, targetUrl?: string): Promise<StateDigest> {
+ const files: Record<string, string> = {};
+ digestFiles(fixtureDir, files);
+ const target: Record<string, string> = {};
+ if (targetUrl) {
+ const sql = postgres(targetUrl, { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ const relations = await sql.unsafe<{ name: string; kind: string }[]>(`SELECT c.relname AS name, c.relkind::text AS kind FROM pg_class c
+ JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind IN ('r','S','v') ORDER BY c.relname COLLATE "C"`);
+ target['@relations'] = relations.map((r: { name: string; kind: string }) => `${r.kind}:${r.name}`).join(',');
+ for (const r of relations) {
+ if (r.kind === 'v') continue;
+ const [row] = r.kind === 'S'
+ ? await sql.unsafe(`SELECT last_value::text || ':' || is_called::text AS d FROM "${r.name}"`)
+ : await sql.unsafe(`SELECT count(*)::text || ':' || md5(coalesce(string_agg(t::text, E'\\n' ORDER BY t::text COLLATE "C"), '')) AS d FROM "${r.name}" t`);
+ target[r.name] = String(row.d);
+ }
+ const triggers = await sql.unsafe<{ d: string }[]>(`SELECT c.relname || '.' || t.tgname || '=' || t.tgenabled::text AS d FROM pg_trigger t
+ JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND NOT t.tgisinternal ORDER BY 1`);
+ target['@triggers'] = triggers.map((t: { d: string }) => t.d).join(',');
+ } catch (error) {
+ if ((error as { code?: string }).code !== '3D000') throw error;
+ target['@database'] = 'absent';
+ } finally { await sql.end(); }
+ }
+ return { files, target };
+}
+
+export function digestChanges(before: StateDigest, after: StateDigest): string[] {
+ const changes: string[] = [];
+ for (const side of ['files', 'target'] as const) {
+ const keys = new Set([...Object.keys(before[side]), ...Object.keys(after[side])]);
+ for (const key of [...keys].sort()) if (before[side][key] !== after[side][key]) changes.push(`${side} ${key}: ${before[side][key] ?? '(absent)'} -> ${after[side][key] ?? '(absent)'}`);
+ }
+ return changes;
+}
+
+// ── Common flows ──────────────────────────────────────────────────────────────
+
+export const TARGET_ENV = 'GBRAIN_TARGET_URL';
+
+/** The two-command agent flow: plan (exit 3, ask_user) then `--yes --expect <hash>`. */
+export async function graduateViaAgentFlow(home: string, url: string, opts: { extra?: string[]; env?: Record<string, string>; hooks?: GbrainOpts['hooks'] } = {}) {
+ const env = { [TARGET_ENV]: url, ...opts.env };
+ const plan = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--json', ...(opts.extra ?? [])], { home, env });
+ const hash = planHashOf(plan.json);
+ const run = hash ? await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', hash, '--json', ...(opts.extra ?? [])],
+ { home, env, hooks: opts.hooks, timeoutMs: 1_800_000 }) : null;
+ return { plan, hash, run };
+}
+
+/** Assert no output byte names the target password (stdout, stderr, files under the fixture except the 0600 manifest and config). */
+export function passwordLeaks(password: string, results: GbrainResult[], fixtureDir: string): string[] {
+ const leaks: string[] = [];
+ for (const [i, r] of results.entries()) {
+ if (r.stdout.includes(password)) leaks.push(`result ${i} stdout`);
+ if (r.stderr.includes(password)) leaks.push(`result ${i} stderr`);
+ }
+ const allowed = new Set(['graduation-manifest.json', 'config.json']);
+ const walk = (dir: string) => {
+ if (!existsSync(dir)) return;
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ const info = lstatSync(path);
+ if (info.isDirectory()) { if (!name.endsWith('.pglite') && !name.includes('.graduated-') && name !== '.git') walk(path); continue; }
+ if (!info.isFile() || info.size > 4 * 1024 * 1024 || allowed.has(name)) continue;
+ if (readFileSync(path).includes(password)) leaks.push(path);
+ }
+ };
+ walk(fixtureDir);
+ return leaks;
+}
+
+export function passwordOf(url: string): string {
+ return decodeURIComponent(new URL(url).password);
+}
+
+/** Sibling paths of a data dir that graduation custody creates. */
+export function custodyPaths(dataDir: string) {
+ const parent = dirname(dataDir);
+ const name = dataDir.slice(parent.length + 1);
+ const graduated = existsSync(parent) ? readdirSync(parent).filter(n => n.startsWith(`${name}.graduated-`)).map(n => join(parent, n)) : [];
+ return {
+ marker: `${dataDir}.gbrain-graduation.json`,
+ graduated,
+ tombstone: existsSync(dataDir) && statSync(dataDir).isFile() ? dataDir : null,
+ dataDirIsDirectory: existsSync(dataDir) && statSync(dataDir).isDirectory(),
+ };
+}
+
+export function manifestPath(home: string): string {
+ return join(home, '.gbrain', 'graduation-manifest.json');
+}
+
+// ── Older released binaries ───────────────────────────────────────────────────
+
+/** The last `count` release tags at or below this checkout's VERSION, newest first (from origin). */
+export function previousReleaseTags(count = 2): string[] {
+ const version = readFileSync(join(REPO, 'VERSION'), 'utf8').trim();
+ const out = Bun.spawnSync(['git', '-C', REPO, 'ls-remote', '--tags', '--refs', 'origin', 'v*'], { stdout: 'pipe', stderr: 'pipe' });
+ if (out.exitCode !== 0) throw new Error(`git ls-remote failed: ${out.stderr.toString()}`);
+ const parse = (tag: string) => tag.slice(1).split('.').map(Number);
+ const cmp = (a: number[], b: number[]) => { for (let i = 0; i < Math.max(a.length, b.length); i++) { const d = (a[i] ?? 0) - (b[i] ?? 0); if (d) return d; } return 0; };
+ const current = version.split('.').map(Number);
+ return out.stdout.toString().split('\n').map(line => line.split('refs/tags/')[1]).filter((t): t is string => !!t && /^v\d+(\.\d+){3}$/.test(t))
+ .filter(t => cmp(parse(t), current) <= 0).sort((a, b) => cmp(parse(b), parse(a))).slice(0, count);
+}
+
+/**
+ * A compiled binary of an older release, built once per tag into the cache
+ * (`GBRAIN_OLDER_RELEASE_DIR`, default ~/.cache/gbrain-older-releases).
+ * `GBRAIN_OLDER_RELEASE_BIN_<tag with dots as underscores>` points at a prebuilt one.
+ */
+export function olderReleaseBinary(tag: string): string {
+ const preset = process.env[`GBRAIN_OLDER_RELEASE_BIN_${tag.replace(/\./g, '_')}`];
+ if (preset) return preset;
+ const cache = process.env.GBRAIN_OLDER_RELEASE_DIR || join(process.env.HOME ?? '/tmp', '.cache', 'gbrain-older-releases');
+ const tree = join(cache, tag);
+ const binary = join(tree, 'bin', 'gbrain');
+ if (existsSync(binary)) return binary;
+ const run = (argv: string[], cwd = REPO) => {
+ const r = Bun.spawnSync(argv, { cwd, stdout: 'pipe', stderr: 'pipe' });
+ if (r.exitCode !== 0) throw new Error(`${argv.join(' ')}: ${r.stderr.toString().slice(-2000)}`);
+ };
+ run(['git', 'fetch', '-q', 'origin', 'tag', tag, '--no-tags']);
+ if (!existsSync(tree)) run(['git', 'worktree', 'add', '-q', '--detach', tree, tag]);
+ run([process.execPath, 'install', '--frozen-lockfile', '--ignore-scripts'], tree);
+ run([process.execPath, 'build', '--compile', '--no-compile-autoload-bunfig', '--outfile', 'bin/gbrain', 'src/cli.ts'], tree);
+ return binary;
+}
+
+// ── MCP clients ───────────────────────────────────────────────────────────────
+
+function parseRpc(text: string): Record<string, any> {
+ const data = text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).pop();
+ return JSON.parse(data ?? text);
+}
+
+/** One stateless JSON-RPC tools/call against `gbrain serve --http`. */
+export async function mcpHttpCall(base: string, token: string, tool: string, args: Record<string, unknown> = {}): Promise<{ status: number; rpc: Record<string, any> | null }> {
+ const res = await fetch(`${base}/mcp`, { method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }) });
+ const text = await res.text();
+ let rpc: Record<string, any> | null = null;
+ try { rpc = parseRpc(text); } catch {}
+ return { status: res.status, rpc };
+}
+
+export interface StdioSession {
+ /** Resolves with the JSON-RPC response, or with null when serve exited first. */
+ call(tool: string, args?: Record<string, unknown>): Promise<Record<string, any> | null>;
+ close(): Promise<GbrainResult>;
+ exited: Promise<GbrainResult>;
+}
+
+/** `gbrain serve` over stdio, initialized, as an MCP host would launch it. */
+export async function mcpStdioSession(opts: GbrainOpts & { argv?: string[] }): Promise<StdioSession> {
+ const started = Date.now();
+ const child = Bun.spawn(command(['serve', ...(opts.argv ?? [])], opts), { cwd: REPO, env: childEnv(opts), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ const pending = new Map<number, (value: Record<string, any> | null) => void>();
+ let stdout = '';
+ let id = 0;
+ const reading = (async () => {
+ const decoder = new TextDecoder();
+ for await (const chunk of child.stdout) {
+ stdout += decoder.decode(chunk);
+ let nl: number;
+ while ((nl = stdout.indexOf('\n')) >= 0) {
+ const line = stdout.slice(0, nl); stdout = stdout.slice(nl + 1);
+ try { const msg = JSON.parse(line); pending.get(msg.id)?.(msg); pending.delete(msg.id); } catch {}
+ }
+ }
+ })();
+ const exited = (async () => {
+ const stderr = await new Response(child.stderr).text();
+ await child.exited; await reading;
+ for (const resolve of pending.values()) resolve(null);
+ return { code: child.exitCode ?? -1, signal: child.signalCode ?? null, stdout, stderr, json: jsonDoc(stdout), ms: Date.now() - started };
+ })();
+ const send = (method: string, params: Record<string, unknown>): Promise<Record<string, any> | null> => {
+ const n = ++id;
+ const reply = new Promise<Record<string, any> | null>(resolve => pending.set(n, resolve));
+ try { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: n, method, params })}\n`); child.stdin.flush(); } catch { pending.get(n)?.(null); }
+ return reply;
+ };
+ const init = await Promise.race([send('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'graduation-e2e', version: '1' } }), exited.then(() => null)]);
+ if (init) { try { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`); child.stdin.flush(); } catch {} }
+ return {
+ call: (tool, args = {}) => Promise.race([send('tools/call', { name: tool, arguments: args }), exited.then(() => null)]),
+ async close() { try { child.stdin.end(); } catch {} const t = setTimeout(() => child.kill('SIGKILL'), 10_000); const r = await exited; clearTimeout(t); return r; },
+ exited,
+ };
+}
+
+/** A free TCP port on loopback. */
+export function freePort(): number {
+ const server = Bun.listen({ hostname: '127.0.0.1', port: 0, socket: { data() {} } });
+ const port = server.port;
+ server.stop(true);
+ return port;
+}
diff --git a/test/helpers/graduation-hooks-preload.ts b/test/helpers/graduation-hooks-preload.ts
new file mode 100644
index 0000000000..29557150f1
--- /dev/null
+++ b/test/helpers/graduation-hooks-preload.ts
@@ -0,0 +1,46 @@
+/**
+ * Bun `--preload` for graduation crash and pause tests. Registers
+ * `GraduationHooks` before the real CLI starts, so the test drives the actual
+ * `gbrain migrate` process and still stops it at an exact custody boundary.
+ *
+ * Environment (set only by test/helpers/graduation-e2e.ts):
+ * - GBRAIN_TEST_GRADUATION_EVENTS: file that receives one JSON line per
+ * boundary reached ({ boundary, detail, pid, at }).
+ * - GBRAIN_TEST_GRADUATION_PAUSE: comma list of `boundary` or
+ * `boundary@relation` entries (`*` pauses at every boundary). On a match
+ * the process writes a `paused` line and blocks until
+ * `<events>.release.<n>` exists (n = the pause ordinal) or it is killed.
+ */
+import { appendFileSync, existsSync } from 'node:fs';
+import { GRADUATION_HOOKS, type GraduationBoundary, type GraduationBoundaryDetail, type GraduationHooks } from '../../src/core/persistence/engine-graduation.types.ts';
+
+const events = process.env.GBRAIN_TEST_GRADUATION_EVENTS;
+const pauses = (process.env.GBRAIN_TEST_GRADUATION_PAUSE ?? '').split(',').map(s => s.trim()).filter(Boolean);
+let ordinal = 0;
+
+function matches(name: GraduationBoundary, detail: GraduationBoundaryDetail): boolean {
+ return pauses.some(entry => {
+ if (entry === '*') return true;
+ const [boundary, relation] = entry.split('@');
+ return boundary === name && (!relation || relation === detail.relation);
+ });
+}
+
+if (events) {
+ const hooks: GraduationHooks = {
+ async boundary(name, detail) {
+ const line = (event: string, extra: Record<string, unknown> = {}) =>
+ appendFileSync(events, `${JSON.stringify({ event, boundary: name, detail, pid: process.pid, at: Date.now(), ...extra })}\n`);
+ line('boundary');
+ if (!matches(name, detail)) return;
+ const n = ++ordinal;
+ line('paused', { ordinal: n });
+ const release = `${events}.release.${n}`;
+ await new Promise<void>(resolve => {
+ const timer = setInterval(() => { if (existsSync(release)) { clearInterval(timer); resolve(); } }, 20);
+ });
+ line('released', { ordinal: n });
+ },
+ };
+ (globalThis as Record<symbol, GraduationHooks>)[GRADUATION_HOOKS] = hooks;
+}
diff --git a/test/helpers/graduation-scenarios.ts b/test/helpers/graduation-scenarios.ts
new file mode 100644
index 0000000000..c9d2ac5fbf
--- /dev/null
+++ b/test/helpers/graduation-scenarios.ts
@@ -0,0 +1,177 @@
+/**
+ * Scenario steps shared by the graduation E2E suites: a fresh legacy fixture
+ * with an empty target, the authority invariant ("at most one engine accepts
+ * writes"), the graduated end state, and the agent-style rollback flow.
+ */
+import { expect } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import postgres from '#postgres';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
+import { admitWrite } from '../../src/core/persistence/journal.ts';
+import { prepareGraduationFixture, type GraduationFixture } from '../../scripts/persistence/graduation-fixture.ts';
+import { legacyTargetMismatches, readQueuedAdmission, snapshotLegacySource, type LegacySourceSnapshot } from '../fixtures/graduation/legacy-brain.ts';
+import { withEnv } from './with-env.ts';
+import {
+ custodyPaths, emptyTarget, gbrain, manifestPath, planHashOf, stateOf, TARGET_ENV, type GbrainOpts, type GbrainResult, type TargetDb,
+} from './graduation-e2e.ts';
+
+export const scratchRoot = mkdtempSync(join(tmpdir(), 'gbrain-graduation-e2e-'));
+const cacheDir = process.env.GBRAIN_GRADUATION_FIXTURE_CACHE || join(scratchRoot, 'fixture-cache');
+let counter = 0;
+
+export interface Case { fx: GraduationFixture; target: TargetDb; before: LegacySourceSnapshot; events: string }
+
+/** A restored legacy fixture, its pre-graduation snapshot and an empty target database. */
+export async function legacyCase(name: string, target?: TargetDb): Promise<Case> {
+ const fx = await prepareGraduationFixture({ kind: 'legacy', dir: join(scratchRoot, `${name}-${++counter}`), cacheDir });
+ const before = await withSource(fx, engine => snapshotLegacySource(engine));
+ return { fx, target: target ?? await emptyTarget(), before, events: join(fx.dir, 'boundary-events.jsonl') };
+}
+
+export async function historyCase(name: string, pages: number, seed = 1): Promise<{ fx: GraduationFixture; target: TargetDb }> {
+ const fx = await prepareGraduationFixture({ kind: 'history', pages, seed, dir: join(scratchRoot, `${name}-${++counter}`), cacheDir, timeoutMs: 45 * 60_000 });
+ return { fx, target: await emptyTarget() };
+}
+
+/** Open the fixture's PGLite source in-process (only while no graduation process holds it). */
+export async function withSource<T>(fx: GraduationFixture, fn: (engine: PGLiteEngine) => Promise<T>, dataDir = fx.dataDir): Promise<T> {
+ return withEnv({ GBRAIN_HOME: fx.home, HOME: fx.home }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ try { return await fn(engine); } finally { await engine.disconnect(); }
+ });
+}
+
+export async function withTarget<T>(url: string, fn: (engine: PostgresEngine) => Promise<T>): Promise<T> {
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: url, poolSize: 2 });
+ try { return await fn(engine); } finally { await engine.disconnect(); }
+}
+
+/** The target's persistence_graduation row state, or null (no table, no row, or no database). */
+export async function targetRowState(url: string): Promise<string | null> {
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ const rows = await sql.unsafe<{ state: string }[]>(`SELECT state FROM persistence_graduation LIMIT 1`);
+ return rows[0]?.state ?? null;
+ } catch { return null; } finally { await sql.end(); }
+}
+
+export async function targetFenceTriggers(url: string): Promise<number> {
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ const [row] = await sql.unsafe<{ n: number }[]>(`SELECT count(*)::int AS n FROM pg_trigger WHERE tgname LIKE 'gbrain_graduation_fence%'`);
+ return Number(row.n);
+ } catch { return 0; } finally { await sql.end(); }
+}
+
+/** Engine routing recorded in the fixture's config.json. */
+export function configuredEngine(fx: GraduationFixture): { engine: string; database_path?: string; database_url?: string } {
+ return JSON.parse(readFileSync(join(fx.home, '.gbrain', 'config.json'), 'utf8'));
+}
+
+/**
+ * Which engines could accept a write right now, read without writing:
+ * the target only when its row is `authoritative` with no fence; the source
+ * only when its data dir is a directory whose source row is not `cutover` and
+ * no graduation intent marker stands in front of it.
+ */
+export async function authority(c: Case): Promise<{ source: boolean; target: boolean; targetState: string | null; sourceState: string | null }> {
+ const targetState = await targetRowState(c.target.url);
+ const target = targetState === 'authoritative' && await targetFenceTriggers(c.target.url) === 0;
+ const paths = custodyPaths(c.fx.dataDir);
+ let sourceState: string | null = null;
+ if (paths.dataDirIsDirectory) {
+ sourceState = await withSource(c.fx, async engine => {
+ try { return (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_graduation LIMIT 1'))[0]?.state ?? null; }
+ catch { return null; }
+ });
+ }
+ const source = paths.dataDirIsDirectory && sourceState !== 'cutover' && !existsSync(paths.marker);
+ return { source, target, targetState, sourceState };
+}
+
+export async function expectAtMostOneWriter(c: Case, label: string): Promise<void> {
+ const a = await authority(c);
+ expect({ label, both: a.source && a.target }).toEqual({ label, both: false });
+}
+
+export function failingChecks(doc: Record<string, any> | null): string[] {
+ return ((doc?.checks ?? []) as { name: string; status: string }[]).filter(c => c.status === 'fail').map(c => c.name);
+}
+
+export async function doctorFailures(home: string): Promise<{ result: GbrainResult; failing: string[] }> {
+ const result = await gbrain(['doctor', '--no-migrate', '--json'], { home, timeoutMs: 300_000 });
+ return { result, failing: failingChecks(result.json) };
+}
+
+/**
+ * The graduated end state: routing on the target, the source tombstoned with
+ * its retained copy, the target authoritative without fence triggers, every
+ * expected.json target expectation, one row per request id, a replay of the
+ * queued request returning the stored outcome, and a green target doctor.
+ */
+export async function expectGraduated(c: Case, label: string): Promise<void> {
+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });
+ expect({ label, code: status.code, state: stateOf(status.json) }).toEqual({ label, code: 0, state: 'graduated' });
+ expect(configuredEngine(c.fx).engine).toBe('postgres');
+ const paths = custodyPaths(c.fx.dataDir);
+ expect({ label, tombstone: paths.tombstone !== null, retained: paths.graduated.length }).toEqual({ label, tombstone: true, retained: 1 });
+ expect(statSync(c.fx.dataDir).mode & 0o777).toBe(0o600);
+ expect(await targetRowState(c.target.url)).toBe('authoritative');
+ expect(await targetFenceTriggers(c.target.url)).toBe(0);
+ await withTarget(c.target.url, async target => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(target) });
+ expect({ label, mismatches: await legacyTargetMismatches(target, c.before, token => provider.verifyAccessToken(token)) }).toEqual({ label, mismatches: [] });
+ const duplicates = await target.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM (SELECT principal_kind,principal_id,request_id
+ FROM persistence_requests GROUP BY 1,2,3 HAVING count(*) > 1) d`);
+ expect(Number(duplicates[0].n)).toBe(0);
+ await expectReplayReturnsStored(target, c.fx);
+ });
+ const doctor = await doctorFailures(c.fx.home);
+ expect({ label, failing: doctor.failing }).toEqual({ label, failing: [] });
+}
+
+/** Resubmit the queued request (recorded with its callerIntent) on the target: stored outcome back, no new row, counters unchanged. */
+export async function expectReplayReturnsStored(target: PostgresEngine, fx: GraduationFixture): Promise<void> {
+ const admission = readQueuedAdmission(fx.root);
+ const counters = async () => (await target.executeRaw<Record<string, unknown>>('SELECT * FROM persistence_counters ORDER BY key COLLATE "C"')).map(r => JSON.stringify(r));
+ const rows = async () => Number((await target.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests'))[0].n);
+ const [stored] = await target.executeRaw<{ id: string; state: string; outcome: Record<string, unknown> | null }>(
+ 'SELECT id::text AS id,state,outcome FROM persistence_requests WHERE request_id=$1::uuid', [admission.requestId]);
+ expect(stored?.state).toBe('committed');
+ const beforeRows = await rows(); const beforeCounters = await counters();
+ const replay = await withEnv({ GBRAIN_HOME: fx.home, HOME: fx.home }, () => admitWrite(target, admission));
+ expect({ id: replay.id, state: replay.state, outcome: replay.outcome }).toEqual({ id: stored.id, state: 'committed', outcome: stored.outcome });
+ expect(await rows()).toBe(beforeRows);
+ expect(await counters()).toEqual(beforeCounters);
+}
+
+/** Run the plan, then the confirmed run, the way an agent would. */
+export async function planAndRun(c: Case, opts: { extra?: string[]; env?: Record<string, string>; hooks?: GbrainOpts['hooks']; url?: string } = {}) {
+ const env = { [TARGET_ENV]: opts.url ?? c.target.url, ...opts.env };
+ const plan = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--plan', '--json', ...(opts.extra ?? [])], { home: c.fx.home, env });
+ expect({ code: plan.code, stderr: plan.code === 0 ? '' : plan.stderr.slice(-2000) }).toEqual({ code: 0, stderr: '' });
+ const hash = planHashOf(plan.json);
+ expect(typeof hash).toBe('string');
+ return { plan, hash: hash!, env, argv: ['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', hash!, '--json', ...(opts.extra ?? [])] };
+}
+
+/** `--rollback-to-source`, confirming once with the hash when the CLI asks (exit 3). */
+export async function rollback(c: Case, opts: { hooks?: GbrainOpts['hooks']; confirm?: boolean } = {}): Promise<{ first: GbrainResult; confirmed: GbrainResult | null }> {
+ const first = await gbrain(['migrate', '--rollback-to-source', '--json'], { home: c.fx.home, hooks: opts.hooks });
+ if (first.code !== 3 || opts.confirm === false) return { first, confirmed: null };
+ const hash = planHashOf(first.json);
+ const confirmed = await gbrain(['migrate', '--rollback-to-source', '--yes', '--expect', String(hash), '--json'], { home: c.fx.home, hooks: opts.hooks });
+ return { first, confirmed };
+}
+
+export function manifestState(fx: GraduationFixture): string | null {
+ const path = manifestPath(fx.home);
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')).state ?? null : null;
+}