Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(eval,bench): D2 NDJSON contract for eval export/replay/gate and bench publish
garrytan711e915b2fb6
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 7f9012120b..e24448609f 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -732,6 +732,14 @@ More: [docs/guides/write-refusals.md#fetch_failed](../../docs/guides/write-refus|---|---|---|---|---|---|---|| The catalog cursor is invalid or expired. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### gate_failed++<a id="gate_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The eval gate found retrieval regressions or correctness below its thresholds. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### git_index_locked<a id="git_index_locked"></a>diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.tsindex 935e986d5a..d5080e4de0 100644--- a/src/cli/cli-error.ts+++ b/src/cli/cli-error.ts@@ -10,7 +10,7 @@*/import { cliRenderContext, renderCliError, renderNotice, type AgentEnvelope, type Notice } from '../core/agent-output.ts';import { renderCliNotices } from '../core/agent-markers.ts';-import { jsonRequested, noteRenderedErrorCode, writeStdoutFinal } from '../core/cli-force-exit.ts';+import { jsonGuardActive, jsonRequested, noteRenderedErrorCode, writeStdoutFinal } from '../core/cli-force-exit.ts';import { opError, type OpErrorOpts, type OperationError } from '../core/ops/contract.ts';import type { RegistryCode } from '../core/error-registry.ts';import {@@ -52,7 +52,9 @@ export function writeCliError(e: unknown, command: string, opts: CliErrorWriteOpif (r.stdout !== undefined) {const env = JSON.parse(r.stdout) as AgentEnvelope;noteRenderedErrorCode(env.code);- const doc = opts.legacy ? `${JSON.stringify({ ...opts.legacy, ...withoutUndefined(env), ...opts.legacy })}\n` : r.stdout;+ // An NDJSON stream ends a failure with one `{status:"error", …envelope}` line (D2).+ const legacy = opts.legacy ?? (jsonGuardActive() === 'ndjson' ? { status: 'error' } : undefined);+ const doc = legacy ? `${JSON.stringify({ ...legacy, ...withoutUndefined(env), ...legacy })}\n` : r.stdout;void writeStdoutFinal(doc).catch(() => { /* fd 1 gone */ });// stderr stays the human channel under --json (same TTY order as renderCliError).stderr = [`Error [${env.code}]: ${env.message}`, `Fix: ${env.fix?.command ?? env.suggestion}`,diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 57b977dc6b..c26824fb6a 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -136,7 +136,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// CLI_ONLY_SELF_HELP, so the dispatcher's generic short-circuit fires and the printInitHelp()// guard in init.ts is dead code.{ name: 'init', phase: 'pre-connect', thinClient: 'none', selfHelp: true, json: 'document', load: () => import('./commands/init.ts') },- { name: 'bench', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/bench.ts') },+ { name: 'bench', phase: 'pre-connect', thinClient: 'none', selfHelp: true, json: 'ndjson', load: () => import('./commands/bench.ts') },// selfHelp: v0.37 fix wave (deferred TODO, shipped): reinit-pglite has its own --help in// runReinitPglite. Routing through SELF_HELP avoids the generic short-circuit so the// destructive-action warning text reaches the user.@@ -269,7 +269,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// printHelp (15 subcommands), storage's status usage, reindex's target-flag usage — that the// generic one-line stub was hiding. Their engine-free --help is answered by pre-engine branches in// handleCliOnly (the sync/capture pattern).- { name: 'eval', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/eval.ts') },+ { name: 'eval', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, jsonSubcommands: { export: 'ndjson', replay: 'ndjson', gate: 'ndjson' }, load: () => import('./commands/eval.ts') },// selfHelp: jobs ships JOBS_HELP + a per-subcommand record (JOBS_SUBCOMMAND_HELP) in jobs.ts,// guarded BEFORE the thin-client refusal and the subcommand switch so `jobs work --help` prints// help instead of starting a worker daemon. Without this entry the generic stub hid the workerdiff --git a/src/cli/commands/bench.ts b/src/cli/commands/bench.tsindex d08366f1fb..cc1502cfc4 100644--- a/src/cli/commands/bench.ts+++ b/src/cli/commands/bench.ts@@ -3,6 +3,8 @@* handleCliOnly before the connectEngine() terminator. Moved verbatim from* src/cli.ts (refactor wave 1, W4 cli); the record lives in src/cli/command-table.ts.*/+import { jsonRequested } from '../../core/cli-force-exit.ts';+import { usageError, writeCliRefusal } from '../cli-error.ts';export async function run(args: string[]): Promise<void> {if (args[0] === 'publish') {@@ -10,7 +12,13 @@ export async function run(args: string[]): Promise<void> {await runBenchPublish(args.slice(1));return;}- console.error('Usage: gbrain bench publish --from <captured.ndjson> --to <X.baseline.ndjson> [flags]');- console.error('Run `gbrain bench publish --help` for the full flag list.');- process.exit(args[0] === '--help' || args[0] === '-h' ? 0 : 2);+ const usage = 'Usage: gbrain bench publish --from <captured.ndjson> --to <X.baseline.ndjson> [flags]';+ if (args[0] === '--help' || args[0] === '-h') {+ console.error(usage);+ console.error('Run `gbrain bench publish --help` for the full flag list.');+ process.exit(0);+ }+ process.exit(writeCliRefusal(usageError(args[0] && !args[0].startsWith('-') ? `Unknown bench subcommand: ${args[0]}.` : 'gbrain bench needs a subcommand (publish).',+ 'Run `gbrain bench publish --help` for the full flag list.'), 'bench',+ { json: jsonRequested(args), human: `${usage}\nRun \`gbrain bench publish --help\` for the full flag list.` }));}diff --git a/src/commands/bench-publish.ts b/src/commands/bench-publish.tsindex dfd9899645..2154ea880c 100644--- a/src/commands/bench-publish.ts+++ b/src/commands/bench-publish.ts@@ -39,6 +39,9 @@ import {type BaselineThresholds,} from '../core/bench/baseline-file.ts';import { createAuditWriter } from '../core/audit/audit-writer.ts';+import { jsonRequested, writeJsonLine } from '../core/cli-force-exit.ts';+import { opError, type OperationError } from '../core/ops/contract.ts';+import { usageError, writeCliRefusal } from '../cli/cli-error.ts';interface PublishOpts {help?: boolean;@@ -273,24 +276,24 @@ export async function runBenchPublish(args: string[]): Promise<void> {return;}- // USAGE checks (exit 2)+ // USAGE checks (exit 2). D2: each refusal keeps its stderr line; under+ // --json the stream ends with the status:error envelope line.+ const json = jsonRequested(args);+ const fail: (e: OperationError) => never = e => process.exit(writeCliRefusal(e, 'bench', { json }));+ const example = 'Example: gbrain bench publish --from captured.ndjson --to personal.baseline.ndjson --json';if (!opts.from) {- console.error('Error: --from FILE is required\n');printHelp();- process.exit(2);+ fail(usageError('Error: --from FILE is required', example));}if (!opts.to) {- console.error('Error: --to FILE is required\n');printHelp();- process.exit(2);+ fail(usageError('Error: --to FILE is required', example));}if (!existsSync(opts.from)) {- console.error(`Error: --from file not found: ${opts.from}`);- process.exit(1);+ fail(opError('not_found', `Error: --from file not found: ${opts.from}`, 'Capture one first: gbrain eval export --tool query > captured.ndjson'));}if (existsSync(opts.to) && !opts.force) {- console.error(`Error: --to path already exists: ${opts.to}\nUse --force to overwrite.`);- process.exit(2);+ fail(usageError(`Error: --to path already exists: ${opts.to}\nUse --force to overwrite.`, 'Pass --force to overwrite it, or choose another --to path.'));}const label = opts.label ?? deriveLabel(opts.to);@@ -301,7 +304,6 @@ export async function runBenchPublish(args: string[]): Promise<void> {input = readInputNdjson(opts.from);} catch (err) {const msg = (err as Error).message;- console.error(`Error: ${msg}`);auditWriter.log({label,source_hash: '',@@ -311,7 +313,7 @@ export async function runBenchPublish(args: string[]): Promise<void> {success: false,failure_reason: msg,});- process.exit(1);+ fail(opError('parse_error', `Error: ${msg}`, 'Pass an NDJSON file written by `gbrain eval export` (one captured row per line).'));}let file: BaselineFile;@@ -322,7 +324,6 @@ export async function runBenchPublish(args: string[]): Promise<void> {});} catch (err) {const msg = (err as Error).message;- console.error(`Error: ${msg}`);auditWriter.log({label,source_hash: '',@@ -332,7 +333,7 @@ export async function runBenchPublish(args: string[]): Promise<void> {success: false,failure_reason: msg,});- process.exit(1);+ fail(opError('parse_error', `Error: ${msg}`, 'Fix the captured rows named above (or de-duplicate them as the message shows), then publish again.'));}const serialized = serializeBaselineFile(file);@@ -341,7 +342,6 @@ export async function runBenchPublish(args: string[]): Promise<void> {writeFileSync(outputPath, serialized);} catch (err) {const msg = (err as Error).message;- console.error(`Error: could not write baseline to ${outputPath}: ${msg}`);auditWriter.log({label,source_hash: file.metadata.source_hash,@@ -351,7 +351,7 @@ export async function runBenchPublish(args: string[]): Promise<void> {success: false,failure_reason: msg,});- process.exit(1);+ fail(opError('storage_error', `Error: could not write baseline to ${outputPath}: ${msg}`, 'Choose a writable --to path.'));}auditWriter.log({@@ -364,7 +364,7 @@ export async function runBenchPublish(args: string[]): Promise<void> {});if (opts.json) {- console.log(JSON.stringify({+ const doc = {schema_version: 1,output_path: outputPath,label: file.metadata.label,@@ -372,7 +372,9 @@ export async function runBenchPublish(args: string[]): Promise<void> {row_count: file.rows.length,baseline_mean_latency_ms: file.metadata.baseline_mean_latency_ms,thresholds: file.metadata.thresholds,- }, null, 2));+ };+ // D2: one NDJSON line under the --json guard; the legacy pretty document otherwise.+ await writeJsonLine(doc, () => console.log(JSON.stringify(doc, null, 2)));} else {console.log(`Wrote ${outputPath}`);console.log(` Label: ${file.metadata.label}`);diff --git a/src/commands/eval-export.ts b/src/commands/eval-export.tsindex adc256d485..0ec2086f5d 100644--- a/src/commands/eval-export.ts+++ b/src/commands/eval-export.ts@@ -16,6 +16,8 @@import type { BrainEngine } from '../core/engine.ts';import type { EvalCandidate } from '../core/types.ts';+import { jsonGuardActive, jsonRequested, writeNdjsonLine } from '../core/cli-force-exit.ts';+import { usageError, writeCliRefusal } from '../cli/cli-error.ts';const SCHEMA_VERSION = 1;@@ -58,8 +60,8 @@ function parseArgs(args: string[]): ExportOpts {if (ms !== null) {opts.since = new Date(Date.now() - ms);} else {- console.error(`Invalid --since value: ${next} (use like 7d, 1h, 30m)`);- process.exit(1);+ process.exit(writeCliRefusal(usageError(`Invalid --since value: ${next} (use like 7d, 1h, 30m)`,+ 'Example: gbrain eval export --since 7d'), 'eval', { json: jsonRequested(args) }));}i++;break;@@ -72,8 +74,8 @@ function parseArgs(args: string[]): ExportOpts {if (next === 'query' || next === 'search') {opts.tool = next;} else if (next) {- console.error(`Invalid --tool value: ${next} (use 'query' or 'search')`);- process.exit(1);+ process.exit(writeCliRefusal(usageError(`Invalid --tool value: ${next} (use 'query' or 'search')`,+ 'Example: gbrain eval export --tool query'), 'eval', { json: jsonRequested(args) }));}i++;break;@@ -142,6 +144,13 @@ export async function runEvalExport(engine: BrainEngine, args: string[]): Promislet written = 0;for (const row of rows) {+ // D2: under the --json guard each row is one NDJSON line on fd 1.+ if (jsonGuardActive()) {+ await writeNdjsonLine({ schema_version: SCHEMA_VERSION, ...row });+ written++;+ progress.tick();+ continue;+ }// Prefix every line with schema_version:1 so gbrain-evals can detect// schema drift before parsing the rest of the fields.const line = JSON.stringify({ schema_version: SCHEMA_VERSION, ...row });diff --git a/src/commands/eval-gate.ts b/src/commands/eval-gate.tsindex 9853d4640f..025284b02f 100644--- a/src/commands/eval-gate.ts+++ b/src/commands/eval-gate.ts@@ -30,6 +30,9 @@import { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from '../core/engine.ts';+import { jsonGuardActive, jsonRequested, writeJsonLine } from '../core/cli-force-exit.ts';+import { usageError, writeCliError, writeCliRefusal } from '../cli/cli-error.ts';+import { opError } from '../core/ops/contract.ts';import {parseBaselineFile,type BaselineFile,@@ -457,42 +460,31 @@ export async function runEvalGate(engine: BrainEngine, args: string[]): Promise<return;}+ const json = jsonRequested(args);+ const usage: (message: string, suggestion?: string) => never = (message, suggestion = 'Example: gbrain eval gate --qrels Y.qrels.json --json') =>+ process.exit(writeCliRefusal(usageError(message, suggestion), 'eval', { json }));if (!opts.baseline && !opts.qrels) {- console.error('Error: at least one of --baseline or --qrels must be set\n');printHelp();- process.exit(2);+ usage('Error: at least one of --baseline or --qrels must be set');}- if (opts.baseline && !existsSync(opts.baseline)) {- console.error(`Error: baseline file not found: ${opts.baseline}`);- process.exit(2);- }- if (opts.qrels && !existsSync(opts.qrels)) {- console.error(`Error: qrels file not found: ${opts.qrels}`);- process.exit(2);- }+ if (opts.baseline && !existsSync(opts.baseline)) usage(`Error: baseline file not found: ${opts.baseline}`, 'Pass an existing --baseline file (write one with `gbrain bench publish`).');+ if (opts.qrels && !existsSync(opts.qrels)) usage(`Error: qrels file not found: ${opts.qrels}`, 'Pass an existing --qrels file.');// Hermetic embedder validation. Only 'deterministic' is supported; the// regression gate is out of scope (replay re-embeds captured queries via// the gateway, which needs a provider key — defeating the hermetic point).if (opts.embedder !== undefined) {if (opts.embedder !== 'deterministic') {- console.error(- `Error: unsupported embedder "${opts.embedder}" — the only supported value is "deterministic".`,- );- process.exit(2);+ usage(`Error: unsupported embedder "${opts.embedder}" — the only supported value is "deterministic".`,+ 'Example: gbrain eval gate --qrels Y.qrels.json --embedder deterministic');}if (opts.baseline) {- console.error(- 'Error: the deterministic embedder cannot be combined with the baseline regression gate ' ++ usage('Error: the deterministic embedder cannot be combined with the baseline regression gate ' +'(replay re-embeds captured queries via the gateway). Use it with the qrels correctness gate only.',- );- process.exit(2);- }- if (!opts.qrels) {- console.error('Error: the deterministic embedder requires a qrels file.');- process.exit(2);+ 'Run the deterministic embedder with --qrels only.');}+ if (!opts.qrels) usage('Error: the deterministic embedder requires a qrels file.', 'Example: gbrain eval gate --qrels Y.qrels.json --embedder deterministic');}const result: GateResult = {@@ -527,10 +519,8 @@ export async function runEvalGate(engine: BrainEngine, args: string[]): Promise<const { buildQrelsQueryEmbedFn } = await import('../eval/deterministic-embed.ts');queryEmbedFn = buildQrelsQueryEmbedFn(readFileSync(opts.qrels, 'utf-8'));} catch (err) {- console.error(- `Error: could not build the deterministic embedder from ${opts.qrels}: ${(err as Error).message}`,- );- process.exit(2);+ usage(`Error: could not build the deterministic embedder from ${opts.qrels}: ${(err as Error).message}`,+ 'Fix the qrels file (it must parse as a qrels fixture).');}const { hybridSearch } = await import('../core/search/hybrid.ts');deterministicSearchFn = async (e, q, o) => {@@ -550,12 +540,21 @@ export async function runEvalGate(engine: BrainEngine, args: string[]): Promise<}if (opts.json) {- console.log(JSON.stringify(result, null, 2));+ // D2: one NDJSON line under the --json guard; the legacy pretty document otherwise.+ await writeJsonLine(result, () => console.log(JSON.stringify(result, null, 2)));} else {printHumanOutput(result);}- if (result.verdict === 'fail') process.exit(1);+ if (result.verdict !== 'fail') return;+ // D2: under the --json guard the stream ends with the status:error line naming the failed gate.+ if (jsonGuardActive()) {+ const breached = [...(result.regression_gate.breaches ?? []), ...(result.correctness_gate.breaches ?? [])].map(b => b.metric);+ process.exit(writeCliError(opError('gate_failed', `The eval gate failed: ${breached.join(', ') || 'thresholds breached'}.`,+ 'Read the result line\'s breaches. Fix the retrieval regression, or (if the change is intended) publish a new baseline with `gbrain bench publish`.'),+ 'eval', { json: true, stderr: false }));+ }+ process.exit(1);}// Exported for tests + e2e LOOP testdiff --git a/src/commands/eval-replay.ts b/src/commands/eval-replay.tsindex 22f0ccbff9..9df0e496eb 100644--- a/src/commands/eval-replay.ts+++ b/src/commands/eval-replay.ts@@ -28,6 +28,9 @@import { readFileSync, existsSync } from 'fs';import type { BrainEngine } from '../core/engine.ts';+import { jsonRequested, writeJsonLine } from '../core/cli-force-exit.ts';+import { opError } from '../core/ops/contract.ts';+import { usageError, writeCliRefusal } from '../cli/cli-error.ts';import type { SearchResult } from '../core/types.ts';import { hybridSearch } from '../core/search/hybrid.ts';@@ -150,7 +153,11 @@ OUTPUT (human mode):EXIT CODE:0 — replay completed (regardless of regression magnitude).- 1 — invalid args, --against not found, or NDJSON parse failure.+ 1 — --against not found, or NDJSON parse failure.+ 2 — invalid args (missing --against, bad --mode).++ --json: one NDJSON result line; a failure ends with a+ {"status":"error", code, suggestion, ...} line.NOTES:Replay is best-effort. Your brain has more pages than when the snapshot@@ -440,15 +447,21 @@ export async function replayCore(}export async function runEvalReplay(engine: BrainEngine, args: string[]): Promise<void> {- const opts = parseArgs(args);+ const json = jsonRequested(args);+ let opts: ReplayOpts;+ try {+ opts = parseArgs(args);+ } catch (e) {+ process.exit(writeCliRefusal(usageError(`Error: ${(e as Error).message}`, 'Example: gbrain eval replay --against captured.ndjson --mode balanced'), 'eval', { json }));+ }if (opts.help) {printHelp();return;}if (!opts.against) {- console.error('Error: --against FILE.ndjson is required\n');printHelp();- process.exit(1);+ process.exit(writeCliRefusal(usageError('Error: --against FILE.ndjson is required',+ 'Example: gbrain eval replay --against captured.ndjson --json'), 'eval', { json }));}if (!opts.json) {@@ -471,16 +484,15 @@ export async function runEvalReplay(engine: BrainEngine, args: string[]): Promissummary = out.summary;results = out.results;} catch (err) {- console.error(`Error: ${(err as Error).message}`);- process.exit(1);+ const msg = (err as Error).message;+ process.exit(writeCliRefusal(opError(msg.startsWith('File not found') ? 'not_found' : 'parse_error', `Error: ${msg}`,+ 'Pass an NDJSON file written by `gbrain eval export` (one captured row per line).'), 'eval', { json }));}if (opts.json) {- console.log(JSON.stringify({- schema_version: 1,- summary,- results: opts.verbose ? results : undefined,- }, null, 2));+ // D2: one NDJSON line under the --json guard; the legacy pretty document otherwise.+ const doc = { schema_version: 1, summary, results: opts.verbose ? results : undefined };+ await writeJsonLine(doc, () => console.log(JSON.stringify(doc, null, 2)));return;}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex f3e659ac57..21c0489f68 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -125,6 +125,7 @@ export const CODES = {facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },+ gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },git_index_locked: { class: 'retryable', summary: "Another Git process holds the canonical checkout index lock." },git_index_stale: { class: 'caller', summary: "Git index stale." },git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },diff --git a/test/cli-contract.serial.test.ts b/test/cli-contract.serial.test.tsindex 0dbf10ce97..90d5970967 100644--- a/test/cli-contract.serial.test.ts+++ b/test/cli-contract.serial.test.ts@@ -80,8 +80,14 @@ interface JsonRow {okOnEmpty?: boolean;/** The succeeding invocation needs Postgres: the E2E file (test/e2e/…) that asserts it instead. */okE2E?: string;+ /** NDJSON only: zero lines is a valid success (e.g. an export of an empty table). */+ okMayBeEmpty?: true;}+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');+/** One row per command-table record that declares `json`; a new declaration needs a row. */const JSON_ROWS: Record<string, JsonRow> = {errors: { ok: ['errors', 'unknown_flag', '--json'], fail: ['errors', 'definitely_not_a_code', '--json'], okOnEmpty: true },@@ -92,14 +98,26 @@ const JSON_ROWS: Record<string, JsonRow> = {'db-repair': { ok: ['db-repair', '--json'], fail: ['db-repair', '--json'], failOnBrain: true, okE2E: 'test/e2e/cli-json-commands-postgres.test.ts' },dream: { ok: ['dream', '--json', '--phase', 'lint'], fail: ['dream', '--json', '--phase', 'garbage'] },'post-upgrade': { ok: ['post-upgrade', '--json', '--no-autopilot-install'], fail: ['post-upgrade', '--bogus', '--json'], okOnEmpty: true },+ bench: { ok: ['bench', 'publish', '--from', CAPTURED, '--to', 'sample.baseline.ndjson', '--json'], fail: ['bench', 'publish', '--json'], okOnEmpty: true },+ 'eval export': { ok: ['eval', 'export', '--json'], fail: ['eval', 'export', '--json', '--since', 'bogus'], failOnBrain: true, okMayBeEmpty: true },+ 'eval replay': { ok: ['eval', 'replay', '--against', CAPTURED, '--json'], fail: ['eval', 'replay', '--json'], failOnBrain: true },+ 'eval gate': {+ ok: ['eval', 'gate', '--qrels', QRELS, '--embedder', 'deterministic', '--threshold-recall-at-k', '0', '--threshold-first-relevant-hit', '0', '--threshold-expected-top1', '0', '--json'],+ fail: ['eval', 'gate', '--qrels', QRELS, '--embedder', 'deterministic', '--json'], failOnBrain: true,+ },'apply-migrations': { ok: ['apply-migrations', '--dry-run', '--json'], fail: ['apply-migrations', '--json', '--migration', '9.9.9'], failOnBrain: true },};function parsedShape(mode: 'document' | 'ndjson', stdout: string): unknown[] {if (mode === 'document') return [JSON.parse(stdout)];- return stdout.trim().split('\n').map(l => JSON.parse(l));+ return stdout.split('\n').filter(l => l.trim() !== '').map(l => JSON.parse(l));}+/** json-declared records, plus `<command> <sub>` for each per-subcommand declaration. */+const JSON_DECLARED: ReadonlyArray<{ name: string; mode: 'document' | 'ndjson' }> = CLI_COMMANDS.flatMap(c => c.json+ ? [{ name: c.name, mode: c.json }]+ : Object.entries(c.jsonSubcommands ?? {}).map(([sub, mode]) => ({ name: `${c.name} ${sub}`, mode })));+function assertFailureShape(name: string, mode: 'document' | 'ndjson', r: CliResult): void {expect(r.exitCode, `${name}: failing invocation exits non-zero`).not.toBe(0);const docs = parsedShape(mode, r.stdout) as Array<Record<string, unknown>>;@@ -126,11 +144,11 @@ describe('D5 json contract: one success and one failure per json-declared comman}, 240_000);test('every json-declared record has a contract row', () => {- const declared = CLI_COMMANDS.filter(c => c.json).map(c => c.name).sort();+ const declared = JSON_DECLARED.map(c => c.name).sort();expect(declared).toEqual(Object.keys(JSON_ROWS).sort());});- for (const record of CLI_COMMANDS.filter(c => c.json)) {+ for (const record of JSON_DECLARED) {test(`${record.name} --json: success shape and failure envelope`, async () => {const row = JSON_ROWS[record.name];if (!row) throw new Error(`no D5 row for json-declared command ${record.name}`);@@ -142,10 +160,11 @@ describe('D5 json contract: one success and one failure per json-declared comman} else {const ok = await runCli(row.ok, { home: okHome, cwd: okHome, timeoutMs: 120_000 });expect(ok.exitCode, `${record.name} ok: ${ok.stderr.slice(-800)}`).toBe(0);- expect(parsedShape(record.json!, ok.stdout).length).toBeGreaterThan(0);+ const lines = parsedShape(record.mode, ok.stdout).length;+ if (!row.okMayBeEmpty) expect(lines).toBeGreaterThan(0);}const failHome = row.failOnBrain ? brainHome : emptyHome;- assertFailureShape(record.name, record.json!, await runCli(row.fail, { home: failHome, cwd: failHome, timeoutMs: 120_000 }));+ assertFailureShape(record.name, record.mode, await runCli(row.fail, { home: failHome, cwd: failHome, timeoutMs: 120_000 }));} finally {rmSync(fresh, { recursive: true, force: true });}diff --git a/test/eval-export.test.ts b/test/eval-export.test.tsindex 966da281a6..6da524c0a7 100644--- a/test/eval-export.test.ts+++ b/test/eval-export.test.ts@@ -136,7 +136,7 @@ describe('gbrain eval export — NDJSON shape', () => {expect(lines.length).toBeLessThanOrEqual(1);});- test('invalid --tool value exits 1 (via process.exit mock check)', async () => {+ test('invalid --tool value exits 2 (invalid_params, D4; via process.exit mock check)', async () => {// Replace process.exit so we can see the exit code without killing bun.const originalExit = process.exit;let exitCode: number | undefined;@@ -149,10 +149,10 @@ describe('gbrain eval export — NDJSON shape', () => {await captureExport(['--tool', 'dance']);} catch { /* expected */ }process.exit = originalExit;- expect(exitCode).toBe(1);+ expect(exitCode).toBe(2);});- test('invalid --since format exits 1', async () => {+ test('invalid --since format exits 2 (invalid_params, D4)', async () => {const originalExit = process.exit;let exitCode: number | undefined;// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -164,7 +164,7 @@ describe('gbrain eval export — NDJSON shape', () => {await captureExport(['--since', 'yesterday']);} catch { /* expected */ }process.exit = originalExit;- expect(exitCode).toBe(1);+ expect(exitCode).toBe(2);});test('output is stream-friendly: each row on its own \\n-terminated line', async () => {diff --git a/test/eval-replay.test.ts b/test/eval-replay.test.tsindex c9d79e0a8a..f903562b40 100644--- a/test/eval-replay.test.ts+++ b/test/eval-replay.test.ts@@ -322,7 +322,7 @@ describe('gbrain eval replay — happy path', () => {});describe('gbrain eval replay — failure modes', () => {- test('missing --against errors and exits 1', async () => {+ test('missing --against errors and exits 2 (invalid_params, D4)', async () => {const origExit = process.exit;let code: number | undefined;process.exit = (c?: number) => { code = c; throw new Error('exit'); };@@ -332,7 +332,7 @@ describe('gbrain eval replay — failure modes', () => {} catch { /* expected */ }cap.restore();process.exit = origExit;- expect(code).toBe(1);+ expect(code).toBe(2);});test('--against pointing at missing file errors and exits 1', async () => {diff --git a/test/fixtures/eval-baselines/captured-sample.ndjson b/test/fixtures/eval-baselines/captured-sample.ndjsonnew file mode 100644index 0000000000..0f10064454--- /dev/null+++ b/test/fixtures/eval-baselines/captured-sample.ndjson@@ -0,0 +1,2 @@+{"schema_version":1,"id":1,"tool_name":"search","query":"hello world","retrieved_slugs":["example"],"source_ids":["notes"],"latency_ms":12,"created_at":"2026-01-01T00:00:00.000Z"}+{"schema_version":1,"id":2,"tool_name":"search","query":"example note","retrieved_slugs":[],"source_ids":["notes"],"latency_ms":9,"created_at":"2026-01-01T00:00:01.000Z"}