Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(exit-codes): A3 exit table; exit 3 means confirmation_required only
garrytan0921d509289b
diff --git a/docs/guides/exit-codes.md b/docs/guides/exit-codes.mdnew file mode 100644index 0000000000..f904fb2433--- /dev/null+++ b/docs/guides/exit-codes.md@@ -0,0 +1,40 @@+# Exit codes++Every `gbrain` command exits with one of these statuses. An agent branches on+the exit code first, then reads the JSON document (`--json`) for the details:+`code`, `class`, `retryable` and `fix`. The protocol page is+[AGENT_OPERATOR_v1](../protocol/AGENT_OPERATOR_v1.md); error codes are listed in+[error codes](error-codes.md).++**Say to your agent:** *"The gbrain command exited 3. What does it need from me?"*++| Exit | Meaning | `--json` document | What the agent does |+|---|---|---|---|+| 0 | ok | the result | continue |+| 1 | failed | error envelope with `class` and `retryable` | follow `fix.next`; retry only when `retryable` is true |+| 2 | usage error or invalid input | error envelope (`invalid_params`, `unknown_flag`) | correct the command; `gbrain <command> --help` |+| 3 | `confirmation_required`: nothing ran | consent payload (`effects`, `user_message`, `fix`) | stop, relay `user_message` to the user, run `fix.command` only after they agree |+| 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0 |+| 11 | partial, resumable budget stop | result with `remaining_*` and `resume_command` | run `resume_command` (it is safe to re-run) |+| 75 | another runner holds the migration lock | error envelope | wait for the other runner, then retry |+| 124 | the command's own deadline elapsed | error envelope | inspect what is still running (the message names the status command) |+| 130 | interrupted (SIGINT) | error envelope | ask the user whether to re-run |++`class` and `retryable` live only in the JSON document; the exit code stays+coarse so shell scripts can branch on it.++Under contract v1, `gbrain mcp expose` and `gbrain google` still exit 2 when+they need the user's confirmation (documented legacy; changing it is a v2 item).++## Changed in this release++| Command | Before | Now | Why |+|---|---|---|---|+| `gbrain embed --stale` time-budget stop | 3 | 11 | 3 means "ask the user first"; a budget stop means "run the resume command" |+| `gbrain agent run … --follow` timeout | 3 | 124 | a timeout, not a consent stop; the job keeps running |+| `gbrain providers test` transient provider error | 3 | 1 (retryable) | retryable failure |+| `gbrain sources harden` with sources needing attention | 3 | 1 | failure for cron; the report names what to fix |+| `gbrain sources pull` rebase conflict aborted | 3 | 1 | failure |+| `gbrain sources remove default` / `gbrain sources archive default` | 3 | 2 | invalid input |+| `gbrain extract-conversation-facts` pages skipped on a busy lock | 3 | 1 (retryable) | re-run to finish the skipped pages |+| `gbrain call` invalid parameters | 1 | 2 | invalid input; stdout now carries the error envelope |diff --git a/src/commands/agent.ts b/src/commands/agent.tsindex ecbf137566..78caa84a02 100644--- a/src/commands/agent.ts+++ b/src/commands/agent.ts@@ -22,6 +22,7 @@ import type { MinionJobInput, SubagentHandlerData, AggregatorHandlerData } fromimport { resolveSourceId, isResolverUserError, ALL_SOURCES } from '../core/source-resolver.ts';import { fetchSource } from '../core/sources-load.ts';import { runAgentLogs } from './agent-logs.ts';+import { TIMEOUT_EXIT_CODE } from '../core/exit-codes.ts';// ── arg parsing helpers ────────────────────────────────────@@ -480,7 +481,7 @@ async function followJob(engine: BrainEngine, queue: MinionQueue, jobId: number,} catch (e) {if (e instanceof TimeoutError) {process.stderr.write(`[gbrain agent] timeout after ${e.elapsedMs}ms — job is still running. Check with: gbrain jobs get ${jobId}\n`);- process.exit(3);+ process.exit(TIMEOUT_EXIT_CODE);}throw e;}diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 9e2b303dfc..989885366b 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -381,6 +381,7 @@ import {import { readConversationBodyForParsing } from '../core/conversation-parser/body.ts';import { runLlmFallback } from '../core/conversation-parser/llm-fallback.ts';import { resolveModel, resolveTierDefault } from '../core/model-config.ts';+import { FAILED_EXIT_CODE } from '../core/exit-codes.ts';/*** v0.41.13.0 — back-compat shape for direct callers + the existing@@ -2116,9 +2117,9 @@ export async function runExtractConversationFacts(}}- // v0.41.15.0 (codex #3): exit 3 when pages were skipped due to- // lock-busy AND no hard failures fired. "Incomplete run, please- // re-run" — distinct from exit 1 (hard failure) and 0 (clean).+ // v0.41.15.0 (codex #3): pages skipped due to lock-busy AND no hard+ // failures fired: "incomplete run, please re-run". Exit 1 (retryable) —+ // 3 is reserved for confirmation_required under the agent contract v1.// anyBudgetExhausted doesn't trigger exit 3; the budget message// above already tells the user what to do, and exit 0 is the right// signal for "ran to the cap intentionally."@@ -2126,7 +2127,8 @@ export async function runExtractConversationFacts(process.exit(1);}if (aggregate.pages_lock_skipped > 0 && !anyBudgetExhausted) {- process.exit(3);+ console.error(`${aggregate.pages_lock_skipped} page(s) were skipped because another writer held their lock; re-run the same command to finish them (retryable).`);+ process.exit(FAILED_EXIT_CODE);}}diff --git a/src/commands/providers.ts b/src/commands/providers.tsindex be693ea9f3..8900e8878f 100644--- a/src/commands/providers.ts+++ b/src/commands/providers.ts@@ -13,6 +13,7 @@ import { loadConfig } from '../core/config.ts';import { AIConfigError, AITransientError } from '../core/ai/errors.ts';import { lookupEmbeddingPrice } from '../core/embedding-pricing.ts';import type { Recipe } from '../core/ai/types.ts';+import { FAILED_EXIT_CODE } from '../core/exit-codes.ts';const SCHEMA_VERSION = 1;@@ -286,8 +287,8 @@ async function runTest(args: string[]): Promise<void> {process.exit(2);} else if (e instanceof AITransientError) {console.error(` ✗ transient error (${ms}ms): ${e.message}`);- console.error(` Retry after a moment.`);- process.exit(3);+ console.error(` Retry after a moment (retryable).`);+ process.exit(FAILED_EXIT_CODE);} else {console.error(` ✗ unknown error (${ms}ms): ${e instanceof Error ? e.message : e}`);process.exit(4);diff --git a/src/commands/sources-harden.ts b/src/commands/sources-harden.tsindex 692fccd2a3..d5cce39cbe 100644--- a/src/commands/sources-harden.ts+++ b/src/commands/sources-harden.ts@@ -22,6 +22,7 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { invalidateBackupStatus } from '../core/backup/status-file.ts';import { existsSync } from 'fs';import { join } from 'path';+import { FAILED_EXIT_CODE } from '../core/exit-codes.ts';interface SourceRow { id: string; local_path: string | null; config: unknown; }@@ -116,7 +117,7 @@ export async function runHarden(engine: BrainEngine, args: string[]): Promise<vo// Non-zero exit if any source needs attention, so cron/automation notices.// Route through setCliExitVerdict — a raw process.exitCode write is zeroed by// the owned-verdict flush-exit (#2084 / PGLite-Emscripten pollution defense).- if (reports.some(r => r.needs_attention.length > 0)) setCliExitVerdict(3);+ if (reports.some(r => r.needs_attention.length > 0)) setCliExitVerdict(FAILED_EXIT_CODE);}function renderReport(r: DurabilityReport): void {@@ -167,7 +168,7 @@ export async function runPull(engine: BrainEngine | null, args: string[]): Promicase 'skipped_dirty': console.log(`skipped — working tree dirty (${branch})`); break;case 'conflict_aborted':console.error(`[gbrain] ${outcome.detail}`);- process.exit(3);+ process.exit(FAILED_EXIT_CODE);}}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 610d91d223..a7e67cd158 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -70,6 +70,7 @@ import {import { sqlQueryForEngine } from '../core/sql-query.ts';import { preflightOauthClientColumns } from './auth.ts';import { deleteSourceRow } from '../core/source-delete.ts';+import { USAGE_EXIT_CODE } from '../core/exit-codes.ts';// ── Validation ──────────────────────────────────────────────@@ -772,7 +773,7 @@ async function runRemove(engine: BrainEngine, args: string[]): Promise<void> {if (id === 'default') {console.error('Error: cannot remove the "default" source (it backs the pre-v0.17 brain).');- process.exit(3);+ process.exit(USAGE_EXIT_CODE);}const src = await fetchSource(engine, id);@@ -938,7 +939,7 @@ async function runArchive(engine: BrainEngine, args: string[]): Promise<void> {if (id === 'default') {console.error('Error: cannot archive the "default" source.');- process.exit(3);+ process.exit(USAGE_EXIT_CODE);}// Show impact previewdiff --git a/src/core/exit-codes.ts b/src/core/exit-codes.tsindex c79d805b71..e903662d27 100644--- a/src/core/exit-codes.ts+++ b/src/core/exit-codes.ts@@ -1,8 +1,30 @@/*** Process exit statuses with a contract beyond "0 ok / 1 failed". One home so* a new status cannot silently reuse a value a caller already branches on.+ *+ * Agent operator contract v1 table (docs/guides/exit-codes.md):+ * 0 ok · 1 failed (class/retryable in JSON) · 2 usage / invalid input ·+ * 3 confirmation_required (its ONLY meaning) · 10 write pending ·+ * 11 resumable budget stop · 75 migration lock held · 124 timeout ·+ * 130 interrupted. `test/exit-codes.test.ts` enumerates every literal+ * exit 3 in src/ so a new one cannot reuse it.*/+export const OK_EXIT_CODE = 0;+export const FAILED_EXIT_CODE = 1;+/** Usage error or invalid input (`invalid_params`, `unknown_flag`). */+export const USAGE_EXIT_CODE = 2;+/**+ * The command needs the user's authorization and ran nothing+ * (`confirmation_required`; `--json` prints the consent payload). Agents stop+ * and ask. `mcp expose` and `google` also use 2 for this under v1 (legacy).+ */+export const CONFIRMATION_REQUIRED_EXIT_CODE = 3;+/** The command's own deadline elapsed; work may still be running elsewhere. */+export const TIMEOUT_EXIT_CODE = 124;+/** Interrupted by a signal (SIGINT). */+export const INTERRUPTED_EXIT_CODE = 130;+/** A runner refused because another runner holds the migration lock (EX_TEMPFAIL). */export const MIGRATIONS_RUNNING_EXIT_CODE = 75;diff --git a/test/exit-codes.test.ts b/test/exit-codes.test.tsnew file mode 100644index 0000000000..bb278fc076--- /dev/null+++ b/test/exit-codes.test.ts@@ -0,0 +1,84 @@+/**+ * Agent operator contract v1 exit table (docs/designs/AGENT_OPERATOR_WAVE.md+ * A3). Exit 3 means confirmation_required and nothing else: every literal+ * `exit(3)`, `setCliExitVerdict(3)`, `exitCode = 3` and exported exit-code+ * constant equal to 3 in src/ must be listed here, so an unlisted one fails.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync, readdirSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import * as exitCodes from '../src/core/exit-codes.ts';+import { exitCodeForCode } from '../src/core/error-catalogue.ts';++const ROOT = join(import.meta.dir, '..');++function srcFiles(dir: string): string[] {+ const out: string[] = [];+ for (const e of readdirSync(dir)) {+ const full = join(dir, e);+ if (statSync(full).isDirectory()) out.push(...srcFiles(full));+ else if (e.endsWith('.ts')) out.push(full);+ }+ return out;+}++/** The only sanctioned exit-3 sites: the constant itself. */+const ALLOWED_EXIT_3: ReadonlySet<string> = new Set([+ 'src/core/exit-codes.ts: CONFIRMATION_REQUIRED_EXIT_CODE',+]);++describe('exit code table', () => {+ test('the published values', () => {+ expect(exitCodes.OK_EXIT_CODE).toBe(0);+ expect(exitCodes.FAILED_EXIT_CODE).toBe(1);+ expect(exitCodes.USAGE_EXIT_CODE).toBe(2);+ expect(exitCodes.CONFIRMATION_REQUIRED_EXIT_CODE).toBe(3);+ expect(exitCodes.PENDING_WRITE_EXIT_CODE).toBe(10);+ expect(exitCodes.BUDGET_STOP_EXIT_CODE).toBe(11);+ expect(exitCodes.MIGRATIONS_RUNNING_EXIT_CODE).toBe(75);+ expect(exitCodes.TIMEOUT_EXIT_CODE).toBe(124);+ expect(exitCodes.INTERRUPTED_EXIT_CODE).toBe(130);+ });++ test('every constant is distinct', () => {+ const values = Object.values(exitCodes).filter(v => typeof v === 'number');+ expect(new Set(values).size).toBe(values.length);+ });++ test('registry codes map onto the table', () => {+ expect(exitCodeForCode('confirmation_required')).toBe(3);+ expect(exitCodeForCode('invalid_params')).toBe(2);+ expect(exitCodeForCode('unknown_flag')).toBe(2);+ expect(exitCodeForCode('write_pending')).toBe(10);+ expect(exitCodeForCode('timeout')).toBe(124);+ expect(exitCodeForCode('interrupted')).toBe(130);+ expect(exitCodeForCode('internal_error')).toBe(1);+ expect(exitCodeForCode('approval_required')).toBe(1);+ });++ test('no exit 3 in src/ outside confirmation_required', () => {+ const offenders: string[] = [];+ const patterns: RegExp[] = [+ /\bexit\(\s*3\s*\)/,+ /setCliExitVerdict\(\s*3\s*\)/,+ /\bexitCode\s*=\s*3\b/,+ /flushThenExit\(\s*3\s*[,)]/,+ ];+ for (const file of srcFiles(join(ROOT, 'src'))) {+ const rel = relative(ROOT, file);+ const lines = readFileSync(file, 'utf8').split('\n');+ lines.forEach((line, i) => {+ if (patterns.some(p => p.test(line))) offenders.push(`${rel}:${i + 1}: ${line.trim()}`);+ const constant = /export const ([A-Z0-9_]*EXIT[A-Z0-9_]*)\s*=\s*3\s*;/.exec(line);+ if (constant && !ALLOWED_EXIT_3.has(`${rel}: ${constant[1]}`)) offenders.push(`${rel}:${i + 1}: ${constant[1]} = 3`);+ });+ }+ expect(offenders).toEqual([]);+ });++ test('the exit-codes guide documents every value', () => {+ const doc = readFileSync(join(ROOT, 'docs/guides/exit-codes.md'), 'utf8');+ for (const v of [0, 1, 2, 3, 10, 11, 75, 124, 130]) expect(doc).toContain(`| ${v} |`);+ expect(doc).toContain('## Changed in this release');+ });+});