Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: split the tier2 journey's read-op sweep into its own serial file; template the graduation harness source datastore

time-attackc65dd10e1f3a
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 776bc4bd05..58c6357215 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -10,7 +10,8 @@ test/agent-injection-http-view.serial.test.ts global-state global-state: binds l
test/agent-install-backup.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; spyOn fs.renameSync, PGLiteEngine.prototype.connect, console.log
test/agent-install-follow-setup.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
test/agent-journey-recovery.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
-test/agent-journey-tier2.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
+test/agent-journey-tier2-json.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll (seedTimelineFinding in test/helpers/agent-journey-tier2.ts); ~60 real CLI subprocesses on one PGLite brain
+test/agent-journey-tier2.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll (seedTimelineFinding in test/helpers/agent-journey-tier2.ts); live gbrain serve over MCP stdio
test/agent-journey-upgrade.serial.test.ts global-state global-state: binds local servers/ports
test/agent-journey.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll
test/agent-operator-gate-fixes.serial.test.ts global-state global-state: binds local servers/ports
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index 43ee807668..bfdb3eee0a 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -7,7 +7,8 @@
"test/agent-install-backup.serial.test.ts": 124,
"test/agent-install-follow-setup.serial.test.ts": 41,
"test/agent-journey-recovery.serial.test.ts": 85,
- "test/agent-journey-tier2.serial.test.ts": 145,
+ "test/agent-journey-tier2-json.serial.test.ts": 80,
+ "test/agent-journey-tier2.serial.test.ts": 65,
"test/agent-journey-upgrade.serial.test.ts": 129,
"test/agent-journey.serial.test.ts": 94,
"test/agent-operator-gate-fixes.serial.test.ts": 57,
diff --git a/test/agent-journey-tier2-json.serial.test.ts b/test/agent-journey-tier2-json.serial.test.ts
new file mode 100644
index 0000000000..fcfe704795
--- /dev/null
+++ b/test/agent-journey-tier2-json.serial.test.ts
@@ -0,0 +1,48 @@
+/**
+ * Lane H1b (Tier 2), row 1: every `--json` stdout parses, for every read op the
+ * CLI exposes (mutating:false, no required params), the doctor family and the
+ * journey's commands, each as a real CLI subprocess against a keyless PGLite
+ * brain in a temp home. Split from test/agent-journey-tier2.serial.test.ts
+ * (rows 2–4) to keep each serial file well under the pool's per-file wall
+ * clock; the brain is seeded the same way.
+ *
+ * Serial: real subprocesses, PGLite locks.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { operations } from '../src/core/operations.ts';
+import { gb } from './helpers/agent-journey.ts';
+import { MARKER, expectJsonContract, seedTimelineFinding, writeNotes } from './helpers/agent-journey-tier2.ts';
+
+describe('H1b: --json parses, every WARN has an executable fix, every plan command runs', () => {
+ let home = '';
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-json-'));
+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ expect((await gb(home, ['import', writeNotes(join(home, 'notes'), 3), '--no-embed', '--json'])).exitCode).toBe(0);
+ await seedTimelineFinding(home, 'tier2-note-1');
+ }, 300_000);
+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+ test('every read op on the CLI and the doctor family: --json stdout is one document', async () => {
+ const readOps = operations
+ .filter(op => op.mutating === false && op.cliHints?.name && !Object.values(op.params).some(p => p.required))
+ .map(op => [op.cliHints!.name!]);
+ expect(readOps.length).toBeGreaterThan(20);
+ const commands = [
+ ...readOps,
+ ['doctor'], ['doctor', '--fast'], ['doctor', '--only', 'embeddings'], ['doctor', '--remediation-plan'],
+ ['search', MARKER], ['query', MARKER], ['get', 'tier2-note-1'], ['recall', MARKER], ['sources', 'list'],
+ ['jobs', 'list'], ['jobs', 'stats'], ['errors', 'invalid_params'], ['features'], ['status'], ['models'],
+ ['embed', '--stale'], ['import', join(home, 'notes')], ['transcripts'], ['whoknows'],
+ ];
+ const bad: string[] = [];
+ for (const args of commands) {
+ const r = await gb(home, [...args, '--json'], { timeoutMs: 90_000 });
+ try { expectJsonContract(r, `gbrain ${args.join(' ')} --json`); } catch (e) { bad.push(`${args.join(' ')} (exit ${r.exitCode}): ${String(e).slice(0, 300)}`); }
+ }
+ expect(bad).toEqual([]);
+ }, 900_000);
+});
diff --git a/test/agent-journey-tier2.serial.test.ts b/test/agent-journey-tier2.serial.test.ts
index b04bfbe8eb..ed5c63a5bd 100644
--- a/test/agent-journey-tier2.serial.test.ts
+++ b/test/agent-journey-tier2.serial.test.ts
@@ -1,6 +1,9 @@
/**
* Lane H1b (Tier 2): the rows of the agent journey that hold the whole wave's
- * contract up across surfaces. Real CLI subprocesses, real `gbrain serve`
+ * contract up across surfaces. Row 1's read-op sweep runs in
+ * test/agent-journey-tier2-json.serial.test.ts and rows 5–8 in
+ * test/agent-journey-recovery.serial.test.ts, so each serial file stays well
+ * under the pool's per-file wall clock. Real CLI subprocesses, real `gbrain serve`
* sessions (stdio and HTTP), keyless PGLite in temp homes, hard timeouts.
*
* 1. Every `--json` stdout parses: the journey's commands, the doctor family,
@@ -16,7 +19,6 @@
* 4. One embedding-enable command on every surface: init's hint, doctor's
* checks, `embed --all`, `whoami`, MCP whoami and gbrain://capabilities
* (behind the lock owner's two-step plan there).
- * (rows 5–8 run in test/agent-journey-recovery.serial.test.ts)
* 5. `--surface starter`: a subset of full, instructions name only listed
* tools, a listed tool answers, an unlisted one is a one-block error.
* 6. Read-only grant over HTTP: only read tools listed; a write is refused
@@ -37,81 +39,12 @@
* Serial: real subprocesses, PGLite locks, an HTTP port.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { spawn, type ChildProcess } from 'node:child_process';
-import { Client } from '@modelcontextprotocol/sdk/client/index.js';
-import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
-import { operations } from '../src/core/operations.ts';
import { shellQuote } from '../src/core/agent-output.ts';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
-import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
-import {
- REPO, body, call, expectOneBlockError, gb, journeyEnv, mcp, oneDocument, waitFor, type GbResult,
-} from './helpers/agent-journey.ts';
-
-const MARKER = 'wombat-tier2-marker';
-
-function writeNotes(dir: string, n: number, prefix = 'tier2-note'): string {
- mkdirSync(dir, { recursive: true });
- for (let i = 1; i <= n; i++) writeFileSync(join(dir, `${prefix}-${i}.md`), `---\ntitle: ${prefix} ${i}\n---\n\n# ${prefix} ${i}\n\nThe ${MARKER} ${i}.\n`);
- return dir;
-}
-
-async function withBrain<T>(home: string, fn: (engine: PGLiteEngine) => Promise<T>): Promise<T> {
- const engine = new PGLiteEngine();
- await engine.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') });
- try { return await fn(engine); } finally { await engine.disconnect(); }
-}
-
-async function seedTimelineFinding(home: string, slug: string): Promise<void> {
- await withBrain(home, engine => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
- `INSERT INTO timeline_entries(page_id,date,source,summary,detail)
- SELECT id,'2026-07-01','legacy','A database-only event','' FROM pages WHERE source_id='default' AND slug=$1`, [slug]),
- TEST_WRITE_ATTRIBUTION)));
-}
-
-async function pagesOf(home: string): Promise<string[]> {
- return withBrain(home, async engine => (await engine.executeRaw<{ s: string }>(
- "SELECT source_id || ':' || slug AS s FROM pages WHERE deleted_at IS NULL ORDER BY 1")).map(r => r.s));
-}
-
-/** A `--json` invocation: one parseable document; a failure document names code + suggestion. */
-function expectJsonContract(r: GbResult, label: string): Record<string, any> {
- const doc = oneDocument(r, label);
- if (r.exitCode !== 0 && r.exitCode !== 3) {
- expect(typeof doc.code, `${label}: failure document has code (exit ${r.exitCode})`).toBe('string');
- expect(typeof doc.suggestion, `${label}: failure document has suggestion`).toBe('string');
- }
- return doc;
-}
-
-/** A directory with a `gbrain` that runs this checkout, so plan/fix command strings run as pasted. */
-function gbrainShim(root: string): string {
- const bin = join(root, 'bin');
- mkdirSync(bin, { recursive: true });
- writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec bun --no-env-file run ${JSON.stringify(join(REPO, 'src', 'cli.ts'))} "$@"\n`);
- chmodSync(join(bin, 'gbrain'), 0o755);
- return bin;
-}
-
-async function sh(home: string, command: string, bin: string, timeoutMs = 120_000): Promise<GbResult> {
- const t0 = performance.now();
- const env = journeyEnv(home, { PATH: `${bin}:${process.env.PATH ?? ''}` });
- const proc = Bun.spawn(['sh', '-c', command], { cwd: home, env, stdin: Bun.file('/dev/null'), stdout: 'pipe', stderr: 'pipe' });
- let killed = false;
- const killer = setTimeout(() => { killed = true; try { proc.kill('SIGKILL'); } catch { /* gone */ } }, timeoutMs);
- try {
- const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
- expect(killed, `${command} hung`).toBe(false);
- return { exitCode, stdout, stderr, ms: Math.round(performance.now() - t0), killed };
- } finally { clearTimeout(killer); }
-}
-
-interface Check { name: string; status: string; message: string; fix?: Fix; fix_unavailable_reason?: string }
-interface Fix { argv?: string[]; command?: string; consent: string[]; actor: string; next: string; inputs?: unknown[]; verify?: { argv?: string[] }; then?: Fix; requires_exclusive?: boolean }
+import { body, call, gb, mcp } from './helpers/agent-journey.ts';
+import { expectJsonContract, gbrainShim, seedTimelineFinding, sh, writeNotes, type Check, type Fix } from './helpers/agent-journey-tier2.ts';
describe('H1b: --json parses, every WARN has an executable fix, every plan command runs', () => {
let home = '';
@@ -125,26 +58,6 @@ describe('H1b: --json parses, every WARN has an executable fix, every plan comma
}, 300_000);
afterAll(() => { rmSync(home, { recursive: true, force: true }); });
- test('every read op on the CLI and the doctor family: --json stdout is one document', async () => {
- const readOps = operations
- .filter(op => op.mutating === false && op.cliHints?.name && !Object.values(op.params).some(p => p.required))
- .map(op => [op.cliHints!.name!]);
- expect(readOps.length).toBeGreaterThan(20);
- const commands = [
- ...readOps,
- ['doctor'], ['doctor', '--fast'], ['doctor', '--only', 'embeddings'], ['doctor', '--remediation-plan'],
- ['search', MARKER], ['query', MARKER], ['get', 'tier2-note-1'], ['recall', MARKER], ['sources', 'list'],
- ['jobs', 'list'], ['jobs', 'stats'], ['errors', 'invalid_params'], ['features'], ['status'], ['models'],
- ['embed', '--stale'], ['import', join(home, 'notes')], ['transcripts'], ['whoknows'],
- ];
- const bad: string[] = [];
- for (const args of commands) {
- const r = await gb(home, [...args, '--json'], { timeoutMs: 90_000 });
- try { expectJsonContract(r, `gbrain ${args.join(' ')} --json`); } catch (e) { bad.push(`${args.join(' ')} (exit ${r.exitCode}): ${String(e).slice(0, 300)}`); }
- }
- expect(bad).toEqual([]);
- }, 900_000);
-
test('every doctor WARN/FAIL carries an executable fix; agent-runnable fixes and every verify run', async () => {
const report = expectJsonContract(await gb(home, ['doctor', '--json']), 'doctor --json');
const notOk = (report.checks as Check[]).filter(c => c.status !== 'ok');
diff --git a/test/helpers/agent-journey-tier2.ts b/test/helpers/agent-journey-tier2.ts
new file mode 100644
index 0000000000..581e2e84cf
--- /dev/null
+++ b/test/helpers/agent-journey-tier2.ts
@@ -0,0 +1,68 @@
+/**
+ * Shared fixtures for the Lane H1b (Tier 2) agent-journey files: a seeded
+ * keyless PGLite brain, the `--json` document contract, and a `gbrain` on PATH
+ * for running plan and fix commands as an agent pastes them.
+ */
+import { expect } from 'bun:test';
+import { chmodSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './write-attribution.ts';
+import { REPO, journeyEnv, oneDocument, type GbResult } from './agent-journey.ts';
+
+export const MARKER = 'wombat-tier2-marker';
+
+export function writeNotes(dir: string, n: number, prefix = 'tier2-note'): string {
+ mkdirSync(dir, { recursive: true });
+ for (let i = 1; i <= n; i++) writeFileSync(join(dir, `${prefix}-${i}.md`), `---\ntitle: ${prefix} ${i}\n---\n\n# ${prefix} ${i}\n\nThe ${MARKER} ${i}.\n`);
+ return dir;
+}
+
+async function withBrain<T>(home: string, fn: (engine: PGLiteEngine) => Promise<T>): Promise<T> {
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') });
+ try { return await fn(engine); } finally { await engine.disconnect(); }
+}
+
+export async function seedTimelineFinding(home: string, slug: string): Promise<void> {
+ await withBrain(home, engine => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail)
+ SELECT id,'2026-07-01','legacy','A database-only event','' FROM pages WHERE source_id='default' AND slug=$1`, [slug]),
+ TEST_WRITE_ATTRIBUTION)));
+}
+
+/** A `--json` invocation: one parseable document; a failure document names code + suggestion. */
+export function expectJsonContract(r: GbResult, label: string): Record<string, any> {
+ const doc = oneDocument(r, label);
+ if (r.exitCode !== 0 && r.exitCode !== 3) {
+ expect(typeof doc.code, `${label}: failure document has code (exit ${r.exitCode})`).toBe('string');
+ expect(typeof doc.suggestion, `${label}: failure document has suggestion`).toBe('string');
+ }
+ return doc;
+}
+
+/** A directory with a `gbrain` that runs this checkout, so plan/fix command strings run as pasted. */
+export function gbrainShim(root: string): string {
+ const bin = join(root, 'bin');
+ mkdirSync(bin, { recursive: true });
+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec bun --no-env-file run ${JSON.stringify(join(REPO, 'src', 'cli.ts'))} "$@"\n`);
+ chmodSync(join(bin, 'gbrain'), 0o755);
+ return bin;
+}
+
+export async function sh(home: string, command: string, bin: string, timeoutMs = 120_000): Promise<GbResult> {
+ const t0 = performance.now();
+ const env = journeyEnv(home, { PATH: `${bin}:${process.env.PATH ?? ''}` });
+ const proc = Bun.spawn(['sh', '-c', command], { cwd: home, env, stdin: Bun.file('/dev/null'), stdout: 'pipe', stderr: 'pipe' });
+ let killed = false;
+ const killer = setTimeout(() => { killed = true; try { proc.kill('SIGKILL'); } catch { /* gone */ } }, timeoutMs);
+ try {
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ expect(killed, `${command} hung`).toBe(false);
+ return { exitCode, stdout, stderr, ms: Math.round(performance.now() - t0), killed };
+ } finally { clearTimeout(killer); }
+}
+
+export interface Check { name: string; status: string; message: string; fix?: Fix; fix_unavailable_reason?: string }
+export interface Fix { argv?: string[]; command?: string; consent: string[]; actor: string; next: string; inputs?: unknown[]; verify?: { argv?: string[] }; then?: Fix; requires_exclusive?: boolean }
diff --git a/test/helpers/graduation-harness.ts b/test/helpers/graduation-harness.ts
index cfd2e4fa99..b968f8124c 100644
--- a/test/helpers/graduation-harness.ts
+++ b/test/helpers/graduation-harness.ts
@@ -6,7 +6,7 @@
* carried probe table. Custody, schema, fence, manifest, marker, tombstone,
* lock and routing code under test is the production code.
*/
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { cpSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
@@ -123,7 +123,36 @@ async function freshTarget(opts: HarnessOptions): Promise<{ engine: BrainEngine;
return { engine, drop };
}
-/** A source brain with history-shaped rows: three probe rows and one access token. */
+let sourceTemplate: Promise<string> | undefined;
+
+/**
+ * One initialized, seeded source datastore per test process. A fresh PGLite
+ * datastore costs an initdb plus the full schema replay (about 2 s); every
+ * harness copies this closed template instead (under 0.2 s), so a file that
+ * builds a harness per test stays inside its lane budget.
+ */
+function seededSourceTemplate(): Promise<string> {
+ sourceTemplate ??= (async () => {
+ const dir = join(mkdtempSync(join(tmpdir(), 'gbrain-graduation-template-')), 'brain.pglite');
+ const source = await openPglite(dir);
+ try {
+ await source.initSchema();
+ await source.executeRaw(PROBE_DDL);
+ await source.executeRaw(`INSERT INTO grad_probe VALUES (1,'alpha'),(2,'beta'),(3,'gamma')`);
+ await source.executeRaw(`INSERT INTO access_tokens (id, name, token_hash) VALUES ($1::uuid, 'agent-example', 'hash-a1')`, [SOURCE_TOKEN_ID]);
+ } finally { await source.disconnect(); }
+ return dir;
+ })();
+ return sourceTemplate;
+}
+
+/**
+ * A source brain with history-shaped rows: three probe rows and one access
+ * token. The datastore is a copy of the process template, opened once at its
+ * own path in the harness home (which writes its owner sidecars there), with
+ * the identity values initSchema randomizes per brain drawn fresh, so no two
+ * harnesses share a brain id or shared-skill secret.
+ */
export async function makeHarness(opts: HarnessOptions = {}): Promise<Harness> {
const root = mkdtempSync(join(tmpdir(), 'gbrain-graduation-'));
const home = join(root, 'home');
@@ -133,13 +162,12 @@ export async function makeHarness(opts: HarnessOptions = {}): Promise<Harness> {
const mountsPath = join(root, 'mounts.json');
writeFileSync(join(gbrainDir, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dataDir }), { mode: 0o600 });
writeFileSync(mountsPath, JSON.stringify({ version: 1, mounts: [{ id: 'team-example', path: root, engine: 'pglite', database_path: dataDir }] }), { mode: 0o600 });
+ cpSync(await seededSourceTemplate(), dataDir, { recursive: true });
await withEnv({ GBRAIN_HOME: home }, async () => {
const source = await openPglite(dataDir);
try {
- await source.initSchema();
- await source.executeRaw(PROBE_DDL);
- await source.executeRaw(`INSERT INTO grad_probe VALUES (1,'alpha'),(2,'beta'),(3,'gamma')`);
- await source.executeRaw(`INSERT INTO access_tokens (id, name, token_hash) VALUES ($1::uuid, 'agent-example', 'hash-a1')`, [SOURCE_TOKEN_ID]);
+ await source.executeRaw(`UPDATE persistence_brain SET brain_id = gen_random_uuid() WHERE singleton = 1`);
+ await source.executeRaw(`UPDATE shared_skill_state SET token_secret = replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', ''), serving_epoch = gen_random_uuid() WHERE singleton = 1`);
} finally { await source.disconnect(); }
});
const { engine: target, drop: dropTarget } = await freshTarget(opts);