Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(graduation): helper split, R3-compliant fixture cache test, testing docs

garrytan1e09d7925f44
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 638d34f94b..8b93a13cc9 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -790,6 +790,36 @@ The CLI without `--informational` still enforces the threshold. The original
heavy shell entry invokes this harness; its optional `STRICT_LATENCY=1`
flag affects only the latency threshold, never validity requirements.
+### Engine graduation
+
+Graduation (`gbrain migrate --to postgres`) is tested against two fixtures.
+`test/fixtures/graduation/legacy-brain.ts` builds a small brain by hand-written
+SQL on a fresh schema, and its expected outcomes live in `expected.json`
+beside it (`test/graduation-legacy-fixture.test.ts` proves the build matches
+and that the target checker discriminates).
+`scripts/persistence/graduation-fixture.ts` wraps `buildHistoryFixture` for
+the 1k and 10k history brains, builds keylessly in a child process, and
+caches each build as a tarball keyed by the fixture sources, schema version,
+seed and size (`GBRAIN_GRADUATION_FIXTURE_CACHE`, default
+`~/.cache/gbrain-graduation-fixtures`). A restore re-homes paths and owner
+stamps and marks sources synced, so the source doctor stays green.
+
+The E2E suites drive the real CLI in child processes:
+`graduation-crash` (SIGKILL at every run and rollback boundary),
+`graduation-faults` (ENOSPC on a tmpfs tablespace, which needs Docker;
+password rotation; DDL route mismatch), `graduation-clients` (older
+releases, respawned and resident serve, stale CLI and MCP configs) and
+`graduation-cli` (agent flow, zero-mutation `--plan`/`--status`, `--force`,
+PgBouncer through `GBRAIN_PGBOUNCER_URL`, a NOSUPERUSER role, the 1k round
+trip). Kill and pause points come from `graduationBoundary()` hooks that only
+`test/helpers/graduation-hooks-preload.ts` registers. Older release binaries
+are built once per tag under `GBRAIN_OLDER_RELEASE_DIR`. The crash suite takes
+about 40 seconds per case, so run it with `GBRAIN_E2E_FILE_TIMEOUT=3600`.
+`scripts/persistence/graduation-ttv.ts` records the commands and wall time
+from the first plan to a green doctor, the run's phase timings and query
+p50/p95 on both engines. The 1k-page gate is five minutes;
+`tests/heavy/graduation_10k.sh` reports the 10k run.
+
### PGLite schema snapshot (default-on)
`scripts/build-pglite-snapshot.ts` (`bun run build:pglite-snapshot`) bakes a
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index a43bce80ae..bc4c4e2c2b 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -62,6 +62,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.
+- `scripts/persistence/{graduation-fixture,graduation-process,graduation-ttv}.ts` — engine graduation test inputs and measurements. `graduation-fixture.ts` builds the 1k/10k history brains (`buildHistoryFixture` plus deterministic chunk vectors) or the hand-built legacy brain (`test/fixtures/graduation/`) in a keyless child process, caches each as a tarball keyed by its source files, schema version, seed and size, and re-homes a restore (database paths, managed-root records, owner stamps re-stamped with the new inode and birth time; sources marked synced). Its report lists bytes, chunks, versions, requests, effects and embeddings. `graduation-process.ts` spawns the real CLI or an older release with an isolated home and no provider keys, with optional boundary hooks, plus MCP stdio/HTTP clients and the JSON contract accessors. `graduation-ttv.ts` times plan to green doctor (five-minute gate at 1k pages; exit 1 under `--enforce`, 3 on a harness crash). Owners: `test/scripts/graduation-fixture.test.ts`, `test/graduation-legacy-fixture.test.ts`, `test/e2e/graduation-{crash,faults,clients,cli}.test.ts`, `tests/heavy/graduation_10k.sh`.
+
- `scripts/persistence/{matrix,matrix-cases}.ts` — required real Postgres/PgBouncer deployment matrix: 24 combinations of RLS policy enforcement, ordinary pool sizes 1/2/3 and shared/separate direct capacity. Production bulk reservations must leave short claims, renewals and reads usable; size-one publication stays queued. Fresh fixtures also verify successor manifests, stale owners, retained native lock exclusion during root replacement and source deletion/recreation. `test/e2e/persistence-runtime-matrix.test.ts` runs it when configured and refuses missing required pooler fixtures. Supplied URLs pass the test-database guard before its CREATE/DROP control connection uses the maintenance database; fresh case databases isolate it from other E2E shards.
- `scripts/persistence/{performance,read-workload,read-metrics,read-admission,read-diagnostics}.ts` — required median-of-three read-workload validity check with advisory CI latency around the existing heavy query corpus (500 pages, 200 reads, four writers, writesPerWriter 25, four-connection PostgreSQL pool). Both engines use public page mutation handlers; every read/write or drained sampler error invalidates the sample, actual in-flight mutation intervals must cover at least 90% of reads, and CI reports the 50% loaded-versus-idle p99 threshold without blocking on that ratio. CI uses `--informational`, which never suppresses invalid-workload failures; the default CLI and explicit strict heavy runs still enforce the threshold. Isolated children retain runtime/source hashes, queue/admission/commit/RSS/recovery/pool metrics and bounded diagnostic records with total/dropped counts, including failed partial observations. Numeric query/corpus/write indices and monotonic timestamps correlate reads, admissions, terminal receipts and pool samples without retaining SQL, parameters, identifiers, content or raw errors. Fixed failure stages retain only allowlisted error properties; raw stacks are omitted. The root postgres.js begin observer covers lexical readers and writers, preserves the original promise/receiver/arguments, and excludes nested savepoints. Dispatch-to-callback includes BEGIN and client scheduling, not pure checkout wait; PGLite has no transaction-entry timing. Identical 20ms timers record event-loop lateness in both phases. Observers run during seed/warmup before measurement; context setup and read retention sit outside query timing where possible, but transaction/timer callbacks add unquantified overhead. No SQL or server sampling is added, and sparse pool samples cannot establish lock causes. The original `tests/heavy/read_latency_under_sync.sh` invokes this runner. The stable admission proxy requires one resolved top-level queued journal transaction per committed UUID. `test/persistence-performance.test.ts` guards validity, strict threshold semantics and advisory CLI exit behavior; `test/persistence-admission-observer.test.ts` proves rollback/publication boundaries; `test/persistence-read-diagnostics{,.serial}.test.ts` covers bounds, transparency, nested transactions, safe failure retention, tiny manifests and late sampler rejection.
diff --git a/test/helpers/graduation-e2e.ts b/test/helpers/graduation-e2e.ts
index b6be8ddc81..b7670749a6 100644
--- a/test/helpers/graduation-e2e.ts
+++ b/test/helpers/graduation-e2e.ts
@@ -13,13 +13,12 @@
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 { dirname, join } from 'node:path';
import postgres from '#postgres';
import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+import { gbrain, planHashOf, REPO, type GbrainChild, type GbrainOpts, type GbrainResult } from '../../scripts/persistence/graduation-process.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');
+export * from '../../scripts/persistence/graduation-process.ts';
/**
* Graduation lands in parallel lanes (G2a orchestrator, G3 CLI). Until the
@@ -35,71 +34,6 @@ export function graduationTestIf(skip: boolean): typeof test {
}
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 }
@@ -128,15 +62,6 @@ 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> }
@@ -357,75 +282,3 @@ export function olderReleaseBinary(tag: string): string {
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/scripts/graduation-fixture.test.ts b/test/scripts/graduation-fixture.test.ts
index 789e756bc7..14e2d58ba4 100644
--- a/test/scripts/graduation-fixture.test.ts
+++ b/test/scripts/graduation-fixture.test.ts
@@ -12,46 +12,58 @@
* that stops counting chunks, versions, requests or embeddings.
* Not covered elsewhere: no other test restores a cached fixture. No production seam.
*/
-import { afterAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { assertPhysicalRoot } from '../../src/core/persistence/physical-root.ts';
-import { graduationFixtureKey, prepareGraduationFixture } from '../../scripts/persistence/graduation-fixture.ts';
+import { graduationFixtureKey, prepareGraduationFixture, type GraduationFixture } from '../../scripts/persistence/graduation-fixture.ts';
import { legacySourceMismatches } from '../fixtures/graduation/legacy-brain.ts';
import { withEnv } from '../helpers/with-env.ts';
const scratch = mkdtempSync(join(tmpdir(), 'gbrain-graduation-fixture-'));
-afterAll(() => rmSync(scratch, { recursive: true, force: true }));
+const cacheDir = join(scratch, 'cache');
+let built: GraduationFixture;
+let restored: GraduationFixture;
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ built = await prepareGraduationFixture({ kind: 'legacy', dir: join(scratch, 'built'), cacheDir });
+ restored = await prepareGraduationFixture({ kind: 'legacy', dir: join(scratch, 'restored'), cacheDir });
+ engine = new PGLiteEngine();
+ await withEnv({ GBRAIN_HOME: restored.home }, () => engine.connect({ database_path: restored.dataDir }));
+}, 180_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(scratch, { recursive: true, force: true });
+});
describe('graduation fixture cache', () => {
- test('a cache hit re-homes the legacy brain so it verifies and its managed roots hold', async () => {
- const cacheDir = join(scratch, 'cache');
- const built = await prepareGraduationFixture({ kind: 'legacy', dir: join(scratch, 'built'), cacheDir });
+ test('the first prepare builds and caches; the second restores the same report', () => {
expect(built.cached).toBe(false);
expect(readdirSync(cacheDir).filter(name => name.endsWith('.tar.gz'))).toEqual([`legacy-${built.key}.tar.gz`]);
- const restored = await prepareGraduationFixture({ kind: 'legacy', dir: join(scratch, 'restored'), cacheDir });
expect(restored.cached).toBe(true);
expect(restored.report).toEqual(built.report);
expect(restored.report).toMatchObject({ pages: 9, chunks: 7, versions: 2, requests: 4, effects: 6, embeddings: { chunks: 1, facts: 1, takes: 0 } });
+ });
+ test('the restored brain matches expected.json and its managed root holds at the new path', async () => {
await withEnv({ GBRAIN_HOME: restored.home }, async () => {
- const engine = new PGLiteEngine();
- await engine.connect({ database_path: restored.dataDir });
- try {
- expect(await legacySourceMismatches(engine)).toEqual([]);
- const bindings = await engine.executeRaw<{ worktree_id: string; local_path: string; coordination_path: string }>(
- 'SELECT worktree_id,local_path,coordination_path FROM persistence_host_bindings');
- expect(bindings.length).toBe(1);
- for (const binding of bindings) {
- expect(binding.local_path.startsWith(restored.dir)).toBe(true);
- expect(binding.coordination_path.startsWith(restored.home)).toBe(true);
- expect(() => assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path })).not.toThrow();
- }
- } finally { await engine.disconnect(); }
+ expect(await legacySourceMismatches(engine)).toEqual([]);
+ const bindings = await engine.executeRaw<{ worktree_id: string; local_path: string; coordination_path: string }>(
+ 'SELECT worktree_id,local_path,coordination_path FROM persistence_host_bindings');
+ expect(bindings.length).toBe(1);
+ for (const binding of bindings) {
+ expect(binding.local_path.startsWith(restored.dir)).toBe(true);
+ expect(binding.coordination_path.startsWith(restored.home)).toBe(true);
+ expect(() => assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path })).not.toThrow();
+ }
+ const stale = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE local_path IS NOT NULL AND last_sync_at IS NULL');
+ expect(stale).toEqual([]);
});
- }, 180_000);
+ });
test('the cache key changes with the seed and the page count', async () => {
const base = { kind: 'history' as const, dir: scratch, pages: 1000, seed: 1 };