Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(graduation): CLI contract suite, time-to-value script, 10k heavy run
garrytan6fb022575f70
diff --git a/scripts/persistence/graduation-process.ts b/scripts/persistence/graduation-process.tsnew file mode 100644index 0000000000..5ebeeb6d84--- /dev/null+++ b/scripts/persistence/graduation-process.ts@@ -0,0 +1,159 @@+/**+ * Child-process plumbing for engine graduation tests and measurements: the+ * real CLI (`bun src/cli.ts`) or another binary with an isolated+ * HOME/GBRAIN_HOME and no provider keys or ambient database URLs, optional+ * boundary hooks (test/helpers/graduation-hooks-preload.ts), MCP stdio and+ * HTTP clients, and the accessors that read the graduation JSON contract.+ * Shared by test/e2e/graduation-*.test.ts and graduation-ttv.ts.+ */+import { join, resolve } from 'node:path';++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');++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;+}++// ── 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;++// ── 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/scripts/persistence/graduation-ttv.ts b/scripts/persistence/graduation-ttv.tsnew file mode 100644index 0000000000..800f74b0f6--- /dev/null+++ b/scripts/persistence/graduation-ttv.ts@@ -0,0 +1,161 @@+/**+ * Time-to-value for engine graduation (PGLite -> Postgres): every command an+ * agent runs from the first `gbrain migrate --to postgres` (which prints the+ * plan and exits 3) to a green `gbrain doctor --no-migrate --json`, with wall+ * time, the run's per-phase timings and query latency on both engines.+ *+ * DATABASE_URL=postgresql://...:5432/gbrain_test \+ * bun scripts/persistence/graduation-ttv.ts --pages 1000 [--seed 1] [--live-serve] [--out report.json] [--enforce]+ * ... --kind legacy the hand-built legacy fixture instead of history pages+ * ... --target-url-env NAME graduate into an existing empty database instead of a fresh one+ *+ * The fixture comes from graduation-fixture.ts (cached; provisioning is+ * excluded from the clock, as is creating the target database). With+ * `--live-serve` a resident `gbrain serve` (stdio) owns the source when the+ * flow starts; the report records whether the run's marker hand-off sufficed+ * or a manual stop was needed (target: none).+ *+ * Gate: 1,000 pages or fewer must reach a green doctor in under five minutes.+ * Larger runs are reported, not gated. Exit codes: 0 report written (and,+ * with --enforce, the gate passed); 1 the gate or an expected exit code+ * failed under --enforce; 2 usage error; 3 the harness itself crashed.+ */+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import postgres from '#postgres';+import { prepareGraduationFixture, type GraduationFixtureKind } from './graduation-fixture.ts';+import { codeOf, gbrain, mcpStdioSession, planHashOf, type GbrainResult } from './graduation-process.ts';++const TARGET_ENV = 'GBRAIN_TARGET_URL';+const GATE_MS = 5 * 60_000;+const TERMS = ['alpha', 'harbor', 'ledger', 'quartz', 'meadow', 'signal', 'copper', 'lantern', 'orbit', 'thistle', 'cobalt', 'drift', 'acme'];++interface Options { kind: GraduationFixtureKind; pages: number; seed: number; liveServe: boolean; out?: string; enforce: boolean; samples: number; targetUrlEnv?: string; keep: boolean }++function parse(argv: string[]): Options {+ const value = (flag: string) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : undefined; };+ const kind = (value('--kind') ?? 'history') as GraduationFixtureKind;+ if (kind !== 'history' && kind !== 'legacy') throw new Error('--kind must be history or legacy');+ const pages = Number(value('--pages') ?? 1000);+ if (kind === 'history' && !(Number.isSafeInteger(pages) && pages >= 1 && pages <= 10_000)) throw new Error('--pages must be 1..10000');+ return { kind, pages, seed: Number(value('--seed') ?? 1), liveServe: argv.includes('--live-serve'), out: value('--out'), enforce: argv.includes('--enforce'),+ samples: Number(value('--query-samples') ?? 50), targetUrlEnv: value('--target-url-env'), keep: argv.includes('--keep') };+}++const redact = (url: string) => { const u = new URL(url); u.password = ''; u.username = u.username ? `${u.username}` : ''; return `${u.protocol}//${u.username}@${u.host}${u.pathname}`; };+function percentile(values: number[], p: number): number { const s = values.toSorted((a, b) => a - b); return s.length ? Number(s[Math.min(s.length - 1, Math.floor(p * s.length))].toFixed(2)) : 0; }++async function queryLatency(engine: import('../../src/core/engine.ts').BrainEngine, samples: number) {+ const times: number[] = [];+ for (const term of TERMS.slice(0, 3)) await engine.searchKeyword(term, { limit: 10 });+ for (let i = 0; i < samples; i++) {+ const started = performance.now();+ await engine.searchKeyword(TERMS[i % TERMS.length], { limit: 10 });+ times.push(performance.now() - started);+ }+ return { samples, p50_ms: percentile(times, 0.5), p95_ms: percentile(times, 0.95) };+}++async function withEnv<T>(env: Record<string, string>, fn: () => Promise<T>): Promise<T> {+ const saved = Object.fromEntries(Object.keys(env).map(k => [k, process.env[k]]));+ Object.assign(process.env, env);+ try { return await fn(); } finally { for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } }+}++async function main(): Promise<number> {+ let opts: Options;+ try { opts = parse(process.argv.slice(2)); } catch (error) { console.error((error as Error).message); return 2; }+ const admin = process.env.DATABASE_URL;+ if (!opts.targetUrlEnv && !admin) { console.error('DATABASE_URL (a test-shaped admin URL) or --target-url-env is required'); return 2; }+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-graduation-ttv-'));+ let database: string | null = null;+ let targetUrl: string;+ if (opts.targetUrlEnv) {+ targetUrl = process.env[opts.targetUrlEnv] ?? '';+ if (!targetUrl) { console.error(`${opts.targetUrlEnv} is empty`); return 2; }+ } else {+ const { assertSafeE2eDatabaseUrl } = await import('../../test/helpers/db-guard.ts');+ assertSafeE2eDatabaseUrl(admin!);+ database = `gbrain_test_graduation_ttv_${randomUUID().replace(/-/g, '').slice(0, 16)}`;+ const sql = postgres(admin!, { max: 1, prepare: false, onnotice: () => {} });+ try { await sql.unsafe(`CREATE DATABASE ${database}`); } finally { await sql.end(); }+ const u = new URL(admin!); u.pathname = `/${database}`; targetUrl = u.toString();+ }+ try {+ const fixture = await prepareGraduationFixture({ kind: opts.kind, pages: opts.pages, seed: opts.seed, dir: join(scratch, 'fixture'), timeoutMs: 45 * 60_000 });+ const home = fixture.home;+ const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const pglite = await withEnv({ GBRAIN_HOME: home, HOME: home }, async () => {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: fixture.dataDir });+ try { return await queryLatency(engine, opts.samples); } finally { await engine.disconnect(); }+ });++ const serve = opts.liveServe ? await mcpStdioSession({ home, timeoutMs: 3_600_000 }) : null;+ if (serve) await serve.call('search', { query: 'alpha' });+ const env = { [TARGET_ENV]: targetUrl };+ const commands: { argv: string[]; exit: number; ms: number; code?: string }[] = [];+ const record = (argv: string[], r: GbrainResult) => { commands.push({ argv: ['gbrain', ...argv], exit: r.code, ms: r.ms, ...(codeOf(r.json) ? { code: codeOf(r.json) } : {}) }); return r; };+ const t0 = Date.now();+ const planArgv = ['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--json'];+ const plan = record(planArgv, await gbrain(planArgv, { home, env, timeoutMs: 600_000 }));+ const hash = planHashOf(plan.json);+ const runArgv = ['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', String(hash), '--json'];+ let run = hash ? record(runArgv, await gbrain(runArgv, { home, env, timeoutMs: 3_600_000 })) : plan;+ let manualStop = false;+ if (serve && codeOf(run.json) === 'graduation_source_writer_held') {+ manualStop = true;+ await serve.close();+ run = record(runArgv, await gbrain(runArgv, { home, env, timeoutMs: 3_600_000 }));+ }+ const doctorArgv = ['doctor', '--no-migrate', '--json'];+ const doctor = record(doctorArgv, await gbrain(doctorArgv, { home, timeoutMs: 600_000 }));+ const wallMs = Date.now() - t0;+ const failing = ((doctor.json?.checks ?? []) as { name: string; status: string }[]).filter(c => c.status === 'fail').map(c => c.name);+ let handoff: Record<string, unknown> | null = null;+ if (serve) {+ const exited = await Promise.race([serve.exited, Bun.sleep(5_000).then(() => null)]);+ handoff = { manual_stop_needed: manualStop, serve_exited: !!exited, serve_refusal: exited ? /graduation_in_progress/.test(`${exited.stdout}${exited.stderr}`) : false };+ if (!exited) await serve.close();+ }++ let postgresLatency = null;+ if (run.code === 0) {+ const { PostgresEngine } = await import('../../src/core/postgres-engine.ts');+ const pg = new PostgresEngine();+ await pg.connect({ database_url: targetUrl, poolSize: 2 });+ try { postgresLatency = await queryLatency(pg, opts.samples); } finally { await pg.disconnect(); }+ }++ const gated = opts.kind === 'legacy' || opts.pages <= 1000;+ const expected = plan.code === 3 && !!hash && run.code === 0 && failing.length === 0;+ const pass = expected && (!gated || wallMs < GATE_MS);+ const report = {+ kind: opts.kind, pages: fixture.report.pages, seed: opts.seed, target: redact(targetUrl),+ label: 'existing brain, provisioned target, plan to green doctor',+ fixture: fixture.report, fixture_cached: fixture.cached,+ commands, wall_ms: wallMs, gate: gated ? { limit_ms: GATE_MS, pass } : { limit_ms: null, pass: expected, note: 'reported, not gated' },+ phases: run.json?.receipt?.timings ?? run.json?.timings ?? null,+ doctor_failing: failing,+ query_latency: { pglite: pglite, postgres: postgresLatency },+ live_serve: handoff,+ };+ const text = JSON.stringify(report, null, 2);+ if (opts.out) writeFileSync(opts.out, `${text}\n`);+ console.log(text);+ if (!expected) console.error(`[graduation-ttv] unexpected outcome: plan exit ${plan.code}, run exit ${run.code}${codeOf(run.json) ? ` (${codeOf(run.json)})` : ''}, failing doctor checks: ${failing.join(', ') || 'none'}\n${run.stderr.slice(-2000)}`);+ return opts.enforce && !pass ? 1 : 0;+ } finally {+ if (database && !opts.keep) {+ const sql = postgres(admin!, { max: 1, prepare: false, onnotice: () => {} });+ try { await sql.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); } finally { await sql.end(); }+ }+ if (!opts.keep) rmSync(scratch, { recursive: true, force: true });+ }+}++if (import.meta.main) {+ main().then(code => process.exit(code), error => { console.error(`[graduation-ttv] harness crashed: ${(error as Error).stack ?? error}`); process.exit(3); });+}diff --git a/test/e2e/graduation-cli.test.ts b/test/e2e/graduation-cli.test.tsnew file mode 100644index 0000000000..ba25bbe57b--- /dev/null+++ b/test/e2e/graduation-cli.test.ts@@ -0,0 +1,293 @@+/**+ * Engine graduation through the agent-operator CLI contract, on Postgres 16,+ * transaction-mode PgBouncer and a hosted-style non-superuser role.+ *+ * Protects: §3 measured outcomes and §7/§13 contract.+ * - Agent workflow: the bare command prints the plan and exits 3+ * (`confirmation_required`, ask_user, egress + destructive effects,+ * plan_hash, preview and fix commands); `--yes` alone re-plans and refuses;+ * `--yes --expect <hash>` graduates with the doctor inline; the target+ * doctor is green; existing tokens and OAuth clients authorize; over MCP a+ * recall, a write, a replay of that write's request id (same outcome, no new+ * row) and a grant-denied call behave as before.+ * - `--plan` and `--status` perform zero mutations, polled at every custody+ * boundary and after a crash.+ * - `--force` binds the target's destructive snapshot: a page added between+ * preview and confirmation refuses with `preview_changed`.+ * - The same legacy round trip through PgBouncer (DDL on the direct route) and+ * as a NOSUPERUSER role (`disable_trigger` bypass recorded in the receipt).+ * - The 1k-page history fixture round trip with the plan-to-green-doctor+ * clock under five minutes.+ * Not covered elsewhere: unit tests cover the plan document and the state+ * machine without a real target.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { rmSync } from 'node:fs';+import { join } from 'node:path';+import postgres from '#postgres';+import { HISTORY_FIXTURE_TABLES } from '../../scripts/persistence/history-fixture.ts';+import {+ codeOf, custodyPaths, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, graduationTest, graduationTestIf, hostedRoleTarget, mcpHttpCall, passwordLeaks, passwordOf,+ planHashOf, pooledUrl, release, startGbrain, stateDigest, TARGET_ENV, waitForEvent, type GbrainResult,+} from '../helpers/graduation-e2e.ts';+import {+ doctorFailures, expectGraduated, failingChecks, historyCase, legacyCase, planAndRun, scratchRoot, targetRowState, withSource, withTarget, type Case,+} from '../helpers/graduation-scenarios.ts';+import { canonicalRows, loadLegacyExpected } from '../fixtures/graduation/legacy-brain.ts';++const cleanups: (() => Promise<void>)[] = [];+afterAll(async () => {+ for (const cleanup of cleanups.reverse()) await cleanup().catch(() => {});+ rmSync(scratchRoot, { recursive: true, force: true });+});+async function fresh(name: string, target?: Case['target']): Promise<Case> {+ const c = await legacyCase(name, target);+ cleanups.push(() => c.target.close());+ return c;+}++describe.skipIf(!DATABASE_URL)('graduation: agent workflow', () => {+ graduationTest('plan -> ask_user -> --yes --expect -> green doctor, then MCP recall, write, replay and a denied grant', async () => {+ const c = await fresh('agent-flow');+ const env = { [TARGET_ENV]: c.target.url };+ const results: GbrainResult[] = [];+ const started = Date.now();+ const ask = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--json'], { home: c.fx.home, env });+ results.push(ask);+ expect(ask.code).toBe(3);+ expect(codeOf(ask.json)).toBe('confirmation_required');+ expect(fixOf(ask.json)?.next).toBe('ask_user');+ expect(ask.json?.effects).toEqual(expect.arrayContaining(['egress', 'destructive']));+ const hash = planHashOf(ask.json)!;+ expect(hash).toMatch(/^[a-f0-9]{8,}$/);+ expect(JSON.stringify(fixOf(ask.json))).toContain(`--expect ${hash}`);+ expect(JSON.stringify(ask.json?.preview ?? ask.json)).toContain('--plan');+ expect(String(ask.json?.user_message ?? '')).toContain(new URL(c.target.url).hostname);+ expect(await targetRowState(c.target.url)).toBeNull();++ const yesOnly = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--json'], { home: c.fx.home, env });+ results.push(yesOnly);+ expect(yesOnly.code).toBe(3);+ expect(planHashOf(yesOnly.json)).toBe(hash);++ const run = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', hash, '--json'], { home: c.fx.home, env, timeoutMs: 900_000 });+ results.push(run);+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ expect(failingChecks(run.json?.doctor ?? run.json?.receipt?.doctor ?? null)).toEqual([]);+ expect(JSON.stringify(run.json)).toContain('gbrain mcp expose');+ const minutes = (Date.now() - started) / 60_000;+ expect(minutes).toBeLessThan(5);+ await expectGraduated(c, 'agent flow');+ expect(passwordLeaks(passwordOf(c.target.url), results, c.fx.dir)).toEqual([]);++ const port = freePort();+ const serve = startGbrain(['serve', '--http', '--port', String(port)], { home: c.fx.home, timeoutMs: 300_000 });+ try {+ const base = `http://127.0.0.1:${port}`;+ const live = loadLegacyExpected().secrets.liveToken;+ for (let i = 0; i < 100; i++) { try { if ((await fetch(`${base}/health`)).status < 500) break; } catch {} await Bun.sleep(100); }+ const t0 = performance.now();+ const recall = await mcpHttpCall(base, live, 'search', { query: 'acme' });+ const remoteMs = Math.round(performance.now() - t0);+ expect(recall.status).toBe(200);+ expect(JSON.stringify(recall.rpc)).toContain('acme');+ const requestId = '00000000-0000-4000-8000-0000000000e1';+ const write = await mcpHttpCall(base, live, 'put_page', { slug: 'notes/after-graduation', content: 'Written over MCP after graduation.\n', request_id: requestId });+ expect(write.rpc?.error).toBeUndefined();+ const replay = await mcpHttpCall(base, live, 'put_page', { slug: 'notes/after-graduation', content: 'Written over MCP after graduation.\n', request_id: requestId });+ expect(JSON.stringify(replay.rpc?.result)).toBe(JSON.stringify(write.rpc?.result));+ await withTarget(c.target.url, async t => {+ const [row] = await t.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ expect(Number(row.n)).toBe(1);+ });+ const denied = await mcpHttpCall(base, loadLegacyExpected().secrets.revokedToken, 'search', { query: 'acme' });+ expect(denied.status === 401 || denied.status === 403 || !!denied.rpc?.error).toBe(true);+ console.log(JSON.stringify({ graduation_agent_flow: { minutes_plan_to_green_doctor: Number(minutes.toFixed(2)), remote_search_ms: remoteMs } }));+ } finally {+ serve.kill('SIGTERM');+ await serve.exited;+ }+ }, 1_200_000);+});++describe.skipIf(!DATABASE_URL)('graduation: --plan and --status are zero-mutation', () => {+ graduationTest('polled at every custody boundary and after a crash, neither changes a byte or a row', async () => {+ const c = await fresh('zero-mutation');+ const { argv, env } = await planAndRun(c);+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['*'] } });+ const seen: string[] = [];+ const probe = async (label: string) => {+ const before = await stateDigest(c.fx.dir, c.target.url);+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });+ expect({ label, code: status.code }).toEqual({ label, code: 0 });+ await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--plan', '--json'], { home: c.fx.home, env });+ const changes = digestChanges(before, await stateDigest(c.fx.dir, c.target.url)).filter(change => !change.includes('boundary-events.jsonl'));+ expect({ label, changes }).toEqual({ label, changes: [] });+ };+ for (let ordinal = 1; ; ordinal++) {+ const paused = await waitForEvent(c.events, e => e.event === 'paused' && e.ordinal === ordinal, child).catch(() => null);+ if (!paused) break;+ seen.push(paused.boundary);+ await probe(`${paused.boundary}#${ordinal}`);+ if (paused.boundary === 'verified') {+ child.kill('SIGKILL');+ await child.exited;+ await probe('after a SIGKILL at verified');+ break;+ }+ release(c.events, ordinal);+ }+ expect(seen).toEqual(expect.arrayContaining(['quiesced', 'drained', 'target_fenced', 'table_copied', 'copied', 'verified']));+ expect((await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 900_000 })).code).toBe(0);+ await expectGraduated(c, 'after zero-mutation polling');+ }, 1_200_000);+});++describe.skipIf(!DATABASE_URL)('graduation: target emptiness and --force', () => {+ graduationTest('a target the user already initialised counts as empty', async () => {+ const c = await fresh('pre-initialised');+ const init = await gbrain(['doctor', '--json'], { home: join(c.fx.dir, 'init-home'), env: { GBRAIN_DATABASE_URL: c.target.url } });+ expect(init.code).not.toBe(2);+ 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: '' });+ await expectGraduated(c, 'pre-initialised target');+ }, 900_000);++ graduationTest('a foreign non-empty target refuses; --force binds the wipe to the previewed snapshot', async () => {+ const c = await fresh('force');+ const other = join(c.fx.dir, 'foreign-home');+ const put = await gbrain(['put', 'notes/foreign', '--source', 'default'], { home: other, env: { GBRAIN_DATABASE_URL: c.target.url }, stdin: 'a foreign brain page\n' });+ expect(put.code).toBe(0);+ const env = { [TARGET_ENV]: c.target.url };+ const plain = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--plan', '--json'], { home: c.fx.home, env });+ expect(JSON.stringify(plain.json)).toContain('target_not_empty');+ const refused = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', String(planHashOf(plain.json)), '--json'], { home: c.fx.home, env });+ expect(codeOf(refused.json)).toBe('graduation_target_not_empty');+ expect(fixOf(refused.json)?.next).toBe('ask_user');++ const preview = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--force', '--plan', '--json'], { home: c.fx.home, env });+ expect(preview.code).toBe(0);+ const hash = planHashOf(preview.json)!;+ expect(JSON.stringify(preview.json)).toMatch(/pages/);+ const more = await gbrain(['put', 'notes/foreign-2', '--source', 'default'], { home: other, env: { GBRAIN_DATABASE_URL: c.target.url }, stdin: 'added after the preview\n' });+ expect(more.code).toBe(0);+ const before = await stateDigest(join(c.fx.dir, '.none'), c.target.url);+ const changed = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--force', '--yes', '--expect', hash, '--json'], { home: c.fx.home, env });+ expect(codeOf(changed.json)).toBe('preview_changed');+ expect(digestChanges(before, await stateDigest(join(c.fx.dir, '.none'), c.target.url))).toEqual([]);++ const again = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--force', '--plan', '--json'], { home: c.fx.home, env });+ const run = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--force', '--yes', '--expect', String(planHashOf(again.json)), '--json'],+ { home: c.fx.home, env, timeoutMs: 900_000 });+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ await expectGraduated(c, 'after --force');+ await withTarget(c.target.url, async t => {+ const [row] = await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE slug LIKE 'notes/foreign%'`);+ expect(Number(row.n)).toBe(0);+ });+ }, 900_000);+});++describe.skipIf(!DATABASE_URL)('graduation: connection topologies', () => {+ graduationTestIf(!process.env.GBRAIN_PGBOUNCER_URL)('through transaction-mode PgBouncer with DDL on the direct route', async () => {+ const c = await fresh('pgbouncer');+ const pooled = pooledUrl(c.target)!;+ const { argv, env } = await planAndRun(c, { url: pooled, env: { GBRAIN_DIRECT_DATABASE_URL: c.target.url } });+ 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: '' });+ await expectGraduated(c, 'pgbouncer');+ }, 900_000);++ test('the hosted-style role is a real constraint: no session_replication_role, but it owns what it creates', async () => {+ const hosted = await hostedRoleTarget();+ cleanups.push(() => hosted.close());+ const sql = postgres(hosted.url, { max: 1, prepare: false, onnotice: () => {} });+ try {+ const replica = await sql.begin(tx => tx.unsafe('SET LOCAL session_replication_role = replica')).then(() => 'allowed', e => String((e as { code?: string }).code));+ expect(replica).toBe('42501');+ await sql.unsafe('CREATE TABLE probe(id int primary key); ALTER TABLE probe DISABLE TRIGGER USER; DROP TABLE probe');+ const [ext] = await sql.unsafe<{ n: number }[]>(`SELECT count(*)::int AS n FROM pg_extension WHERE extname='vector'`);+ expect(Number(ext.n)).toBe(1);+ } finally { await sql.end(); }+ const oldUrl = hosted.url;+ const rotated = await hosted.rotatePassword();+ expect(passwordOf(rotated)).not.toBe(passwordOf(oldUrl));+ const stale = postgres(oldUrl, { max: 1, prepare: false, onnotice: () => {}, connect_timeout: 5 });+ expect(await stale.unsafe('SELECT 1').then(() => 'connected', e => String((e as { code?: string }).code))).toBe('28P01');+ await stale.end();+ const fresh = postgres(rotated, { max: 1, prepare: false, onnotice: () => {} });+ expect((await fresh.unsafe<{ n: number }[]>('SELECT 1 AS n'))[0].n).toBe(1);+ await fresh.end();+ });++ graduationTest('as a hosted-style NOSUPERUSER role: the disable-trigger fallback, every user trigger re-enabled', async () => {+ const hosted = await hostedRoleTarget();+ const c = await fresh('hosted-role', hosted);+ const { argv, env } = await planAndRun(c, { url: hosted.url });+ 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: '' });+ expect(JSON.stringify(run.json)).toContain('disable_trigger');+ await expectGraduated(c, 'hosted role');+ const sql = postgres(hosted.url, { max: 1, prepare: false, onnotice: () => {} });+ try {+ const disabled = await sql.unsafe<{ t: string }[]>(`SELECT c.relname || '.' || t.tgname AS t 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 AND t.tgenabled <> 'O'`);+ expect(disabled.map(r => r.t)).toEqual([]);+ } finally { await sql.end(); }+ }, 900_000);++ graduationTest('--trigger-bypass disable-trigger is honoured on a superuser target and recorded', async () => {+ const c = await fresh('forced-bypass');+ const { argv, env } = await planAndRun(c, { extra: ['--trigger-bypass', 'disable-trigger'] });+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });+ expect(run.code).toBe(0);+ expect(JSON.stringify(run.json)).toContain('disable_trigger');+ await expectGraduated(c, 'forced disable-trigger');+ }, 900_000);+});++describe.skipIf(!DATABASE_URL)('graduation: 1k-page history round trip', () => {+ graduationTest('1,000 pages with history graduate with verify green and the plan-to-green-doctor clock under five minutes', async () => {+ const { fx, target } = await historyCase('history-1k', 1000);+ cleanups.push(() => target.close());+ const env = { [TARGET_ENV]: target.url };+ const t0 = Date.now();+ const plan = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--json'], { home: fx.home, env });+ expect(plan.code).toBe(3);+ const run = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', String(planHashOf(plan.json)), '--json'],+ { home: fx.home, env, timeoutMs: 1_800_000 });+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ const doctor = await doctorFailures(fx.home);+ const wallMs = Date.now() - t0;+ expect(doctor.failing).toEqual([]);+ console.log(JSON.stringify({ graduation_1k: { wall_ms: wallMs, fixture: fx.report, timings: run.json?.receipt?.timings ?? run.json?.timings ?? null } }));+ expect(wallMs).toBeLessThan(5 * 60_000);++ const retained = custodyPaths(fx.dataDir).graduated[0];+ const outputs = fx.outputs as { queuedRequestId: string; delayedEffectId: string };+ const sourceSide = await withSource(fx, async source => {+ const counts: Record<string, number> = {};+ for (const table of HISTORY_FIXTURE_TABLES) counts[table] = Number((await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table}`))[0].n);+ const rows: Record<string, string[]> = {};+ for (const table of ['pages', 'page_versions', 'facts', 'takes', 'fact_withdrawals', 'content_chunks', 'access_tokens', 'oauth_clients', 'oauth_tokens']) rows[table] = await canonicalRows(source, table);+ return { counts, rows };+ }, retained);+ await withTarget(target.url, async t => {+ for (const table of HISTORY_FIXTURE_TABLES) {+ const n = Number((await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table}`))[0].n);+ expect({ table, n }).toEqual({ table, n: sourceSide.counts[table] });+ }+ for (const [table, rows] of Object.entries(sourceSide.rows)) {+ const got = await canonicalRows(t, table);+ const first = got.findIndex((row, i) => row !== rows[i]);+ expect({ table, length: got.length, first }).toEqual({ table, length: rows.length, first: -1 });+ }+ const [queued] = await t.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [outputs.queuedRequestId]);+ expect(queued.state).toBe('committed');+ const [delayed] = await t.executeRaw<{ state: string }>('SELECT state FROM persistence_effects WHERE id=$1', [outputs.delayedEffectId]);+ expect(delayed.state).toBe('queued');+ });+ }, 1_800_000);+});+diff --git a/tests/heavy/graduation_10k.sh b/tests/heavy/graduation_10k.shnew file mode 100755index 0000000000..a6ff32d9be--- /dev/null+++ b/tests/heavy/graduation_10k.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+# Engine graduation at 10,000 pages: builds (or restores from the fixture+# cache) the 10k history fixture, graduates it into a fresh Postgres test+# database through the agent flow (plan, confirm, green doctor) and writes the+# time-to-value report with per-phase timings and query p50/p95 on both+# engines. Reported, not gated (the 5-minute gate applies at 1k pages).+set -euo pipefail++source "$(dirname "$0")/_db_floor.sh"+cd "$(dirname "$0")/../.."++if [ -z "${DATABASE_URL:-}" ]; then+ echo "[graduation_10k] DATABASE_URL not set; skipping (informational)." >&2+ exit 0+fi++LOG_DIR="${GBRAIN_HEAVY_LOG_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/gbrain-graduation-10k.XXXXXX")}"+mkdir -p "$LOG_DIR"+REPORT="$LOG_DIR/graduation-10k-$(date -u +%Y%m%d-%H%M%SZ).json"+echo "[graduation_10k] report=$REPORT"+bun --no-env-file scripts/persistence/graduation-ttv.ts --pages 10000 --seed 1 --live-serve --out "$REPORT" --enforce