Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(agent-contract): --json stdout guard mode, fallback document, spawnCliChild; gbrain call and the fatal seam render the v1 envelope

garrytan6055e16fe411
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index 806cdf316a..dd7a309235 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -44,6 +44,7 @@
"test/check-update-refresh.serial.test.ts": 0,
"test/checkpoint-harvest.serial.test.ts": 9,
"test/cli-help-without-brain.serial.test.ts": 16,
+ "test/cli-json-guard.serial.test.ts": 4,
"test/cli-util-prompt.serial.test.ts": 3,
"test/code-callers-pin.serial.test.ts": 11,
"test/code-def-refs-pin.serial.test.ts": 12,
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 59c79f477e..8e38e81086 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -14,6 +14,8 @@
"test/advisor-op-gate.test.ts": 17,
"test/advisor-ranking-eval.test.ts": 22,
"test/agent-cli.test.ts": 357,
+ "test/agent-contract-a0.test.ts": 1,
+ "test/agent-contract-goldens.test.ts": 1,
"test/agent-install.test.ts": 137,
"test/agent-register.test.ts": 347,
"test/agent-runner.test.ts": 6,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 74426dc719..53142c7cea 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -319,6 +319,7 @@
"serial:test/check-update-refresh.serial.test.ts": 356,
"serial:test/checkpoint-harvest.serial.test.ts": 4977,
"serial:test/cli-help-without-brain.serial.test.ts": 9329,
+ "serial:test/cli-json-guard.serial.test.ts": 4000,
"serial:test/cli-util-prompt.serial.test.ts": 2644,
"serial:test/code-callers-pin.serial.test.ts": 2975,
"serial:test/code-def-refs-pin.serial.test.ts": 5089,
@@ -631,6 +632,8 @@
"unit:test/advisor-op-gate.test.ts": 480,
"unit:test/advisor-ranking-eval.test.ts": 548,
"unit:test/agent-cli.test.ts": 2184,
+ "unit:test/agent-contract-a0.test.ts": 400,
+ "unit:test/agent-contract-goldens.test.ts": 400,
"unit:test/agent-install.test.ts": 216,
"unit:test/agent-register.test.ts": 1904,
"unit:test/agent-runner.test.ts": 177,
diff --git a/src/cli.ts b/src/cli.ts
index a98fbdc684..292b0fb664 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -37,7 +37,9 @@ import { formatVolunteeredPage } from './core/context/volunteer.ts';
import type { Operation, OperationContext } from './core/operations.ts';
import { currentCliWriteWait } from './core/persistence/write-wait.ts';
import { isScopeErrorCode } from './core/error-catalogue.ts';
-import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';
+import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery, jsonRequested, noteRenderedErrorCode } from './core/cli-force-exit.ts';
+import { renderCliError } from './core/agent-output.ts';
+import { agentJsonGuardMode } from './cli/json-guard.ts';
import { serializeMarkdown } from './core/markdown.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';
import { runCliPreflight } from './core/cli-preflight.ts';
@@ -3118,12 +3120,18 @@ if (import.meta.main) {
installCleanupSignalHandlers();
// #4383: CLI_ONLY payloads (console.log / bare process.stdout.write) get
// delivery-exact serialized writes; `serve` keeps native streaming stdout.
- if (shouldForceExitAfterMain()) installStdoutPipeDelivery();
+ if (shouldForceExitAfterMain()) installStdoutPipeDelivery(agentJsonGuardMode(process.argv.slice(2)));
main().then(
() => {
if (shouldForceExitAfterMain()) flushThenExit(currentExitCode());
},
(e) => {
+ if (e?.code !== 'pglite_busy' && jsonRequested(process.argv.slice(2))) {
+ const r = renderCliError(e, { json: true, command: process.argv[2] ?? '', tty: false });
+ noteRenderedErrorCode(JSON.parse(r.stdout!).code);
+ void writeStdoutFinal(r.stdout!).finally(() => flushThenExit(r.exitCode));
+ return;
+ }
if (e?.code === 'pglite_busy' && process.argv.includes('--json')) {
console.log(JSON.stringify({ error: 'pglite_busy', retryable: true, reason: e.reason,
next_action: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' }));
diff --git a/src/cli/json-guard.ts b/src/cli/json-guard.ts
new file mode 100644
index 0000000000..5830ac77e8
--- /dev/null
+++ b/src/cli/json-guard.ts
@@ -0,0 +1,18 @@
+/**
+ * Agent contract v1 (D2): which `--json` guard mode this invocation runs
+ * under. The guard is on only for commands whose command-table record
+ * declares `json` (they write their result through writeStdoutFinal /
+ * writeNdjsonLine), so undeclared commands keep their current stdout.
+ * Also wires the E11 `json_document_missing` record for the exit-0 bug case.
+ */
+import { jsonRequested, setJsonDocumentMissingHook } from '../core/cli-force-exit.ts';
+import { recordAgentContractEvent } from '../core/agent-contract-log.ts';
+import { findCliCommand } from './command-table.ts';
+
+export function agentJsonGuardMode(argv: readonly string[]): { json?: 'document' | 'ndjson' } {
+ const command = argv.find(a => !a.startsWith('-') && findCliCommand(a) !== undefined);
+ const json = command ? findCliCommand(command)?.json : undefined;
+ if (!json || !jsonRequested(argv)) return {};
+ setJsonDocumentMissingHook(() => recordAgentContractEvent({ transport: 'cli', command, code: 'json_document_missing', outcome: 'committed' }));
+ return { json };
+}
diff --git a/src/commands/call.ts b/src/commands/call.ts
index a46e9006cd..8eaa9b27ba 100644
--- a/src/commands/call.ts
+++ b/src/commands/call.ts
@@ -2,12 +2,15 @@ import type { BrainEngine } from '../core/engine.ts';
import { handleToolCall } from '../mcp/server.ts';
import { resolveSourceWithTier, localFederatedSourceIds } from '../core/source-resolver.ts';
import { bigintToStringReplacer } from '../core/utils.ts';
-import { writeStdoutFinal } from '../core/cli-force-exit.ts';
import { loadConfig } from '../core/config.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
+import { cliRenderContext, toAgentError } from '../core/agent-output.ts';
+import { exitCodeForCode } from '../core/error-catalogue.ts';
+import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
+import { operations } from '../core/operations.ts';
/**
* `gbrain call <tool> <json>` — trusted local op-dispatch surface.
@@ -99,6 +102,15 @@ export async function runCall(
await out(JSON.stringify(result, bigintToStringReplacer, 2) + '\n');
} catch (error) {
if (await reportPersistenceCliError(error, true, out)) return;
- throw error;
+ // Agent contract v1 (A1): `gbrain call` is a JSON surface, so a failure is
+ // the same envelope an MCP caller gets, on stdout, with the registry's exit.
+ const op = operations.find(o => o.name === tool);
+ const envelope = toAgentError(error, {
+ transport: 'cli', op: tool, mutating: op?.mutating === true, idempotent: op?.idempotent === true,
+ outcome: op?.mutating ? 'unknown' : 'failed', render: cliRenderContext(),
+ });
+ await out(JSON.stringify(envelope, null, 2) + '\n');
+ console.error(`Error [${envelope.code}]: ${envelope.message}`);
+ setCliExitVerdict(exitCodeForCode(envelope.code));
}
}
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index c565f6cfec..bf7e4e3f6b 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -682,10 +682,17 @@ function chainStdoutWrite(data: string | Uint8Array, encoding?: BufferEncoding):
* (always true: the chain owns backpressure, and flushThenExit awaits it).
*/
export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' } = {}): void {
- void opts;
if (stdoutInterposed) return;
- if (process.stdout.isTTY) return;
+ // Agent contract v1 (D2 guard mode): under `--json` the guard installs even
+ // on a TTY, because the contract is "fd 1 carries exactly the document".
+ if (process.stdout.isTTY && !opts.json) return;
stdoutInterposed = true;
+ jsonGuardMode = opts.json ?? null;
+ const toStderr = (data: string | Uint8Array, encoding?: BufferEncoding): Promise<void> => {
+ try { process.stderr.write(typeof data === 'string' ? Buffer.from(data, encoding ?? 'utf8') : data); } catch { /* best effort */ }
+ return Promise.resolve();
+ };
+ const sink = jsonGuardMode ? toStderr : chainStdoutWrite;
const interposed = function (
chunk: string | Uint8Array,
encodingOrCb?: BufferEncoding | ((err?: Error | null) => void),
@@ -699,7 +706,7 @@ export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' }
encoding = encodingOrCb;
if (typeof maybeCb === 'function') cb = maybeCb;
}
- const settled = chainStdoutWrite(chunk, encoding);
+ const settled = sink(chunk, encoding);
if (cb) void settled.then(() => cb(null));
return true;
};
@@ -714,8 +721,11 @@ export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' }
// resolveStdoutDrainDeadlineMs, same policy as the async drain), then call
// the real exit. flushThenExit is unaffected — it drains via the pump
// before it ever reaches exit, so the patched drain is a no-op there.
+ // Guard mode: a non-zero exit that wrote no final document gets the
+ // fallback document (A0 golden json-fallback.json) so fd 1 always parses.
const realExit = process.exit.bind(process);
const patchedExit = ((code?: number | string | null): never => {
+ writeJsonFallbackIfMissing(typeof code === 'number' ? code : Number(code ?? process.exitCode ?? 0) || 0);
if (stdoutTailPending > 0) drainStdoutQueueSync();
return realExit(code as number);
}) as typeof process.exit;
@@ -726,15 +736,60 @@ export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' }
// that process.exit discards — the `orphans --json` truncation). Formatting
// parity comes from util.formatWithOptions (what Node's Console uses);
// colors stay off — this path is non-TTY by construction. console.error /
- // console.warn are stderr-bound and stay native.
+ // console.warn are stderr-bound and stay native. Guard mode sends them to
+ // stderr: only writeStdoutFinal / writeNdjsonLine reach fd 1.
const consoleToChain = (...args: unknown[]): void => {
- void chainStdoutWrite(formatWithOptions({ colors: false }, ...args) + '\n');
+ void sink(formatWithOptions({ colors: false }, ...args) + '\n');
};
console.log = consoleToChain;
console.info = consoleToChain;
console.debug = consoleToChain;
}
+let jsonGuardMode: 'document' | 'ndjson' | null = null;
+let jsonDocumentWritten = false;
+let lastRenderedErrorCode: string | undefined;
+
+/** renderCliError's callers record the code they rendered so the fallback document can carry it. */
+export function noteRenderedErrorCode(code: string): void {
+ lastRenderedErrorCode = code;
+}
+
+/** Test seam. */
+export function _resetJsonGuardForTests(): void {
+ jsonGuardMode = null;
+ jsonDocumentWritten = false;
+ lastRenderedErrorCode = undefined;
+}
+
+function writeJsonFallbackIfMissing(exitCode: number): void {
+ if (!jsonGuardMode || jsonDocumentWritten) return;
+ if (exitCode === 0) {
+ // Exit 0 with no document is a bug in the command (D5 fails it); log it, never invent a result.
+ recordJsonDocumentMissing();
+ return;
+ }
+ jsonDocumentWritten = true;
+ const doc = {
+ ...(jsonGuardMode === 'ndjson' ? { status: 'error' } : {}),
+ error: 'command_failed',
+ code: lastRenderedErrorCode ?? 'command_failed',
+ message: `The command exited with status ${exitCode} without writing its JSON result.`,
+ suggestion: 'Re-run without --json to read the error on stderr, or run `gbrain doctor --json`.',
+ exit_code: exitCode,
+ contract_version: 1,
+ };
+ const text = `${JSON.stringify(doc, null, jsonGuardMode === 'ndjson' ? undefined : 2)}\n`;
+ void chainStdoutWrite(text).catch(() => { /* fd 1 gone */ });
+}
+
+let jsonMissingHook: (() => void) | null = null;
+/** E11 seam, set by the CLI so this module stays free of config imports. */
+export function setJsonDocumentMissingHook(hook: () => void): void { jsonMissingHook = hook; }
+function recordJsonDocumentMissing(): void {
+ try { jsonMissingHook?.(); } catch { /* fail-open */ }
+}
+
/**
* Deliver a one-shot command's stdout payload FULLY before the exit seam runs.
*
@@ -754,6 +809,7 @@ export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' }
* wrapper has been initialized (see the #4383 block comment above).
*/
export async function writeStdoutFinal(output: string): Promise<void> {
+ jsonDocumentWritten = true;
await chainStdoutWrite(output);
}
@@ -771,6 +827,8 @@ export function jsonRequested(argv: readonly string[]): boolean {
/** One NDJSON line on fd 1 (the only stdout path for `json: 'ndjson'` commands under the guard). */
export async function writeNdjsonLine(line: unknown): Promise<void> {
+ const status = (line as { status?: unknown } | null)?.status;
+ if (status === 'error' || status === 'done' || status === 'ok') jsonDocumentWritten = true;
await chainStdoutWrite(`${JSON.stringify(line)}\n`);
}
@@ -780,7 +838,10 @@ export async function writeNdjsonLine(line: unknown): Promise<void> {
* otherwise stdio is inherited. The one sanctioned `stdio: 'inherit'` site.
*/
export function spawnCliChild(cmd: string, args: readonly string[], opts: SpawnOptions = {}): ChildProcess {
- return spawn(cmd, [...args], { stdio: 'inherit', ...opts });
+ if (!jsonGuardMode) return spawn(cmd, [...args], { stdio: 'inherit', ...opts });
+ const child = spawn(cmd, [...args], { ...opts, stdio: ['inherit', 'pipe', 'inherit'] });
+ child.stdout?.on('data', (chunk: Buffer) => { try { process.stderr.write(chunk); } catch { /* best effort */ } });
+ return child;
}
export interface FinishCliTeardownOpts {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 31560138cc..20f4c22d7b 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -3,7 +3,7 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import type { BrainEngine } from '../core/engine.ts';
-import { operations } from '../core/operations.ts';
+import { operations, opError, OperationError } from '../core/operations.ts';
import { VERSION } from '../version.ts';
import { buildToolDefs } from './tool-defs.ts';
import { dispatchToolCall, buildOperationContext } from './dispatch.ts';
@@ -484,10 +484,10 @@ export async function handleToolCall(
opts?: { sourceId?: string; localFederatedSourceIds?: string[]; writeWaitMs?: number },
): Promise<unknown> {
const op = operations.find(o => o.name === tool);
- if (!op) throw new Error(`Unknown tool: ${tool}`);
+ if (!op) throw opError('unknown_tool', `Unknown tool: ${tool}`, 'Run `gbrain --tools-json` to list the tool names.');
const validationError = validateParams(op, params);
- if (validationError) throw new Error(validationError);
+ if (validationError) throw new OperationError('invalid_params', validationError, `Read the ${tool} schema in \`gbrain --tools-json\` (required params and types).`);
const ctx = buildOperationContext(engine, params, {
remote: false,
diff --git a/test/cli-json-guard.serial.test.ts b/test/cli-json-guard.serial.test.ts
new file mode 100644
index 0000000000..be70b9c31e
--- /dev/null
+++ b/test/cli-json-guard.serial.test.ts
@@ -0,0 +1,101 @@
+/**
+ * Agent contract v1 `--json` guard (A0/D2): under the guard, fd 1 carries
+ * exactly one JSON document. Interposed stdout writes and console.log go to
+ * stderr; only writeStdoutFinal (or writeNdjsonLine) reaches fd 1; a non-zero
+ * exit that wrote no document gets the fallback document; spawnCliChild
+ * pipes a child's stdout to stderr. Child processes, because the guard
+ * patches process-global stdout/exit.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const HELPER = join(import.meta.dir, '..', 'src', 'core', 'cli-force-exit.ts');
+
+async function run(body: string): Promise<{ out: string; err: string; code: number }> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-json-guard-'));
+ const script = join(dir, 'run.ts');
+ writeFileSync(script, `import * as g from ${JSON.stringify(HELPER)};\n${body}\n`);
+ try {
+ const proc = Bun.spawn([process.execPath, script], { stdout: 'pipe', stderr: 'pipe' });
+ const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { out, err, code };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+describe('--json guard (document mode)', () => {
+ test('console.log and stdout.write go to stderr; the final document alone reaches fd 1', async () => {
+ const r = await run(`g.installStdoutPipeDelivery({ json: 'document' });
+console.log('human progress line');
+process.stdout.write('more noise\\n');
+await g.writeStdoutFinal(JSON.stringify({ ok: true }) + '\\n');
+g.flushThenExit(0);`);
+ expect(r.code).toBe(0);
+ expect(JSON.parse(r.out)).toEqual({ ok: true });
+ expect(r.err).toContain('human progress line');
+ expect(r.err).toContain('more noise');
+ }, 20_000);
+
+ test('a direct non-zero exit with no document writes the fallback document', async () => {
+ const r = await run(`g.installStdoutPipeDelivery({ json: 'document' });
+console.log('Error: something human');
+g.noteRenderedErrorCode('invalid_params');
+process.exit(2);`);
+ expect(r.code).toBe(2);
+ const doc = JSON.parse(r.out);
+ expect(doc).toEqual({
+ error: 'command_failed', code: 'invalid_params',
+ message: 'The command exited with status 2 without writing its JSON result.',
+ suggestion: 'Re-run without --json to read the error on stderr, or run `gbrain doctor --json`.',
+ exit_code: 2, contract_version: 1,
+ });
+ }, 20_000);
+
+ test('a document already written is never followed by a fallback', async () => {
+ const r = await run(`g.installStdoutPipeDelivery({ json: 'document' });
+await g.writeStdoutFinal(JSON.stringify({ error: 'x', code: 'x' }) + '\\n');
+process.exit(1);`);
+ expect(r.code).toBe(1);
+ expect(JSON.parse(r.out)).toEqual({ error: 'x', code: 'x' });
+ }, 20_000);
+
+ test('exit 0 without a document writes nothing to fd 1 (a bug D5 fails; E11 hook fires)', async () => {
+ const r = await run(`g.installStdoutPipeDelivery({ json: 'document' });
+g.setJsonDocumentMissingHook(() => process.stderr.write('HOOK_FIRED\\n'));
+console.log('forgot the document');
+process.exit(0);`);
+ expect(r.code).toBe(0);
+ expect(r.out).toBe('');
+ expect(r.err).toContain('HOOK_FIRED');
+ }, 20_000);
+
+ test('ndjson: lines reach fd 1; a failing exit appends a status:error line', async () => {
+ const r = await run(`g.installStdoutPipeDelivery({ json: 'ndjson' });
+await g.writeNdjsonLine({ n: 1 });
+console.log('noise');
+process.exit(1);`);
+ const lines = r.out.trim().split('\n').map(l => JSON.parse(l));
+ expect(lines[0]).toEqual({ n: 1 });
+ expect(lines[1]).toMatchObject({ status: 'error', error: 'command_failed', exit_code: 1 });
+ }, 20_000);
+
+ test('spawnCliChild pipes the child stdout to stderr under the guard', async () => {
+ const r = await run(`g.installStdoutPipeDelivery({ json: 'document' });
+const child = g.spawnCliChild(process.execPath, ['-e', 'console.log("child says hi")']);
+await new Promise(res => child.on('close', res));
+await g.writeStdoutFinal(JSON.stringify({ ok: 1 }) + '\\n');
+g.flushThenExit(0);`);
+ expect(JSON.parse(r.out)).toEqual({ ok: 1 });
+ expect(r.err).toContain('child says hi');
+ }, 20_000);
+
+ test('without the guard, installStdoutPipeDelivery keeps stdout as-is', async () => {
+ const r = await run(`g.installStdoutPipeDelivery();
+console.log('plain');
+g.flushThenExit(0);`);
+ expect(r.out).toBe('plain\n');
+ }, 20_000);
+});