Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(cli): D2 success + failure --json cases for the remaining commands

garrytan3f121460ebaa
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 8cc8f5aa77..5ff5ec0905 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -58,6 +58,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Fix wave 5 shared commit: preview-bound approved sets in op_checkpoints.
"src/core/persistence/preview-approval.ts": ["test/e2e/preview-approval-postgres.test.ts", "test/e2e/minions-legacy-journey-postgres.test.ts"],
// #5157: the legacy recovery commands and doctor check.
+ // Agent operator wave D2: the Postgres-only --json successes (db-repair healthy, supervisor --detach).
+ "src/commands/db-repair.ts": ["test/e2e/cli-json-commands-postgres.test.ts"],
+ "src/commands/jobs/supervisor.ts": ["test/e2e/cli-json-commands-postgres.test.ts"],
"src/commands/jobs/authorize-legacy.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
"src/commands/jobs/cancel.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
"src/commands/doctor/checks/legacy-job-authority.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.json
index fb4d41e838..164df4a99d 100644
--- a/scripts/e2e-weights.json
+++ b/scripts/e2e-weights.json
@@ -25,6 +25,7 @@
"test/e2e/chunker-takes-strip.test.ts": 1260,
"test/e2e/cjk-roundtrip.test.ts": 1670,
"test/e2e/claude-plugin-install-real.serial.test.ts": 544,
+ "test/e2e/cli-json-commands-postgres.test.ts": 2900,
"test/e2e/cli-source-scoping-pglite.test.ts": 1560,
"test/e2e/client-grants.test.ts": 1850,
"test/e2e/code-edges-jsonb-postgres.test.ts": 1149,
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index 2e07cd192c..9d62208c19 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -47,6 +47,7 @@
"test/cli-error-render.serial.test.ts": 3,
"test/cli-help-curated.serial.test.ts": 5,
"test/cli-help-without-brain.serial.test.ts": 21,
+ "test/cli-json-commands.serial.test.ts": 37,
"test/cli-json-guard.serial.test.ts": 17,
"test/cli-util-prompt.serial.test.ts": 3,
"test/code-callers-pin.serial.test.ts": 11,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 21f543dd86..d867d05e74 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -27,6 +27,7 @@
"e2e:test/e2e/chunker-takes-strip.test.ts": 1073,
"e2e:test/e2e/cjk-roundtrip.test.ts": 1740,
"e2e:test/e2e/claude-plugin-install-real.serial.test.ts": 523,
+ "e2e:test/e2e/cli-json-commands-postgres.test.ts": 2900,
"e2e:test/e2e/cli-source-scoping-pglite.test.ts": 1931,
"e2e:test/e2e/client-grants.test.ts": 2180,
"e2e:test/e2e/code-edges-jsonb-postgres.test.ts": 807,
@@ -322,6 +323,7 @@
"serial:test/cli-error-render.serial.test.ts": 3000,
"serial:test/cli-help-curated.serial.test.ts": 5000,
"serial:test/cli-help-without-brain.serial.test.ts": 21000,
+ "serial:test/cli-json-commands.serial.test.ts": 37000,
"serial:test/cli-json-guard.serial.test.ts": 17000,
"serial:test/cli-util-prompt.serial.test.ts": 2644,
"serial:test/code-callers-pin.serial.test.ts": 2975,
diff --git a/test/cli-json-commands.serial.test.ts b/test/cli-json-commands.serial.test.ts
new file mode 100644
index 0000000000..3b439645c1
--- /dev/null
+++ b/test/cli-json-commands.serial.test.ts
@@ -0,0 +1,248 @@
+/**
+ * Agent contract v1 (D2), the remaining command migrations: under `--json`
+ * stdout carries exactly one document (or, for NDJSON commands, lines that
+ * end a failure with a `{status:"error", …envelope}` line), a failure is an
+ * envelope with `code` + `suggestion`, and legacy keys stay. Subprocesses
+ * against a keyless PGLite brain (and an unreachable-Postgres config for
+ * the paths that need one); the Postgres-only successes (db-repair healthy,
+ * jobs supervisor start --detach) live in
+ * test/e2e/cli-json-commands-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli, type CliResult } from './helpers/cli-spawn.ts';
+
+const EVAL_FIXTURES = join(import.meta.dir, 'fixtures', 'eval-baselines');
+const QRELS = join(EVAL_FIXTURES, 'qrels-search.json');
+const CAPTURED = join(EVAL_FIXTURES, 'captured-sample.ndjson');
+const UNREACHABLE_PG = 'postgresql://fixture:[email protected]:1/gbrain_test';
+
+function onlyDocument(r: CliResult): Record<string, unknown> {
+ const doc = JSON.parse(r.stdout);
+ expect(typeof doc).toBe('object');
+ return doc as Record<string, unknown>;
+}
+
+function lines(r: CliResult): Array<Record<string, unknown>> {
+ return r.stdout.split('\n').filter(l => l.trim() !== '').map(l => JSON.parse(l) as Record<string, unknown>);
+}
+
+function expectEnvelope(doc: Record<string, unknown>, code: string): void {
+ expect(doc.code).toBe(code);
+ expect(typeof doc.suggestion).toBe('string');
+ expect(doc.contract_version).toBe(1);
+}
+
+let brain = '';
+let pgHome = '';
+const cli = (args: string[], home = brain, env?: Record<string, string | undefined>) =>
+ runCli(args, { home, cwd: home, timeoutMs: 120_000, ...(env ? { env } : {}) });
+
+function freshHome(prefix: string): string {
+ return mkdtempSync(join(tmpdir(), prefix));
+}
+
+beforeAll(async () => {
+ brain = freshHome('gbrain-json-cmds-brain-');
+ const init = await cli(['init', '--pglite', '--no-embedding', '--json']);
+ if (init.exitCode !== 0) throw new Error(`fixture init failed: ${init.stderr}`);
+ pgHome = freshHome('gbrain-json-cmds-pg-');
+ mkdirSync(join(pgHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(pgHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: UNREACHABLE_PG }));
+}, 150_000);
+
+afterAll(() => {
+ for (const home of [brain, pgHome]) if (home) rmSync(home, { recursive: true, force: true });
+});
+
+describe('apply-migrations --json', () => {
+ test('dry run: one document with the plan; unknown --migration: invalid_params envelope (exit 2) leading with the plan keys', async () => {
+ const ok = await cli(['apply-migrations', '--dry-run', '--json']);
+ expect(ok.exitCode).toBe(0);
+ const doc = onlyDocument(ok);
+ expect(doc).toMatchObject({ status: 'dry_run' });
+ expect(Array.isArray((doc.plan as { pending: unknown[] }).pending)).toBe(true);
+
+ const bad = await cli(['apply-migrations', '--json', '--migration', '9.9.9']);
+ expect(bad.exitCode).toBe(2);
+ const env = onlyDocument(bad);
+ expectEnvelope(env, 'invalid_params');
+ expect(env).toMatchObject({ status: 'invalid', fix: { argv: ['gbrain', 'apply-migrations', '--list'] } });
+ }, 120_000);
+
+ test('a real run: one document with per-migration results; --list is a document too', async () => {
+ const run = await cli(['apply-migrations', '--yes', '--no-autopilot-install', '--json']);
+ expect(run.exitCode).toBe(0);
+ const doc = onlyDocument(run);
+ expect(doc.status === 'ok' || doc.status === 'partial').toBe(true);
+ expect((doc.results as unknown[]).length).toBeGreaterThan(0);
+ const list = await cli(['apply-migrations', '--list', '--json']);
+ expect(list.exitCode).toBe(0);
+ expect(onlyDocument(list)).toMatchObject({ status: 'listed' });
+ }, 240_000);
+
+ test('A4: the v0.11.0 autopilot install needs consent (exit 3 payload); --no-autopilot-install skips the ask and the failure is migration_failed', async () => {
+ const ask = await cli(['apply-migrations', '--migration', '0.11.0', '--json'], pgHome);
+ expect(ask.exitCode).toBe(3);
+ expect(onlyDocument(ask)).toMatchObject({
+ code: 'confirmation_required', effects: ['persistent_install'],
+ fix: { argv: ['gbrain', 'apply-migrations', '--migration', '0.11.0', '--yes'], next: 'ask_user' },
+ });
+ const skip = await cli(['apply-migrations', '--migration', '0.11.0', '--no-autopilot-install', '--json'], pgHome);
+ expect(skip.exitCode).toBe(1);
+ const env = onlyDocument(skip);
+ expectEnvelope(env, 'migration_failed');
+ expect(env).toMatchObject({ status: 'failed', reason: 'orchestrator_failed', results: [{ version: '0.11.0', status: 'failed' }] });
+ }, 120_000);
+
+ test('no brain: the unconfigured document (exit 0)', async () => {
+ const empty = freshHome('gbrain-json-cmds-empty-');
+ try {
+ const r = await cli(['apply-migrations', '--json'], empty);
+ expect(r.exitCode).toBe(0);
+ expect(onlyDocument(r)).toMatchObject({ status: 'unconfigured', previews: [] });
+ } finally {
+ rmSync(empty, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
+
+describe('post-upgrade --json', () => {
+ test('success: one report; a failing apply-migrations: one envelope leading with the report', async () => {
+ const empty = freshHome('gbrain-json-cmds-pu-');
+ try {
+ const ok = await cli(['post-upgrade', '--json', '--no-autopilot-install'], empty, { GBRAIN_SKIP_REFERENCE_SWEEP: '1' });
+ expect(ok.exitCode).toBe(0);
+ expect(onlyDocument(ok)).toMatchObject({ status: 'ok', warnings: [] });
+ } finally {
+ rmSync(empty, { recursive: true, force: true });
+ }
+ const bad = await cli(['post-upgrade', '--json'], pgHome, { GBRAIN_SKIP_REFERENCE_SWEEP: '1' });
+ expect(bad.exitCode).toBe(1);
+ const env = onlyDocument(bad);
+ expectEnvelope(env, 'migration_failed');
+ expect(env).toMatchObject({ status: 'failed', apply_migrations: { exit_code: 1 } });
+ }, 180_000);
+});
+
+describe('db-repair --json', () => {
+ test('an unreachable Postgres: one database_error envelope leading with the diagnosis report', async () => {
+ const r = await cli(['db-repair', '--json'], pgHome);
+ expect(r.exitCode).toBe(1);
+ const env = onlyDocument(r);
+ expectEnvelope(env, 'database_error');
+ expect(env).toMatchObject({ schema_version: 1, reason: 'conn_refused', tier: 'auto', fixed: false, fix: { argv: ['gbrain', 'db-repair', '--yes'] } });
+ }, 60_000);
+
+ test('a PGLite brain: config_error naming pglite-repair; a bad flag combination: invalid_params (exit 2)', async () => {
+ const pglite = await cli(['db-repair', '--json']);
+ expect(pglite.exitCode).toBe(1);
+ expect(onlyDocument(pglite)).toMatchObject({ code: 'config_error', fix: { argv: ['gbrain', 'pglite-repair', '--help'] } });
+ const flags = await cli(['db-repair', '--apply-rewrites', '--json']);
+ expect(flags.exitCode).toBe(2);
+ expectEnvelope(onlyDocument(flags), 'invalid_params');
+ }, 60_000);
+});
+
+describe('dream --json', () => {
+ test('cycle: one CycleReport document; an unknown phase: invalid_params (exit 2)', async () => {
+ const ok = await cli(['dream', '--json', '--phase', 'lint']);
+ expect(ok.exitCode).toBe(0);
+ expect(onlyDocument(ok)).toMatchObject({ schema_version: '1' });
+ const bad = await cli(['dream', '--json', '--phase', 'garbage']);
+ expect(bad.exitCode).toBe(2);
+ expectEnvelope(onlyDocument(bad), 'invalid_params');
+ }, 120_000);
+
+ test('retriage and reset-key: refusals are envelopes, --list is a document', async () => {
+ const retriage = await cli(['dream', 'retriage', '--json']);
+ expect(retriage.exitCode).toBe(1);
+ expectEnvelope(onlyDocument(retriage), 'config_error');
+ const list = await cli(['dream', 'reset-key', '--list', '--json']);
+ expect(list.exitCode).toBe(0);
+ expect(onlyDocument(list)).toMatchObject({ enabled: true, tripped: [] });
+ const key = await cli(['dream', 'reset-key', 'not-a-key', '--json']);
+ expect(key.exitCode).toBe(2);
+ expectEnvelope(onlyDocument(key), 'invalid_params');
+ }, 120_000);
+});
+
+describe('jobs supervisor start --detach --json', () => {
+ test('a PGLite brain refuses with one config_error envelope; an unknown subcommand is invalid_params', async () => {
+ const r = await cli(['jobs', 'supervisor', 'start', '--detach', '--json']);
+ expect(r.exitCode).toBe(1);
+ expectEnvelope(onlyDocument(r), 'config_error');
+ const sub = await cli(['jobs', 'supervisor', 'bogus', '--json']);
+ expect(sub.exitCode).toBe(2);
+ expectEnvelope(onlyDocument(sub), 'invalid_params');
+ }, 60_000);
+});
+
+describe('NDJSON: eval export / replay / gate, bench publish', () => {
+ test('eval export: one line per captured row; a bad --since ends with one status:error line (exit 2)', async () => {
+ const capture = await cli(['search', 'hello'], brain, { GBRAIN_CONTRIBUTOR_MODE: '1' });
+ expect(capture.exitCode).toBe(0);
+ const ok = await cli(['eval', 'export', '--json']);
+ expect(ok.exitCode).toBe(0);
+ const rows = lines(ok);
+ expect(rows.length).toBeGreaterThan(0);
+ for (const row of rows) expect(row).toMatchObject({ schema_version: 1, tool_name: 'search' });
+ const bad = await cli(['eval', 'export', '--json', '--since', 'bogus']);
+ expect(bad.exitCode).toBe(2);
+ const out = lines(bad);
+ expect(out.length).toBe(1);
+ expect(out[0]).toMatchObject({ status: 'error' });
+ expectEnvelope(out[0]!, 'invalid_params');
+ }, 120_000);
+
+ test('eval replay: one summary line; no --against: one status:error line (exit 2)', async () => {
+ const ok = await cli(['eval', 'replay', '--against', CAPTURED, '--json']);
+ expect(ok.exitCode).toBe(0);
+ const out = lines(ok);
+ expect(out.length).toBe(1);
+ expect(out[0]).toMatchObject({ schema_version: 1, summary: { rows_total: 2 } });
+ const bad = await cli(['eval', 'replay', '--json']);
+ expect(bad.exitCode).toBe(2);
+ const err = lines(bad);
+ expect(err.length).toBe(1);
+ expect(err[0]).toMatchObject({ status: 'error', code: 'invalid_params' });
+ }, 120_000);
+
+ test('eval gate: a pass is one result line; a breached gate is the result line then a gate_failed status:error line', async () => {
+ const det = ['eval', 'gate', '--qrels', QRELS, '--embedder', 'deterministic'];
+ const ok = await cli([...det, '--threshold-recall-at-k', '0', '--threshold-first-relevant-hit', '0', '--threshold-expected-top1', '0', '--json']);
+ expect(ok.exitCode).toBe(0);
+ const pass = lines(ok);
+ expect(pass.length).toBe(1);
+ expect(pass[0]).toMatchObject({ verdict: 'pass' });
+ const bad = await cli([...det, '--json']);
+ expect(bad.exitCode).toBe(1);
+ const fail = lines(bad);
+ expect(fail.length).toBe(2);
+ expect(fail[0]).toMatchObject({ verdict: 'fail' });
+ expect(fail[1]).toMatchObject({ status: 'error' });
+ expectEnvelope(fail[1]!, 'gate_failed');
+ }, 120_000);
+
+ test('bench publish: one result line; an existing --to: one status:error line (exit 2)', async () => {
+ const home = freshHome('gbrain-json-cmds-bench-');
+ try {
+ const args = ['bench', 'publish', '--from', CAPTURED, '--to', 'sample.baseline.ndjson', '--json'];
+ const ok = await cli(args, home);
+ expect(ok.exitCode).toBe(0);
+ const out = lines(ok);
+ expect(out.length).toBe(1);
+ expect(out[0]).toMatchObject({ schema_version: 1, label: 'sample', row_count: 2 });
+ expect(existsSync(join(home, 'sample.baseline.ndjson'))).toBe(true);
+ const again = await cli(args, home);
+ expect(again.exitCode).toBe(2);
+ const err = lines(again);
+ expect(err.length).toBe(1);
+ expect(err[0]).toMatchObject({ status: 'error', code: 'invalid_params' });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 120_000);
+});
diff --git a/test/e2e/cli-json-commands-postgres.test.ts b/test/e2e/cli-json-commands-postgres.test.ts
new file mode 100644
index 0000000000..c1c99986dc
--- /dev/null
+++ b/test/e2e/cli-json-commands-postgres.test.ts
@@ -0,0 +1,65 @@
+/**
+ * Agent contract v1 (D2): the --json successes that need Postgres — a
+ * healthy `db-repair --json` report and `jobs supervisor start --detach
+ * --json` (one document naming the detached pid, pid file, status and log).
+ * The failure shapes run keyless in test/cli-json-commands.serial.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from '../helpers/cli-spawn.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+const describeDatabase = hasDatabase() ? describe : describe.skip;
+
+function postgresHome(prefix: string): string {
+ const home = mkdtempSync(join(tmpdir(), prefix));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: process.env.DATABASE_URL }));
+ return home;
+}
+
+function alive(pid: number): boolean {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+}
+
+describeDatabase('D2 --json successes against Postgres', () => {
+ beforeAll(async () => { await setupDB(); });
+ afterAll(async () => { await teardownDB(); });
+
+ test('db-repair --json on a healthy database: one healthy report document (exit 0)', async () => {
+ const home = postgresHome('gbrain-json-dbrepair-');
+ try {
+ const r = await runCli(['db-repair', '--json'], { home, cwd: home, timeoutMs: 60_000 });
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(JSON.parse(r.stdout)).toMatchObject({ schema_version: 1, reason: 'healthy', fixed: true, plan: [], applied: [] });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 90_000);
+
+ test('jobs supervisor start --detach --json: one document naming the detached pid, pid file, status and log', async () => {
+ const home = postgresHome('gbrain-json-detach-');
+ const pidFile = join(home, 'supervisor.pid');
+ let pid: number | undefined;
+ try {
+ const r = await runCli(['jobs', 'supervisor', 'start', '--detach', '--json', '--pid-file', pidFile,
+ '--queue', `json-detach-${process.pid}`, '--concurrency', '1', '--health-interval', '0', '--max-rss', '0'],
+ { home, cwd: home, timeoutMs: 60_000 });
+ expect(r.exitCode, r.stderr).toBe(0);
+ const doc = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect(doc).toMatchObject({ event: 'started', status: 'started', pid_file: pidFile, detached: true });
+ expect(typeof doc.supervisor_pid).toBe('number');
+ pid = doc.supervisor_pid as number;
+ if (doc.stderr_log !== undefined) expect(typeof doc.stderr_log).toBe('string');
+ } finally {
+ if (pid !== undefined) {
+ try { process.kill(-pid, 'SIGTERM'); } catch { try { process.kill(pid, 'SIGTERM'); } catch { /* gone */ } }
+ for (let i = 0; i < 40 && alive(pid); i++) await new Promise(res => setTimeout(res, 250));
+ if (alive(pid)) { try { process.kill(-pid, 'SIGKILL'); } catch { /* gone */ } }
+ }
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 90_000);
+});