Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(cli): D1 renderCliError at every top-level catch, usage error and the fatal seam

garrytan3423fbbe826f
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index d20958734c..e5f2ab64af 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -10,5 +10,6 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` for doctor's `agent_contract` check.
- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`empty_retrieval`, `unknown_param`, `listing_truncated`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.
- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).
+- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.serial.test.ts`.
- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.serial.test.ts`.
- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 71169002ba..97b009d169 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1018,6 +1018,14 @@ More: [docs/guides/write-refusals.md#managed_pull_skipped](../../docs/guides/wri
|---|---|---|---|---|---|---|
| A configured model is not allowed under models strict mode. | 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 |
+### no_brain
+
+<a id="no_brain"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| No brain is configured on this machine. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run `gbrain init --pglite --no-embedding` to create a local keyless brain (or `gbrain init --help` for hosted and Postgres options). | agent | `repeat the read that failed` | 1 | no |
+
### no_pricing
<a id="no_pricing"></a>
@@ -1162,6 +1170,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| This caller is not authorized for the operation. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+### pglite_busy
+
+<a id="pglite_busy"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Another gbrain process holds this PGLite brain's single-writer lock. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait for the current command or server to close, then retry. Do not remove a live lock. | agent | `repeat the read that failed` | 1 | yes |
+
+Reasons: `timeout`, `live_serve`.
+
### plan_output_failed
<a id="plan_output_failed"></a>
@@ -1398,6 +1416,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| The runtime requirements exceed the owner-approved publication policy. | 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 |
+### requires_local_engine
+
+<a id="requires_local_engine"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| This command needs the brain's local database, and this install is a thin client of a remote brain. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+
### response_too_large
<a id="response_too_large"></a>
@@ -1684,6 +1710,14 @@ More: [docs/guides/write-refusals.md#sync_in_progress](../../docs/guides/write-r
|---|---|---|---|---|---|---|
| An unclassified failure (legacy StructuredError fallback code). | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+### unknown_command
+
+<a id="unknown_command"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The CLI has no command by that name. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run `gbrain --help` for the command list. | agent | `repeat the read that failed` | 2 | no |
+
### unknown_flag
<a id="unknown_flag"></a>
diff --git a/scripts/agent-contract-baselines/legacy-advice-key.tsv b/scripts/agent-contract-baselines/legacy-advice-key.tsv
index 36a85b8b50..34ea5c21ab 100644
--- a/scripts/agent-contract-baselines/legacy-advice-key.tsv
+++ b/scripts/agent-contract-baselines/legacy-advice-key.tsv
@@ -1,5 +1,5 @@
# shrink-only baseline for scripts/check-agent-contract.ts rule legacy-advice-key: path<TAB>count
-src/cli.ts 1
+src/cli/cli-error.ts 1
src/commands/autopilot/jobs.ts 2
src/commands/claw-test.ts 11
src/commands/code-callees.ts 1
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bcb69c4cd9..00bb1d8df1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 3211 ratchet +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult
+src/cli.ts 3131 ratchet +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult
src/commands/autopilot.ts 1639 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts)
src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2217 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index e7062dc8ae..25f096eb97 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -43,6 +43,7 @@
"test/brainstorm/checkpoint.serial.test.ts": 0,
"test/check-update-refresh.serial.test.ts": 0,
"test/checkpoint-harvest.serial.test.ts": 9,
+ "test/cli-error-render.serial.test.ts": 3,
"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,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 4824102762..6ff645778c 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -318,6 +318,7 @@
"serial:test/brainstorm/checkpoint.serial.test.ts": 395,
"serial:test/check-update-refresh.serial.test.ts": 356,
"serial:test/checkpoint-harvest.serial.test.ts": 4977,
+ "serial:test/cli-error-render.serial.test.ts": 3000,
"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,
diff --git a/src/cli.ts b/src/cli.ts
index 5061e94c47..cfa4fb4446 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -26,8 +26,6 @@ import {
shouldEmitDbAccessMarker,
} from './core/pg-access-classify.ts';
import { resolveBrainId as resolveBrainIdForDbMarker } from './core/brain-resolver.ts';
-import { redactUrlsInText as redactUrlsForFatal } from './core/url-redact.ts';
-import { redactConnectionInfo as redactConnInfoForFatal } from './core/audit/redact-connection-info.ts';
import type { GBrainConfig } from './core/config.ts';
import type { AIGatewayConfig } from './core/ai/types.ts';
import type { BrainEngine } from './core/engine.ts';
@@ -39,6 +37,8 @@ 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 { agentJsonGuardMode } from './cli/json-guard.ts';
+import { cliCommandOf, exitCliError, unknownFlagError, usageError, writeCliError, writeFatalCliError } from './cli/cli-error.ts';
+import { opError } from './core/ops/contract.ts';
import { serializeMarkdown } from './core/markdown.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';
import { runCliPreflight } from './core/cli-preflight.ts';
@@ -456,18 +456,14 @@ async function main() {
const migrationError = migrationCliArgumentError(command, subArgs, rawArgs);
const unknown = migrationError?.flag ?? validateCommandFlags(command, subArgs);
if (unknown) {
- // Message contract shared with init.ts's in-handler check (which this
- // pre-dispatch validator now reaches first): lowercase 'unknown flag'
- // on stderr; --json callers get the structured error on stdout with
- // reason 'invalid_flag' (pinned by test/init-migrate-only.test.ts).
+ // Message contract shared with init.ts's in-handler check: lowercase
+ // 'unknown flag' on stderr; --json gets one envelope whose legacy keys
+ // (status, reason 'invalid_flag', message) are pinned by
+ // test/init-migrate-only.test.ts. D1/D3: exit 2 + did-you-mean.
const message = migrationError?.message ?? `unknown flag ${unknown} for 'gbrain ${command}'`;
- // Both --json spellings get the structured envelope (--json=false opts out).
- if (subArgs.some(a => a === '--json' || (a.startsWith('--json=') && a !== '--json=false'))) {
- process.stdout.write(JSON.stringify({ status: 'error', reason: 'invalid_flag', message }) + '\n');
- }
- console.error(`gbrain ${command}: ${message}`);
- console.error(`Run: gbrain ${command} --help`);
- process.exit(1);
+ const flagOp = cliOps.get(command) ?? cliAliases.get(command);
+ const known = CLI_FLAG_REGISTRY[command] ?? Object.keys(flagOp?.params ?? {}).map(k => `--${k.replace(/_/g, '-')}`);
+ exitCliError(await unknownFlagError(command, unknown, message, known), command, { legacy: { status: 'error', reason: 'invalid_flag', message } });
}
}
@@ -500,11 +496,7 @@ async function main() {
async function runSharedOperation(command: string, subArgs: string[], cliOpts: CliOptions): Promise<void> {
// Shared operations (fall through to aliases, e.g. link-add -> add_link)
const op = cliOps.get(command) ?? cliAliases.get(command);
- if (!op) {
- console.error(`Unknown command: ${command}`);
- console.error('Run gbrain --help for available commands.');
- process.exit(1);
- }
+ if (!op) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);
// v0.31.1 (Issue #734, CDX-1): parse CLI args BEFORE engine connect so
// the routing seam below can decide local-vs-remote without paying a
@@ -532,8 +524,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
params.image_mime = mime;
void path;
} catch (err) {
- console.error(err instanceof Error ? err.message : String(err));
- process.exit(1);
+ exitCliError(usageError(err instanceof Error ? err.message : String(err), 'Pass --image a readable PNG/JPEG/WebP/GIF path.'), command);
}
}
@@ -548,8 +539,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
const cliName = op.cliHints?.name || op.name;
const positional = op.cliHints?.positional || [];
const usage = positional.map(p => `<${p}>`).join(' ');
- console.error(`Usage: gbrain ${cliName} ${usage}`);
- process.exit(1);
+ exitCliError(usageError(`Missing required parameter '${key}' for 'gbrain ${cliName}'.`, `Usage: gbrain ${cliName} ${usage}`.trimEnd() + ` (see \`gbrain ${cliName} --help\`).`), command);
}
}
@@ -568,13 +558,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// as applyThinClientSourceScope's --source refusal). Ambient tiers
// (GBRAIN_BRAIN_ID / .gbrain-mount) are ignored here, matching the
// source axis's ambient-with-nowhere-to-send behavior.
- if (cliOpts.brain) {
- console.error(
- '--brain is not supported on a thin-client install: the remote server is a single brain. ' +
- 'Remove the flag, or run from a machine with local mounts (gbrain mounts list).',
- );
- process.exit(1);
- }
+ if (cliOpts.brain) exitCliError(usageError(THIN_CLIENT_BRAIN_FLAG_MESSAGE, 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), command);
// #2098: the local path resolves --source / GBRAIN_SOURCE / .gbrain-source
// inside makeContext (ctx.sourceId), which this route never reaches — so
// scope must be mapped onto the op's source_id wire param before the call.
@@ -582,8 +566,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
try {
ambientScope = applyThinClientSourceScope(op, params);
} catch (e: unknown) {
- console.error(e instanceof Error ? e.message : String(e));
- process.exit(1);
+ exitCliError(e, command);
}
await runThinClientRouted(op, params, cfgPre!, cliOpts, ambientScope);
return;
@@ -594,8 +577,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
try {
assertSingleSourceScopeFlag(op, params);
} catch (e: unknown) {
- console.error(e instanceof Error ? e.message : String(e));
- process.exit(1);
+ exitCliError(e, command);
}
// The live PGLite owner exposes canonical operations over a dedicated
@@ -716,9 +698,9 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// bounds a hung one.
// #5232: the reporter owns the write verdict; never overwrite it.
const { reportPersistenceCliError } = await import('./commands/persistence-delegate.ts');
- if (!await reportPersistenceCliError(e, params.json === true || !!(e as OperationError)?.writeRequest)) {
- console.error(e instanceof Error ? e.message : String(e));
- setCliExitVerdict(1);
+ const receipt = !(e instanceof OperationError) || !!e.writeRequest;
+ if (!receipt || !await reportPersistenceCliError(e, params.json === true || !!(e as OperationError)?.writeRequest)) {
+ setCliExitVerdict(writeCliError(e, command));
}
} finally {
// 1s per-sink drain budget: read paths with no pending work pay the ~0ms
@@ -803,6 +785,13 @@ async function runThinClientRouted(
process.off('SIGINT', onSigint);
process.exit(sigintController.signal.aborted ? 130 : currentExitCode());
}
+ // D1: --json gets the one v1 envelope; a server tool error renders its
+ // own code/fix. Transport failures keep their specific human text.
+ const scopeDenied = isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason);
+ if (params.json === true || (e.reason === 'tool_error' && !scopeDenied)) {
+ process.off('SIGINT', onSigint);
+ exitCliError(e, op.cliHints?.name ?? op.name);
+ }
const url = cfg.remote_mcp!.mcp_url;
switch (e.reason) {
case 'config':
@@ -834,14 +823,9 @@ async function runThinClientRouted(
}
break;
case 'tool_error':
- if (isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason)) {
- console.error('Missing OAuth scope on this client.');
- console.error('On the host, re-register the client with broader scopes:');
- console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');
- } else {
- console.error(e.message);
- console.error('Run `gbrain remote doctor` if this persists.');
- }
+ console.error('Missing OAuth scope on this client.');
+ console.error('On the host, re-register the client with broader scopes:');
+ console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');
break;
case 'parse':
console.error('Server response was malformed. Run `gbrain remote doctor`.');
@@ -858,11 +842,10 @@ async function runThinClientRouted(
process.exit(1);
}
// Defense in depth: callRemoteTool's contract is that everything is
- // RemoteMcpError. If a plain Error escapes, render it generically and
- // exit 1 — but this should never happen post-CDX-4.
- console.error(e instanceof Error ? e.message : String(e));
+ // RemoteMcpError. If a plain Error escapes, render it generically — but
+ // this should never happen post-CDX-4.
process.off('SIGINT', onSigint);
- process.exit(1);
+ exitCliError(e, op.cliHints?.name ?? op.name);
} finally {
process.off('SIGINT', onSigint);
}
@@ -1152,8 +1135,7 @@ export async function applyStdinParam(
if (content.trim() === '') return;
const MAX_STDIN = 5_000_000; // 5MB
if (Buffer.byteLength(content, 'utf-8') > MAX_STDIN) {
- console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
- process.exit(1);
+ exitCliError(opError('payload_too_large', `stdin content exceeds ${MAX_STDIN} bytes.`, 'Split the content into smaller inputs.'), op.cliHints?.name ?? op.name);
}
params[op.cliHints.stdin] = content;
}
@@ -1883,18 +1865,19 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
*/
function refuseThinClient(command: string, mcpUrl: string): never {
const hint = THIN_CLIENT_REFUSE_HINTS[command];
- if (hint) {
- console.error(`\`gbrain ${command}\` is not routable. ${hint}`);
- console.error(`(thin-client of ${mcpUrl})`);
- } else {
- console.error(
- `\`gbrain ${command}\` requires a local engine. This install is a thin client of ${mcpUrl}.\n` +
- `Run \`${command}\` on the remote host, or use the corresponding MCP tool from your agent.`,
- );
- }
- process.exit(1);
+ const message = hint
+ ? `\`gbrain ${command}\` is not routable from this thin client of ${mcpUrl}; run it on the brain host.`
+ : `\`gbrain ${command}\` requires a local engine. This install is a thin client of ${mcpUrl}.`;
+ exitCliError(opError('requires_local_engine', message,
+ hint ?? `Run \`${command}\` on the remote host, or use the corresponding MCP tool from your agent.`, {
+ ...(hint ? { why: hint } : {}),
+ fix: { argv: ['gbrain', command], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'The brain database lives on the brain host; this machine only forwards MCP calls.' },
+ }), command);
}
+const THIN_CLIENT_BRAIN_FLAG_MESSAGE = '--brain is not supported on a thin-client install: the remote server is a single brain.';
+
/** Dispatcher-owned pieces the command modules under src/cli/commands/ receive (see CliDispatchContext). */
const CLI_DISPATCH_CONTEXT: CliDispatchContext = {
connectEngine,
@@ -2411,8 +2394,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis
}
} catch (e) {
// A bad --hard-deadline value throws here (same posture as --timeout).
- console.error(e instanceof Error ? e.message : String(e));
- process.exit(1);
+ exitCliError(usageError(e instanceof Error ? e.message : String(e), 'Pass --hard-deadline a duration such as 30m or 2h.'), command);
}
}
@@ -2519,11 +2501,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis
if (command === 'recall' && isThinClient(loadConfig())) {
const { hasRecallBudgetPolicy, runRecall } = await import('./commands/recall.ts');
if (hasRecallBudgetPolicy(args)) {
- if (getCliOptions().brain) {
- console.error('--brain is not supported on a thin-client install: the remote server is a single brain. ' +
- 'Remove the flag, or run from a machine with local mounts (gbrain mounts list).');
- process.exit(1);
- }
+ if (getCliOptions().brain) exitCliError(usageError(THIN_CLIENT_BRAIN_FLAG_MESSAGE, 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), command);
await runRecall(null as never, args);
return null;
}
@@ -2737,8 +2715,10 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin
}
if (d?.reason === 'env_shadowed') console.error(d.remediation);
} catch { /* marker is best-effort — the message below always prints */ }
- console.error('No brain configured. Run: gbrain init');
- process.exit(1);
+ exitCliError(opError('no_brain', 'No brain configured. Run: gbrain init', 'Run `gbrain init --pglite --no-embedding` for a local keyless brain, or `gbrain init --help` for hosted and Postgres options.', {
+ fix: { argv: ['gbrain', 'init', '--pglite', '--no-embedding'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Creates a local PGLite brain with no API keys; nothing leaves this machine.' },
+ }), cliCommandOf());
}
// Configure the AI gateway BEFORE engine connect — initSchema needs embedding dims.
@@ -3135,42 +3115,17 @@ if (import.meta.main) {
if (shouldForceExitAfterMain()) flushThenExit(currentExitCode());
},
(e) => {
- 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.' }));
- flushThenExit(1);
- return;
- }
- // db-availability loop: this choke point covers CONNECT-TIME failures
- // for every engine-needing command. The happy path redacts (the old
- // bare `e.message` was itself an unredacted-DSN surface); DB-access
- // failures additionally emit the GBRAIN_DB_ACCESS marker the bundled
- // skills/db-repair skill literal-matches. Everything is wrapped — a
- // classifier bug must never make error reporting worse. Honest caveat:
- // the two last-resort fallbacks below print the RAW message, reachable
- // only when a redactor itself threw — losing the error entirely would
- // be worse than the residual leak risk on that path.
+ // D1: the fatal seam renders through renderCliError (one --json
+ // envelope on stdout; human `Error [code]` / `Fix:` on stderr), keeping
+ // the pglite_busy keys and the GBRAIN_DB_ACCESS marker. A renderer
+ // fault must never lose the error, so the raw message is the fallback.
+ let exitCode = 1;
try {
- const rawMsg = (e && (e as Error).message) || String(e);
- let printed = false;
- try {
- const safeMsg = redactConnInfoForFatal(redactUrlsForFatal(rawMsg));
- const d = classifyDbAccessError(e, { url: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
- if (d.reason !== 'unknown' && shouldEmitDbAccessMarker()) {
- console.error(formatDbMarker(d));
- }
- if (d.reason !== 'unknown') {
- console.error(`${safeMsg}\n${d.remediation} Run: gbrain db-repair`);
- } else {
- console.error(safeMsg);
- }
- printed = true;
- } catch { /* classifier/redactor failure — fall through */ }
- if (!printed) console.error(rawMsg);
+ exitCode = writeFatalCliError(e, { dbUrl: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
} catch {
console.error(e?.message || e);
}
- flushThenExit(1);
+ flushThenExit(exitCode);
},
);
}
diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts
new file mode 100644
index 0000000000..b9d2d39a4c
--- /dev/null
+++ b/src/cli/cli-error.ts
@@ -0,0 +1,130 @@
+/**
+ * Agent contract v1 (D1): the CLI's one error writer. Every top-level catch,
+ * usage error and the fatal seam render through `renderCliError`: human
+ * output is `Error [code]: …` / `Fix:` / `Why:` / `Docs:` on stderr; under
+ * `--json` stdout carries exactly one envelope (a legacy JSON shape keeps its
+ * keys and gains the v1 siblings). Writes go through the `cli-force-exit.ts`
+ * interposer: `writeStdoutFinal` delivers synchronously when the chain is
+ * idle and the patched `process.exit` drains anything queued, so callers may
+ * exit right after.
+ */
+import { renderCliError, type AgentEnvelope } from '../core/agent-output.ts';
+import { 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 {
+ classifyPgAccessError,
+ formatDbAccessMarker,
+ shouldEmitDbAccessMarker,
+} from '../core/pg-access-classify.ts';
+import { redactUrlsInText } from '../core/url-redact.ts';
+import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';
+import { suggestNearest } from '../core/levenshtein.ts';
+import { findCliCommand } from './command-table.ts';
+
+export interface CliErrorWriteOpts {
+ /** Raw argv (defaults to process.argv.slice(2)); decides `--json`. */
+ argv?: readonly string[];
+ /**
+ * A pre-v1 JSON shape this site printed: its keys lead and keep their
+ * values, the envelope adds the rest, and the document stays one line
+ * (line-reading consumers of the old shape keep working).
+ */
+ legacy?: Record<string, unknown>;
+}
+
+/** The command word of an argv (first token that is not a flag), for E11 records. */
+export function cliCommandOf(argv: readonly string[] = process.argv.slice(2)): string {
+ return argv.find(a => !a.startsWith('-')) ?? '';
+}
+
+/** Render and write `e`; returns the exit code (the caller exits or sets the verdict). */
+export function writeCliError(e: unknown, command: string, opts: CliErrorWriteOpts = {}): number {
+ const json = jsonRequested(opts.argv ?? process.argv.slice(2));
+ const r = renderCliError(e, { json, command, tty: process.stderr.isTTY === true });
+ let stderr = r.stderr;
+ if (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;
+ 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}`,
+ ...(env.why ? [`Why: ${env.why}`] : [])].join('\n') + '\n';
+ }
+ try { process.stderr.write(stderr ?? ''); } catch { /* stderr gone */ }
+ return r.exitCode;
+}
+
+function withoutUndefined(o: object): Record<string, unknown> {
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
+}
+
+/** Render, write and exit with the error's contract exit code. */
+export function exitCliError(e: unknown, command: string, opts: CliErrorWriteOpts = {}): never {
+ process.exit(writeCliError(e, command, opts));
+}
+
+/**
+ * A usage / invalid-input error (exit 2 via the registry): `invalid_params`
+ * by default, `unknown_flag` / `unknown_command` for those cases.
+ */
+export function usageError(
+ message: string,
+ suggestion: string,
+ opts: OpErrorOpts & { code?: Extract<RegistryCode, 'invalid_params' | 'unknown_flag' | 'unknown_command'> } = {},
+): OperationError {
+ const { code = 'invalid_params', ...rest } = opts;
+ return opError(code, message, suggestion, rest);
+}
+
+/**
+ * D3: `unknown_flag` with a did-you-mean drawn from the command's curated
+ * help flags when it has a help module, else from `fallback` (the generated
+ * acceptance registry / op params).
+ */
+export async function unknownFlagError(command: string, flag: string, message: string, fallback: readonly string[] = []): Promise<OperationError> {
+ const help = findCliCommand(command)?.help;
+ const candidates = help ? (await help()).help.flags.map(f => f.name) : fallback;
+ const bare = flag.split('=')[0];
+ const nearest = suggestNearest(bare, candidates.filter(c => c !== bare));
+ const suggestion = nearest
+ ? `Did you mean ${nearest}? Run \`gbrain ${command} --help\` for the accepted flags.`
+ : `Run \`gbrain ${command} --help\` for the accepted flags.`;
+ return usageError(nearest ? `${message} (did you mean ${nearest}?)` : message, suggestion, {
+ code: 'unknown_flag',
+ fix: { argv: ['gbrain', command, '--help'], consent: [], actor: 'agent', why: 'The help lists every flag this command accepts.', requires_exclusive: false },
+ });
+}
+
+/**
+ * The fatal seam (main() rejected). Same renderer, plus the two pre-v1
+ * behaviours agents and skills depend on: the `pglite_busy` JSON keys
+ * (`next_action`) and the `GBRAIN_DB_ACCESS` marker line skills/db-repair
+ * literal-matches, with the classifier's remediation.
+ */
+export function writeFatalCliError(e: unknown, opts: { argv?: readonly string[]; dbUrl?: string | null; brainId?: string } = {}): number {
+ const argv = opts.argv ?? process.argv.slice(2);
+ const command = cliCommandOf(argv);
+ const busy = e as { code?: unknown; reason?: unknown; message?: unknown } | null;
+ if (busy?.code === 'pglite_busy') {
+ const next = 'Wait for the current command or server to close, then retry. Do not remove a live lock.';
+ const err = opError('pglite_busy', String(busy.message ?? 'The brain is busy.'), next, {
+ ...(typeof busy.reason === 'string' ? { reason: busy.reason } : {}),
+ });
+ return writeCliError(err, command, { argv, legacy: { error: 'pglite_busy', retryable: true, reason: busy.reason, next_action: next } });
+ }
+ if (!jsonRequested(argv)) {
+ try {
+ const d = classifyPgAccessError(e, { url: opts.dbUrl ?? null, brainId: opts.brainId });
+ if (d.reason !== 'unknown') {
+ if (shouldEmitDbAccessMarker()) process.stderr.write(`${formatDbAccessMarker(d)}\n`);
+ const raw = (e instanceof Error && e.message) || String(e);
+ const safe = redactConnectionInfo(redactUrlsInText(raw));
+ process.stderr.write(`Error [database_error]: ${safe}\n${d.remediation} Run: gbrain db-repair\n`);
+ return 1;
+ }
+ } catch { /* classifier failure: the generic renderer below still reports it */ }
+ }
+ return writeCliError(e, command, { argv });
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9d25f43de9..9d2be94d65 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -166,6 +166,7 @@ export const CODES = {
no_worker_surface: { class: 'caller', summary: "No worker surface." },
not_a_git_repo: { class: 'caller', summary: "The source path must contain committed Git content." },
not_connected: { class: 'caller', summary: "Google connect credential error: not connected.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ no_brain: { class: 'caller', summary: "No brain is configured on this machine.", suggestion: 'Run `gbrain init --pglite --no-embedding` to create a local keyless brain (or `gbrain init --help` for hosted and Postgres options).' },
not_found: { class: 'caller', summary: "The requested resource does not exist or is not visible to this caller.", legacy_error: 'invalid_params' },
overlapping_path: { class: 'caller', summary: "Sources cannot claim overlapping canonical directories." },
owner_unavailable: { class: 'retryable', summary: "The brain's persistence owner is not reachable right now." },
@@ -176,6 +177,7 @@ export const CODES = {
payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },
pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },
permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },
+ pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },
plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },
plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },
port_in_use: { class: 'retryable', summary: "Google connect credential error: port in use.", docs: 'docs/guides/google-connect.md#troubleshooting' },
@@ -202,6 +204,7 @@ export const CODES = {
request_already_submitted: { class: 'caller', summary: "This optimizer publication request has already been submitted." },
request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },
requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },
+ requires_local_engine: { class: 'host_only', summary: "This command needs the brain's local database, and this install is a thin client of a remote brain." },
response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },
resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },
revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches." },
@@ -237,6 +240,7 @@ export const CODES = {
unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },
unexpected_staging_bytes: { class: 'server', summary: "Recovery staging has unexpected bytes or identity; the root and its recovery capacity remain reserved." },
unknown: { class: 'server', summary: "An unclassified failure (legacy StructuredError fallback code)." },
+ unknown_command: { class: 'caller', summary: "The CLI has no command by that name.", suggestion: 'Run `gbrain --help` for the command list.', exit: 2 },
unknown_flag: { class: 'caller', summary: "The command does not accept one of the flags passed.", exit: 2 },
unknown_method: { class: 'caller', summary: "The JSON-RPC method is not supported." },
unknown_source: { class: 'caller', summary: "The named source is not registered or is archived." },
diff --git a/test/cli-error-render.serial.test.ts b/test/cli-error-render.serial.test.ts
new file mode 100644
index 0000000000..557367c82b
--- /dev/null
+++ b/test/cli-error-render.serial.test.ts
@@ -0,0 +1,75 @@
+/**
+ * Agent contract v1 D1: every top-level catch, usage error and the fatal seam
+ * render through renderCliError. Human: `Error [code]: …` / `Fix: …` on
+ * stderr; `--json`: exactly one envelope on stdout (code + suggestion +
+ * contract_version), exit code from the registry (2 for usage errors).
+ * Real CLI subprocesses against an empty GBRAIN_HOME (no brain is opened).
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-error-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+const cli = (args: string[]) => runCli(args, { home, cwd: home });
+
+describe('D1 CLI error rendering', () => {
+ test('unknown command: human lines on stderr, exit 2', async () => {
+ const r = await cli(['definitely-not-a-command']);
+ expect(r.exitCode).toBe(2);
+ expect(r.stdout).toBe('');
+ expect(r.stderr).toContain('Error [unknown_command]: Unknown command: definitely-not-a-command');
+ expect(r.stderr).toContain('Fix: Run `gbrain --help`');
+ });
+
+ test('unknown command --json: one envelope on stdout', async () => {
+ const r = await cli(['definitely-not-a-command', '--json']);
+ expect(r.exitCode).toBe(2);
+ expect(JSON.parse(r.stdout)).toMatchObject({
+ error: 'unknown_command', code: 'unknown_command', class: 'caller', retryable: false, contract_version: 1,
+ docs_cmd: ['gbrain', 'errors', 'unknown_command'],
+ });
+ });
+
+ test('unknown flag keeps the legacy one-line keys and gains the envelope + did-you-mean', async () => {
+ const r = await cli(['search', 'needle', '--limitt', '3', '--json']);
+ expect(r.exitCode).toBe(2);
+ expect(r.stdout.trim().split('\n')).toHaveLength(1);
+ const doc = JSON.parse(r.stdout);
+ expect(doc).toMatchObject({ status: 'error', reason: 'invalid_flag', error: 'unknown_flag', code: 'unknown_flag', contract_version: 1 });
+ expect(doc.suggestion).toContain('--limit');
+ expect(doc.fix).toMatchObject({ argv: ['gbrain', 'search', '--help'], next: 'run' });
+ expect(r.stderr).toContain("unknown flag --limitt for 'gbrain search'");
+ });
+
+ test('missing required param names the param, exit 2', async () => {
+ const r = await cli(['get', '--json']);
+ expect(r.exitCode).toBe(2);
+ const doc = JSON.parse(r.stdout);
+ expect(doc).toMatchObject({ code: 'invalid_params' });
+ expect(doc.message).toContain("'slug'");
+ expect(doc.suggestion).toContain('Usage: gbrain get <slug>');
+ });
+
+ test('fatal seam: a parser OperationError thrown out of main() renders the envelope', async () => {
+ const r = await cli(['put', 'example-slug', '--content', '--json']);
+ expect(r.exitCode).toBe(2);
+ const doc = JSON.parse(r.stdout);
+ expect(doc).toMatchObject({ error: 'invalid_params', code: 'invalid_params', contract_version: 1 });
+ expect(doc.message).toContain('--content requires a value');
+ });
+
+ test('no brain configured: no_brain with an init fix (human and --json)', async () => {
+ const human = await cli(['stats']);
+ expect(human.exitCode).toBe(1);
+ expect(human.stderr).toContain('Error [no_brain]: No brain configured');
+ expect(human.stderr).toContain('Fix: gbrain init --pglite --no-embedding');
+ const json = await cli(['stats', '--json']);
+ expect(json.exitCode).toBe(1);
+ expect(JSON.parse(json.stdout)).toMatchObject({
+ code: 'no_brain', fix: { argv: ['gbrain', 'init', '--pglite', '--no-embedding'], actor: 'agent', next: 'run' },
+ });
+ });
+});
diff --git a/test/cli-flag-validation.test.ts b/test/cli-flag-validation.test.ts
index f7a8331131..3f24b41ea3 100644
--- a/test/cli-flag-validation.test.ts
+++ b/test/cli-flag-validation.test.ts
@@ -280,7 +280,7 @@ describe('#2185 subprocess smokes — end-to-end error surface', () => {
test('init --migrate-only --dry-run fails loud BEFORE any engine work', () => {
const r = run(['init', '--migrate-only', '--dry-run']);
- expect(r.status).toBe(1);
+ expect(r.status).toBe(2);
expect(r.stderr).toContain("unknown flag --dry-run for 'gbrain init'");
// Pre-engine: no migration output may appear.
expect(r.stderr).not.toContain('migration');
@@ -288,7 +288,7 @@ describe('#2185 subprocess smokes — end-to-end error surface', () => {
test('typo on an op command fails loud with the command named', () => {
const r = run(['search', 'needle', '--jsno']);
- expect(r.status).toBe(1);
+ expect(r.status).toBe(2);
expect(r.stderr).toContain("unknown flag --jsno for 'gbrain search'");
});
@@ -302,7 +302,7 @@ describe('#2185 subprocess smokes — end-to-end error surface', () => {
// --quiet is a parseGlobalFlags global: it never reaches the validator.
// The bogus flag proves validation still ran on what remained.
const r = run(['init', '--migrate-only', '--quiet', '--definitely-bogus-xyz']);
- expect(r.status).toBe(1);
+ expect(r.status).toBe(2);
expect(r.stderr).toContain("unknown flag --definitely-bogus-xyz for 'gbrain init'");
expect(r.stderr).not.toContain('--quiet');
});
@@ -311,7 +311,7 @@ describe('#2185 subprocess smokes — end-to-end error surface', () => {
// Fast path: --help short-circuits AFTER global parse, so a bogus flag
// alongside --source proves ordering: --source accepted, bogus rejected.
const r = run(['search', 'needle', '--source', 'nope-source', '--definitely-bogus-xyz']);
- expect(r.status).toBe(1);
+ expect(r.status).toBe(2);
expect(r.stderr).toContain("unknown flag --definitely-bogus-xyz for 'gbrain search'");
expect(r.stderr).not.toContain('unknown flag --source');
});
@@ -393,9 +393,9 @@ describe('#5700 subprocess smoke — the reported invocation fails loud', () =>
env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },
});
- test('put --content --source <id> exits 1 naming both flags', () => {
+ test('put --content --source <id> exits 2 naming both flags', () => {
const r = run(['put', 'repro-a', '--content', '--source', 'default']);
- expect(r.status).toBe(1);
+ expect(r.status).toBe(2);
expect(r.stderr).toContain("--content requires a value, but '--source' is a flag");
// Pre-write: the page must not have been created with a flag token body.
expect(r.stdout).not.toContain('created_or_updated');
diff --git a/test/cli-recall-flag-ownership.test.ts b/test/cli-recall-flag-ownership.test.ts
index 9f906614d2..27764ccb04 100644
--- a/test/cli-recall-flag-ownership.test.ts
+++ b/test/cli-recall-flag-ownership.test.ts
@@ -39,7 +39,7 @@ describe('recall and degraded serve flag ownership', () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-recall-flags-'));
try {
const result = await runCli(['recall', '--query', 'example', flag, '--json'], { home, cwd: home });
- expect(result.exitCode).toBe(1);
+ expect(result.exitCode).toBe(2);
expect(result.stderr).toContain(`unknown flag ${flag} for 'gbrain recall'`);
expect(JSON.parse(result.stdout)).toMatchObject({ status: 'error', reason: 'invalid_flag' });
expect(result.stderr).not.toContain('database_url is missing');
diff --git a/test/cli-stdin-hang.test.ts b/test/cli-stdin-hang.test.ts
index 1005b4267b..792fa8f581 100644
--- a/test/cli-stdin-hang.test.ts
+++ b/test/cli-stdin-hang.test.ts
@@ -9,7 +9,7 @@
*
* The load-bearing regression test spawns the REAL CLI with a held-open,
* never-written pipe: on pre-fix code it hangs until our observation window
- * kills it; on fixed code it exits 1 with the usage error well inside the
+ * kills it; on fixed code it exits 2 with the usage error well inside the
* window. The stdin read + required-param check both run BEFORE engine
* connect, so no brain/DB is touched.
*/
@@ -75,11 +75,11 @@ describe('#3513 — stdin-capable op with a non-TTY, never-written stdin', () =>
test('exits fast with the usage error instead of blocking forever', async () => {
// `put` declares stdin:'content' (required). No inline content, no piped
// input → the bounded read times out at 500ms, content stays unset, and
- // the required-param check prints usage and exits 1. Pre-fix: readFileSync(0)
+ // the required-param check prints usage and exits 2 (usage). Pre-fix: readFileSync(0)
// blocks until the 20s window kills the child.
const run = await runCliWithStdin(['put', 'stdin-hang-test-slug'], 'hold-open', 20_000);
expect(run.exited).toBe(true); // pre-#3513 this is false: the read never returns
- expect(run.exitCode).toBe(1);
+ expect(run.exitCode).toBe(2);
expect(run.stderr).toContain('Usage: gbrain put');
}, 30_000);
@@ -88,20 +88,20 @@ describe('#3513 — stdin-capable op with a non-TTY, never-written stdin', () =>
// the required check — proving the stream path read stdin and moved on.
const run = await runCliWithStdin(['put'], { data: '# hello\n' }, 20_000);
expect(run.exited).toBe(true);
- expect(run.exitCode).toBe(1);
+ expect(run.exitCode).toBe(2);
expect(run.stderr).toContain('Usage: gbrain put');
}, 30_000);
test('empty-but-real input (`< /dev/null`) does not hang', async () => {
const run = await runCliWithStdin(['put'], { file: '/dev/null' }, 20_000);
expect(run.exited).toBe(true);
- expect(run.exitCode).toBe(1);
+ expect(run.exitCode).toBe(2);
}, 30_000);
test('an empty pipe that closes immediately does not hang', async () => {
const run = await runCliWithStdin(['put'], 'closed-empty', 20_000);
expect(run.exited).toBe(true);
- expect(run.exitCode).toBe(1);
+ expect(run.exitCode).toBe(2);
}, 30_000);
});
diff --git a/test/cli.test.ts b/test/cli.test.ts
index 428cd142a6..d7511ff7fb 100644
--- a/test/cli.test.ts
+++ b/test/cli.test.ts
@@ -239,7 +239,7 @@ describe('CLI dispatch integration', () => {
expect(stdout.trim()).toMatch(/^gbrain \d+\.\d+\.\d+/);
});
- test('unknown command prints error and exits 1', async () => {
+ test('unknown command prints error and exits 2 (usage)', async () => {
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'notacommand'], {
cwd: new URL('..', import.meta.url).pathname,
stdout: 'pipe',
@@ -248,7 +248,7 @@ describe('CLI dispatch integration', () => {
const stderr = await new Response(proc.stderr).text();
const exitCode = await proc.exited;
expect(stderr).toContain('Unknown command: notacommand');
- expect(exitCode).toBe(1);
+ expect(exitCode).toBe(2);
});
test('per-command --help prints usage without DB connection', async () => {
diff --git a/test/engine-status.test.ts b/test/engine-status.test.ts
index a719c0936e..9cd86d0f17 100644
--- a/test/engine-status.test.ts
+++ b/test/engine-status.test.ts
@@ -175,11 +175,11 @@ describe('gbrain engine status', () => {
expect(stderr).toContain('Unknown flag for engine status');
}, 60_000);
- test('unknown --flag: intercepted by the CLI flag registry before dispatch (exit 1)', () => {
+ test('unknown --flag: intercepted by the CLI flag registry before dispatch (exit 2, usage)', () => {
// Dash-prefixed unknown flags never reach runEngineStatus — the global
// flag validation in cli.ts rejects them first with its own message.
const { status, stderr } = run(['engine', 'status', '--bogus']);
- expect(status).toBe(1);
+ expect(status).toBe(2);
expect(stderr).toContain('unknown flag --bogus');
}, 60_000);
});
diff --git a/test/eval-longmemeval-cli-smoke.test.ts b/test/eval-longmemeval-cli-smoke.test.ts
index cfa9cc3b20..9f894f9316 100644
--- a/test/eval-longmemeval-cli-smoke.test.ts
+++ b/test/eval-longmemeval-cli-smoke.test.ts
@@ -69,7 +69,7 @@ describe('gbrain eval longmemeval — documented invocation end-to-end', () => {
test('a typo is still refused by the validator before any eval code runs', () => {
const r = run(['eval', 'longmemeval', FIXTURE, '--retrieval-only', '--frobnicate']);
- expect(r.status).toBe(1);
+ expect(r.status).toBe(2);
expect(r.stderr).toContain("unknown flag --frobnicate for 'gbrain eval'");
expect(r.stderr).not.toContain('[longmemeval]');
}, 60_000);
diff --git a/test/fixtures/goldens/cli/engine-free-db-down.json b/test/fixtures/goldens/cli/engine-free-db-down.json
index 8752c47de7..326d5fb3ce 100644
--- a/test/fixtures/goldens/cli/engine-free-db-down.json
+++ b/test/fixtures/goldens/cli/engine-free-db-down.json
@@ -362,7 +362,7 @@
"exitCode": 1,
"stderr": [
"GBRAIN_DB_ACCESS conn_refused",
- "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check your connection URL in ~/.gbrain/config.json",
+ "Error [database_error]: Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check your connection URL in ~/.gbrain/config.json",
"Connection refused. If this is a Supabase direct URL (db.<ref>...:5432), switch to the transaction pooler (port 6543): gbrain db-repair can rewrite it. Run: gbrain db-repair"
],
"stderrFirstLine": "GBRAIN_DB_ACCESS conn_refused",
@@ -375,7 +375,7 @@
"exitCode": 1,
"stderr": [
"GBRAIN_DB_ACCESS conn_refused",
- "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check your connection URL in ~/.gbrain/config.json",
+ "Error [database_error]: Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check your connection URL in ~/.gbrain/config.json",
"Connection refused. If this is a Supabase direct URL (db.<ref>...:5432), switch to the transaction pooler (port 6543): gbrain db-repair can rewrite it. Run: gbrain db-repair"
],
"stderrFirstLine": "GBRAIN_DB_ACCESS conn_refused",
@@ -388,7 +388,7 @@
"exitCode": 1,
"stderr": [
"GBRAIN_DB_ACCESS conn_refused",
- "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check your connection URL in ~/.gbrain/config.json",
+ "Error [database_error]: Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check your connection URL in ~/.gbrain/config.json",
"Connection refused. If this is a Supabase direct URL (db.<ref>...:5432), switch to the transaction pooler (port 6543): gbrain db-repair can rewrite it. Run: gbrain db-repair"
],
"stderrFirstLine": "GBRAIN_DB_ACCESS conn_refused",
diff --git a/test/init-migrate-only.test.ts b/test/init-migrate-only.test.ts
index 4fdde8e0d9..a68adaaab7 100644
--- a/test/init-migrate-only.test.ts
+++ b/test/init-migrate-only.test.ts
@@ -63,7 +63,7 @@ describe('gbrain init --migrate-only — error paths', () => {
test('rejects unknown flags before any migrate-only side effects', () => {
const result = cached('init', '--migrate-only', '--dry-run');
- expect(result.exitCode).toBe(1);
+ expect(result.exitCode).toBe(2);
expect(result.stderr).toContain('unknown flag --dry-run');
// Unknown safety flags must not fall through to the migration path.
expect(result.stderr).not.toContain('No brain configured');
@@ -72,7 +72,7 @@ describe('gbrain init --migrate-only — error paths', () => {
test('unknown flags respect --json output', () => {
const result = cached('init', '--migrate-only', '--dry-run', '--json');
- expect(result.exitCode).toBe(1);
+ expect(result.exitCode).toBe(2);
const lines = result.stdout.split('\n').filter((l: string) => l.trim().startsWith('{'));
const parsed = JSON.parse(lines[lines.length - 1]);
expect(parsed.status).toBe('error');
diff --git a/test/recall-budget-policy-thin-cli.test.ts b/test/recall-budget-policy-thin-cli.test.ts
index f06e2de279..dcf30234d5 100644
--- a/test/recall-budget-policy-thin-cli.test.ts
+++ b/test/recall-budget-policy-thin-cli.test.ts
@@ -99,7 +99,7 @@ test('a query value spelling the policy flag does not opt a legacy thin call int
test('explicit thin brain selection fails before remote or local work', async () => {
const result = await thinCall('postgres', ['--budget-policy', 'query_first', '--brain', 'unregistered-example', '--json']);
- expect(result.exitCode).toBe(1);
+ expect(result.exitCode).toBe(2);
expect(result.stderr).toContain('--brain is not supported on a thin-client install');
expect(result.calls).toEqual([]);
expect(result.localStoreCreated).toBe(false);