Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(errors): per-reason class and exit overrides in the error registry
garrytan979200d2f144
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 92537a841c..ceb2fe01e2 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -6,12 +6,12 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/core/fix-routing.ts` — A1 render-time routing pin: `pinRouting(argv, routing)` appends `--brain` and the command's source flag (`--source`; `--source-id` for a record declaring `routes_source: '--source-id'`, extract, whose `--source` is a mode selector and never blocks the pin) before a bare `--` for commands that route them (shared ops registered by `operations.ts`; CLI-only commands from the generated `CLI_ROUTING_FLAGS`, built from the command table's `phase`/`routes_source` and each command's code). Holds the CLI process's routing provider (`installCliRouting`, installed by `src/cli/fix-routing-provider.ts`; never for `serve`) and the first source the invocation resolved (`noteResolvedSource`, called by the source resolver). Never imports the command table (its lazy loaders would bundle every command). Tests: `test/fix-routing.test.ts`; journey proof in `test/agent-journey-recovery.serial.test.ts`.- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`; the escalation flag `ask_user: true` marks a refusal whose every way out is the user's decision) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (a stored `ask_user: true` → `ask_user`; no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace, returned as the parser normalizes it (fix wave 13 P1.16); an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.-- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.-- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).+- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`, and `reason_overrides`: a reason whose class and exit replace the code's on the envelope and the CLI exit); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.+- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable, plus an `Override:` line per reason override) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).- `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` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`). #6758: every event carries `version` (defaults to the writing build's `VERSION`); on a warn the check adds `details.builds` (`this_build`, `other_builds`, `unknown_build` for older unversioned lines, `versions`) and `details.incident` (`historical` when no counted event came from this build, `since` the oldest), and the message names the events another build recorded. Test: `test/doctor-status-set.test.ts`.- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `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 (`PER_CALL_NOTICE_CODES`: `degraded_recall`, `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`, …) and, on HTTP, `degraded`/`safety` notices are never deduped, except that a notice's unrendered `Notice.dedupe_key` replaces its code as the dedupe identity and dedupes a per-call code once per session per key on stdio/CLI (`degradedRecallNotice` sets it only when every stage/reason pair is configuration-persistent: a keyless brain's `embed_unavailable`; HTTP ignores it for degraded notices; `renderNotice` never copies it); at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute). D4: `claim(key)` (true once per key) and `memoize(key, compute)` back the once-per-session `grant_blocked_operations` notice; codes in `SELF_DEDUPED_NOTICE_CODES` were deduped by their producer on its own key, so `admit` applies mute only. `hidden_tool_content` is per-call.- `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.test.ts`.+- `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; a `pglite_busy` with reason `legacy_owner_unverified` renders its own ask_user fix, `retryable: false`, exit 3). Test: `test/cli-error-render.test.ts`.- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.- `src/cli/flag-values.ts` — strict numeric values for CLI-only flags (D4): `intFlagValue` / `numberFlagValue` (digits only, safe integer, `[min, max]`) and `flagValueError` raise `invalid_params` usage errors (exit 2) naming the flag, what it accepts and an example. Used by jobs submit, extract-conversation-facts, eval run-all, sync `--interval`, connectors sync, book-mirror (the absorbed community fixes #5936 #5934 #5933 #5931 #5930 #5909). Tests: each command's `*-numeric-flags`/`*-flags` test.- `src/cli/op-param-values.ts` — `opParamValue`: typed values for shared ops from `ParamDef` inside `parseOpArgs` (number → finite, string enum → declared values), `invalid_params` with an example otherwise; mirrors MCP `validateParams`. `parseOpArgs` also honours a bare `--` (D6). Test: `test/cli-op-typed-args.test.ts`.diff --git a/src/commands/call.ts b/src/commands/call.tsindex 4e208e9228..ae852dab95 100644--- a/src/commands/call.ts+++ b/src/commands/call.ts@@ -136,5 +136,5 @@ async function failCall(tool: string, error: unknown, out: (text: string) => Proconst envelope = localCallErrorEnvelope(tool, error);await out(JSON.stringify(envelope, null, 2) + '\n');console.error(`Error [${envelope.code}]: ${envelope.message}`);- setCliExitVerdict(exitCodeForCode(envelope.code));+ setCliExitVerdict(exitCodeForCode(envelope.code, envelope.reason));}diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 06894c47e6..d0ff90fd0b 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -433,8 +433,8 @@ export function buildEnvelope(p: EnvelopeParts, ctx: RenderContext): AgentEnvelo...(p.why !== undefined ? { why: p.why } : {}),...(fix ? { fix } : {}),docs_cmd: ['gbrain', 'errors', p.code],- class: codeClass(p.code),- retryable: p.retryable ?? codeRetryable(p.code),+ class: codeClass(p.code, p.reason),+ retryable: p.retryable ?? codeRetryable(p.code, p.reason),...(notices ? { notices } : {}),contract_version: CONTRACT_VERSION,};@@ -850,7 +850,7 @@ export function projectionConflictLine(e: unknown, command: string): string | nu/** Pure: callers write the strings. TTY order: `Error [code]: msg` / `Fix:` / `Why:` / `Docs:`. */export function renderCliError(e: unknown, opts: { json: boolean; command: string; tty: boolean }): CliErrorRender {const env = toAgentError(e, { transport: 'cli', command: opts.command, render: cliRenderContext() });- const exitCode = exitCodeForCode(env.code);+ const exitCode = exitCodeForCode(env.code, env.reason);if (opts.json) return { stdout: `${JSON.stringify(env, null, 2)}\n`, exitCode };const lines = [`Error [${env.code}]: ${env.message}`];const relay = env.fix && !env.fix.command && env.fix.mcp ? `call ${env.fix.mcp.tool} over MCP with ${JSON.stringify(env.fix.mcp.arguments)}` : undefined;diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 77f68d2aac..307351c334 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -170,19 +170,27 @@ export function canonicalCodeFor(wire: string): string {return CANONICAL_BY_LEGACY.get(wire) ?? wire;}-/** An unregistered code is a server fault by construction (the AST test keeps that set empty). */-export function codeClass(code: string): ErrorClass {- return isRegistryCode(code) ? (CODES[code] as CodeEntry).class : 'server';+function reasonOverride(code: string, reason: string | undefined): { class: ErrorClass; exit?: number } | undefined {+ return reason === undefined || !isRegistryCode(code) ? undefined : (CODES[code] as CodeEntry).reason_overrides?.[reason];}-export function codeRetryable(code: string): boolean {+/** An unregistered code is a server fault by construction (the AST test keeps that set empty). A reason override replaces the code's class. */+export function codeClass(code: string, reason?: string): ErrorClass {+ return reasonOverride(code, reason)?.class ?? (isRegistryCode(code) ? (CODES[code] as CodeEntry).class : 'server');+}++export function codeRetryable(code: string, reason?: string): boolean {if (!isRegistryCode(code)) return false;+ const override = reasonOverride(code, reason);+ if (override) return override.class === 'retryable';const e = CODES[code] as CodeEntry;return e.retryable ?? e.class === 'retryable';}-/** CLI exit code for an error code (A3 table): entry override, else 1. */-export function exitCodeForCode(code: string): number {+/** CLI exit code for an error code (A3 table): reason override, then entry override, else 1. */+export function exitCodeForCode(code: string, reason?: string): number {+ const override = reasonOverride(code, reason);+ if (override) return override.exit ?? 1;return isRegistryCode(code) ? (CODES[code] as CodeEntry).exit ?? 1 : 1;}diff --git a/src/core/error-docs.ts b/src/core/error-docs.tsindex f3365d4d41..d319662020 100644--- a/src/core/error-docs.ts+++ b/src/core/error-docs.ts@@ -23,6 +23,8 @@ export interface ErrorCodeRow {legacy_error?: string;renamed_from?: string;reasons?: readonly string[];+ /** Reasons whose class and exit replace the code's. */+ reason_overrides?: Array<{ reason: string; class: ErrorClass; exit_code: number }>;}const CLASS_WHY: Record<ErrorClass, string> = {@@ -59,9 +61,12 @@ export function errorCodeRow(code: string): ErrorCodeRow | undefined {...(e.legacy_error ? { legacy_error: e.legacy_error } : {}),...(e.renamed_from ? { renamed_from: e.renamed_from } : {}),...(e.reasons?.length ? { reasons: e.reasons } : {}),+ ...(e.reason_overrides ? { reason_overrides: Object.entries(e.reason_overrides).map(([reason, o]) => ({ reason, class: o.class, exit_code: o.exit ?? 1 })) } : {}),};}+const overrideLine = (o: { reason: string; class: ErrorClass; exit_code: number }) => `reason ${o.reason}: ${o.class}, exit ${o.exit_code}${o.class === 'retryable' ? ', retryable' : ', not retryable'}`;+/** Codes whose wire `error` value stays frozen under v1 while `code` carries the canonical value. */export function changedCodeRows(): ErrorCodeRow[] {return (Object.keys(CODES) as RegistryCode[])@@ -81,6 +86,7 @@ export function renderErrorCodeText(r: ErrorCodeRow): string {` verify: ${r.verify}`,...(r.legacy_error ? [` legacy: some surfaces keep error: "${r.legacy_error}" with code: "${r.code}"`] : []),...(r.reasons?.length ? [` reasons: ${r.reasons.join(', ')}`] : []),+ ...(r.reason_overrides ?? []).map(o => ` override: ${overrideLine(o)}`),` docs: ${docsUrl(r.docs)}`,].join('\n');}@@ -117,6 +123,7 @@ export function renderErrorCodesMarkdown(): string {out.push('|---|---|---|---|---|---|---|');out.push(`| ${cell(r.meaning)} | ${cell(r.why)} | ${cell(r.next_step)} | ${r.actor}${r.effects.length ? ` · ${r.effects.join(', ')}` : ''} | \`${cell(r.verify)}\` | ${r.exit_code} | ${r.retryable ? 'yes' : 'no'} |`);if (r.reasons?.length) out.push('', `Reasons: ${r.reasons.map(x => `\`${x}\``).join(', ')}.`);+ for (const o of r.reason_overrides ?? []) out.push('', `Override: ${overrideLine(o).replace(o.reason, `\`${o.reason}\``)}.`);if (r.docs !== `docs/guides/error-codes.md#${r.code}`) out.push('', `More: [${r.docs}](../../${r.docs})`);out.push('');}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 56524e685b..05ba4803b5 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -28,6 +28,11 @@ export interface CodeEntry {* still carry one, so it stays explained here, and it never returns to `reasons`.*/retired_reasons?: Readonly<Record<string, string>>;+ /**+ * A reason whose next step differs in kind from the code's (a lock that waiting never frees needs the user, not a retry):+ * its class and exit replace the code's on the envelope and the CLI exit. Every key is also in `reasons`.+ */+ reason_overrides?: Readonly<Record<string, { class: ErrorClass; exit?: number }>>;/** Repo-relative anchor; default `docs/guides/error-codes.md#<code>`. */docs?: string;/** Default prose suggestion when a site supplies none. */