Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge D2b and the collector (Lanes B, E, F, Foundations 1 / master) into capy/aow-lane-d
garrytan28f81c18d0b7
diff --cc docs/architecture/key-files/agent-contract.mdindex 518ece90fe,255fce9460..03fd11b91d--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@@ -7,14 -7,16 +7,22 @@@ Spec: `docs/designs/AGENT_OPERATOR_WAVE- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (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`, 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. `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`.- `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/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/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`).- `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/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), a bare `--flag` in MCP-visible error text or op descriptions outside a full `gbrain …` command (`flag-in-mcp-text`), a `<placeholder>` in a fix argv without declared `inputs` or in an error suggestion (`in-scope-placeholder`), "retry" advice from a mutating non-idempotent op handler (`retry-on-mutating`), 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.+- `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/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.serial.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`.+- `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `harness_wiring` today). Tests: `test/cli-json-guard.serial.test.ts`.+- `test/cli-contract.serial.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.+- `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`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.serial.test.ts`) has one row per declaration, `<command> <sub>` included.+- `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.+ - `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; none on a brain keyless by choice). `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.+ - `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` — F4 status-only stdio serve. cli.ts hands over a `serve` (stdio, host brain, not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, or a PGLite lock held by a live holder; `runStatusModeServe` builds a gated lazy engine (`createDegradedEngine` with the configured `kind`; its method set aligns with the live engine on recovery) marked with `StatusModeState`. `probeStatus` reads config + `peekLock` only; `gatedReconnect` refuses while blocked (no lock attempt) and otherwise connects (≤1 attempt / 5 s, inside tool calls only, `resetReadinessMemo()` first). `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. Test: `test/serve-status-mode.serial.test.ts` (recover in place → recall; shared `serve --http` with tokens minted before it starts → both harnesses recall; no brain → init → recall; `--fail-fast`).+ - `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.+ - `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`) and `GBRAIN_SURFACE=full`; HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills.+ - `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.+ - `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).+ - `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.+ - `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.diff --cc docs/architecture/key-files/commands-1.mdindex b02d58c7cb,4febc51cd4..93ea88929b--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@@ -3,7 -3,7 +3,7 @@@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- - `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.serial.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending`, `database_error` for `--require-db`, `migrations_running` exit 75). A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.serial.test.ts`.-- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains; a phase's `argv` prints as its next step. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.serial.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.++- `src/commands/apply-migrations.ts` and `src/commands/migrations/v0_11_0.ts` — forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.serial.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`. D2 (`json: 'document'`): every `--json` path is one single-line document (`status` unconfigured/dry_run/listed/ok/partial/up_to_date, `plan`, `previews`, `results[]`, `retry_markers`, `schema`); a non-zero exit is one envelope leading with those keys (`invalid_params` exit 2, `migration_failed` with reasons, `migrations_pending`, `database_error` for `--require-db`, `migrations_running` exit 75). A4: `Migration.effects` (v0.11.0: `persistent_install`, its Phase F autopilot install) is asked through `consentGate` before the orchestrator runs (skipped under `--no-autopilot-install` or on PGLite); `--yes`, `--non-interactive` (mapped to `persistent_install` only), a preapproval or a TTY yes authorize, otherwise exit 3. `applyMigrations()` returns `{exitCode, failure}` for in-process callers (post-upgrade); `runApplyMigrations()` exits. Child CLIs use `cliChildStdio()`. Tests: `test/cli-json-commands.serial.test.ts`. the plan adds `pending_fresh_install` (unrun setup work on a brain `gbrain init` created; runs like `pending`, reported as expected work, never as a failed upgrade); `--list --json` prints one row per migration (`fresh_install: true` on init stamps) plus `next.argv` when work remains; a phase's `argv` prints as its next step. Forced dry-runs return a no-write action preview before opening a database or loading/copying the migration ledger. Any failed phase makes the migration partial, stops the chain and exits nonzero; ordinary pending-host-work partial results retain their resume behavior. Explicit `--force-retry` recovers a historical false-complete record. No-autopilot skips remain successful and do not install services. Every run except `--list` and `--dry-run` holds the orchestration lock (`src/core/migration-orchestration-lock.ts`) from before its first ledger write through its final status: a Postgres TTL lease row `gbrain-apply-migrations` in `gbrain_cycle_locks` (survives transaction-mode poolers; an unreachable database or a schema without the table runs unlocked until the preflight creates it), or on PGLite a native lock on `<datastore>.gbrain-migrations.lock`, separate from the datastore lock so orchestrators still open the datastore. A second runner prints `another apply-migrations is running (host …, pid …)` and exits 75; dead holders are taken over by the existing db-lock and kernel rules. The locked body returns its exit status so the lock is released before `process.exit`. Tests: `apply-migrations-safety.serial.test.ts`, `apply-migrations-orchestration-lock.serial.test.ts`, `e2e/apply-migrations-orchestration-lock.test.ts` and `e2e/migration-preview-safety.test.ts`.- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.diff --cc scripts/agent-contract-baselines/yes-rerun-string.tsvindex 7c7d235720,1797ba002b..a130ae4209--- a/scripts/agent-contract-baselines/yes-rerun-string.tsv+++ b/scripts/agent-contract-baselines/yes-rerun-string.tsv@@@ -1,9 -1,8 +1,6 @@@# shrink-only baseline for scripts/check-agent-contract.ts rule yes-rerun-string: path<TAB>count- src/commands/config.ts 1-src/cli.ts 3-src/commands/apply-migrations.ts 3src/commands/db-repair.ts 1- src/commands/doctor/checks/memory-writeback.ts 2src/commands/mcp-expose.ts 3- src/commands/migrations/v0_11_0.ts 1src/core/page-state/credential-reseal.ts 1src/core/schema-migrations/v039-multimodal-dual-column-v0-27-1.ts 2src/core/schema-migrations/v045-facts-hot-memory-v0-31.ts 1diff --cc scripts/module-size-limits.tsvindex 7b6b9b7484,ffd0c4d3a8..fbe3553896--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -3,14 -3,14 +3,14 @@@# 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 3172 ratchet +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +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/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 3195 ratchet +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +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 1642 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); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)+ src/commands/doctor.ts 666 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)+src/commands/embed.ts 2219 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; 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)src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)- src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)- src/commands/serve-http.ts 917 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts)+ src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5)+ src/commands/serve-http.ts 919 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities)src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)src/core/cycle.ts 3207 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix@@@ -25,7 -25,7 +25,7 @@@ src/core/postgres-engine.ts 2914 ratchesrc/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache keysrc/core/types.ts 2123 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes)src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys- src/commands/init.ts 1880 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init-src/commands/init.ts 1935 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; +2: E8 fresh-install migration stamping in both engine epilogues (logic lives in commands/migrations/fresh-install.ts); +1 --mcp-only pre-flight: rate-limit hint and retry_after_s for a /token 429 (1935 at the Lane E merge)++src/commands/init.ts 1883 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-initsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatchsrc/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)diff --cc src/cli/commands/sync.tsindex 2ae535c56e,952b26f932..26adc1d328--- a/src/cli/commands/sync.ts+++ b/src/cli/commands/sync.ts@@@ -3,21 -3,26 +3,31 @@@* engine connectEngine() opened. Moved verbatim from the src/cli.ts* handleCliOnly switch (refactor wave 1, W4 cli); the record lives in* src/cli/command-table.ts.+ *+ * A refusal that carries an agent-contract `fix` (e.g. `sync_not_applicable`,+ * `writer_coordinator_required`) renders through `renderCliError` so the+ * operator sees the code, the exact next command and why (`--json`: the v1+ * envelope on stdout).*/import type { BrainEngine } from '../../core/engine.ts';- import { opError } from '../../core/ops/contract.ts';-import { OperationError } from '../../core/ops/contract.ts';++import { OperationError, opError } from '../../core/ops/contract.ts';++import { setCliExitVerdict } from '../../core/cli-force-exit.ts';++import { writeCliError } from '../cli-error.ts';export async function run(engine: BrainEngine, args: string[]): Promise<void> {- const { runSync } = await import('../../commands/sync.ts');+ const { runSync, SyncLockBusyError } = await import('../../commands/sync.ts');try {await runSync(engine, args);- } catch (e) {+ } catch (err) {+ // D1/D2: a busy sync lock is a retryable sync_in_progress refusal (its+ // message names the holder and the --break-lock recovery), not an+ // unclassified internal error.- if (!(e instanceof SyncLockBusyError)) throw e;- throw opError('sync_in_progress', e.message,- `Wait for the running sync to finish and retry. If its holder is dead, run \`gbrain sync --break-lock\` (with the same --source).`,- { reason: 'lock_busy', detail: e.lockKey });++ if (err instanceof SyncLockBusyError) {++ throw opError('sync_in_progress', err.message,++ `Wait for the running sync to finish and retry. If its holder is dead, run \`gbrain sync --break-lock\` (with the same --source).`,++ { reason: 'lock_busy', detail: err.lockKey });++ }+ if (!(err instanceof OperationError) || !err.fix) throw err;- const { renderCliError } = await import('../../core/agent-output.ts');- const { setCliExitVerdict, writeStdoutFinal } = await import('../../core/cli-force-exit.ts');- const out = renderCliError(err, { json: args.includes('--json'), command: 'sync', tty: !!process.stderr.isTTY });- if (out.stdout) await writeStdoutFinal(out.stdout);- if (out.stderr) process.stderr.write(out.stderr);- setCliExitVerdict(out.exitCode);++ setCliExitVerdict(writeCliError(err, 'sync', { json: args.includes('--json') }));}}diff --cc src/commands/apply-migrations.tsindex 910ca8cabe,41617b07d9..26d5d1175a--- a/src/commands/apply-migrations.ts+++ b/src/commands/apply-migrations.ts@@@ -27,13 -27,12 +27,16 @@@ import { migrations, compareVersions, timport {indexCompletedEntries,statusForVersion as ledgerStatusForVersion,+ freshInstallVersion,+ isFreshInstallStamp,+ isPendingFreshInstall,MAX_CONSECUTIVE_PARTIALS,} from '../core/migration-ledger.ts';- import type { Effect } from '../core/agent-output.ts';-import { shellQuote } from '../core/agent-output.ts';++import { shellQuote, type Effect } from '../core/agent-output.ts';+import { writeJsonDocument } from '../core/cli-force-exit.ts';+import { consentGate } from '../core/consent-cli.ts';+import { opError, type OperationError } from '../core/ops/contract.ts';+import { exitCliError, usageError, writeCliError } from '../cli/cli-error.ts';interface ApplyMigrationsArgs {list: boolean;@@@ -263,6 -279,25 +289,25 @@@ function printList(plan: Plan, installe}}-/** `--list --json`: one row per registered migration plus the command that completes outstanding work. */-function printListJson(plan: Plan, idx: CompletedIndex, installed: string, dbProbe: DbProbeOutcome): void {++/** `--list --json` fields: one row per registered migration plus the command that completes outstanding work. */++function listJson(plan: Plan, idx: CompletedIndex, installed: string, dbProbe: DbProbeOutcome): Record<string, unknown> {+ const outstanding = plan.pending.length + plan.partial.length + plan.pending_fresh_install.length;- console.log(JSON.stringify({++ return {+ installed,+ database: dbProbe,+ fresh_install_version: idx.freshVersion,+ migrations: listRows(plan).map(r => ({+ version: r.m.version,+ status: r.status,+ headline: r.m.featurePitch.headline,+ ...(r.status === 'applied' && (idx.byVersion.get(r.m.version) ?? []).some(isFreshInstallStamp) ? { fresh_install: true } : {}),+ })),+ needs_action: plan.pending.length + plan.partial.length,+ pending_fresh_install: plan.pending_fresh_install.length,+ ...(outstanding > 0 ? { next: { argv: FINISH_SETUP_ARGV, command: shellQuote(FINISH_SETUP_ARGV) } } : {}),- }));++ };+ }+function printDryRun(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void {console.log(`Dry run — installed gbrain version: ${installed}`);console.log(formatDbProbeLine(dbProbe));@@@ -578,17 -597,15 +628,17 @@@ async function runLockedMigrations// Don't exit — applied/partial/pending are still worth reporting and running.}- if (cli.specificMigration && plan.applied.length + plan.partial.length + plan.pending.length + plan.skippedFuture.length === 0) {+ if (cli.specificMigration && plan.applied.length + plan.partial.length + plan.pending.length + plan.pending_fresh_install.length + plan.skippedFuture.length === 0) {console.error(`No migration registered with version "${cli.specificMigration}". Run \`gbrain apply-migrations --list\` to see registered versions.`);+ fail('invalid', unknownMigrationError(cli.specificMigration));return 2;}// #4364: --require-db turns an unreachable DB into a hard failure instead// of a filesystem-only plan that renders identically to a clean database.const listExit = cli.requireDb && dbProbe.status === 'unreachable' ? 1 : 0;- if (cli.list && cli.json) { printListJson(plan, idx, installed, dbProbe); return listExit; }+ if (listExit) fail('database_unreachable', requireDbError(dbProbe));- if (cli.list && cli.json) { doc.status = listExit ? doc.status : 'listed'; return listExit; }++ if (cli.list && cli.json) { Object.assign(doc, listJson(plan, idx, installed, dbProbe)); doc.status = listExit ? doc.status : 'listed'; return listExit; }if (cli.list) { printList(plan, installed, dbProbe); return listExit; }if (cli.dryRun) {const previews: Array<{ version: string; preview?: unknown; error?: string }> = [];@@@ -630,10 -642,9 +680,10 @@@return 1;}console.log('All migrations up to date.');+ doc.status = 'up_to_date';return 0;}- if (!schemaBehind && plan.pending.length === 0 && plan.partial.length === 0) {+ if (!schemaBehind && plan.pending.length === 0 && plan.pending_fresh_install.length === 0 && plan.partial.length === 0) {console.log('All migrations up to date. This covers orchestrator checkpoints only; host publication and client activation are being rechecked.');}diff --cc src/commands/doctor/remediate.tsindex be1c4d0326,487e0513ae..260d195677--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@@ -115,8 -115,8 +115,8 @@@ export async function runRemediationPlaconst plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed } });const planHash = plan.repair_steps?.length ? await remediationPlanHash(engine, args, plan) : undefined;if (args.includes('--json')) {- console.log(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),+ await writeJsonDocument(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),- combined_command: combinedRemediateCommand(plan, targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}) }, null, 2));+ combined_command: combinedRemediateCommand(plan, plan.target_unreachable ? plan.max_reachable_score : targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}) }, null, 2));return;}for (const line of renderRemediationPlanLines(plan, targetScore, { noEmbed, planHash })) console.log(line);diff --cc src/commands/dream.tsindex e177cecd80,aef6337854..f938da986b--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@@ -864,20 -873,23 +864,24 @@@ export async function runDream(engine:onceForPhase: opts.once ? opts.phases[0]! : undefined,});- // Exit non-zero when the cycle failed overall (helps cron spot real problems).- // 'partial' is not a failure — it means some phase warned but the cycle ran —- // except when a phase threw and was contained so later phases could run.- const failed = report.status === 'failed' || report.phases.some(p => p.details?.contained === true);- if (opts.json) {- console.log(JSON.stringify(report, null, 2));- } else {- printHuman(report);- }-+ // Exit non-zero when the cycle failed overall or any phase failed (agent-first+ // operator wave E4): a 'partial' cycle whose phase reports 'fail' — thrown and+ // contained, or caught inside the runner — is never success. Warn-only+ // 'partial' cycles still exit 0.- const failedPhases = report.phases.filter(p => p.status === 'fail').map(p => p.phase);- if (report.status === 'failed' || failedPhases.length > 0) {- if (!opts.json && failedPhases.length > 0) {- console.error(`Dream failed: ${failedPhases.length} phase(s) failed (${failedPhases.join(', ')}); see the phase errors above. After fixing the cause, re-run one with: gbrain dream --phase ${failedPhases[0]}`);- }- process.exit(1);- }++ const failedPhases = report.phases.filter(p => p.status === 'fail' || p.details?.contained === true).map(p => p.phase);++ const failed = report.status === 'failed' || failedPhases.length > 0;+ if (!opts.json) printHuman(report);+ else if (!failed || !jsonGuardActive()) await writeJsonDocument(JSON.stringify(report, null, 2));+ else {+ // D2: under the --json guard a failed cycle is one envelope leading with the CycleReport keys.- const bad = report.phases.filter(p => p.status === 'fail' || p.details?.contained === true).map(p => p.phase);- writeCliError(opError('cycle_failed', `The dream cycle ${report.status === 'failed' ? 'failed' : 'contained a phase that threw'}${bad.length ? ` (${bad.join(', ')})` : ''}.`,- `Read phases[].error for the cause, fix it, then rerun the phase: gbrain dream --phase ${bad[0] ?? '<phase>'}`),++ writeCliError(opError('cycle_failed', `The dream cycle ${report.status === 'failed' ? 'failed' : 'had failing phases'}${failedPhases.length ? ` (${failedPhases.join(', ')})` : ''}.`,++ `Read phases[].error for the cause, fix it, then rerun the phase: gbrain dream --phase ${failedPhases[0] ?? '<phase>'}`),+ 'dream', { json: true, stderr: false, legacy: { ...report } });+ }++ if (failed && !opts.json && failedPhases.length > 0) {++ console.error(`Dream failed: ${failedPhases.length} phase(s) failed (${failedPhases.join(', ')}); see the phase errors above. After fixing the cause, re-run one with: gbrain dream --phase ${failedPhases[0]}`);++ }+ if (failed) process.exit(1);return report;}diff --cc src/commands/migrations/types.tsindex 6abd8eac1a,6c4500cb06..08c5db18de--- a/src/commands/migrations/types.ts+++ b/src/commands/migrations/types.ts@@@ -69,10 -69,13 +71,19 @@@ export interface Migrationorchestrator: (opts: OrchestratorOpts) => Promise<OrchestratorResult>;preview?: (opts: OrchestratorOpts) => Promise<unknown>;reconcile?: boolean;+ /**+ * Consent effects the orchestrator performs (agent operator contract A4);+ * apply-migrations asks for them before running it. `persistent_install`+ * is skipped (and not asked) under --no-autopilot-install or on PGLite.+ */+ effects?: readonly Effect[];+ /**+ * True only when the orchestrator changes nothing on a brain `gbrain init`+ * just created: schema already current, no data to backfill, no files,+ * preferences or services to write. Init records these as complete+ * (`fresh_install: true` ledger entries, `./fresh-install.ts`); every other+ * migration lists as `pending_fresh_install` until it runs. Each flagged+ * migration is proven by test/migrations-fresh-install-audit.serial.test.ts.+ */+ fresh_install_noop?: true;}diff --cc src/core/agent-output.tsindex e245a2f6ff,a1f4a00ecb..5cb2fcf279--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@@ -506,33 -565,11 +567,28 @@@ const ROWS: Row[] =}),},{- // A keyless brain (`init --no-embedding`) asked to embed: a capability- // disabled by choice, not a server fault.- match: named('EmbeddingDisabledError'),- map: (e: Error) => ({- error: 'embedding_disabled', code: 'embedding_disabled', reason: 'disabled_by_choice', message: e.message.split('\n')[0],- suggestion: 'Keyword search keeps working without embeddings. To turn them on, see `gbrain embeddings enable --help`.',- fix: { argv: ['gbrain', 'embeddings', 'enable', '--help'], consent: [], actor: 'agent', requires_exclusive: false,- why: 'Shows the command that enables embeddings for this brain and what it costs.' },+ match: named('CredentialError'),+ map: (e: Error & { code: string; problem: string; cause_text: string; fix: string; doc_url: string }) => ({+ error: e.code, code: e.code, message: e.problem, why: e.cause_text, suggestion: e.fix, docs: e.doc_url,}),},+ {+ // embed preflight: no usable embedding credentials (userMessage is the paste-ready diagnosis).+ match: named('EmbeddingCredentialError'),+ map: (e: Error & { userMessage?: string }) => {+ const [first, ...rest] = (e.userMessage ?? e.message).split('\n').filter(l => l.trim());+ return { error: 'unavailable', code: 'unavailable', reason: 'embedding_credentials', message: first ?? e.message,+ suggestion: rest.join(' ').trim() || 'Configure an embedding provider key, then retry.' };+ },+ },+ {+ match: named('EmbeddingDimMismatchError'),+ map: (e: Error & { recipeMessage?: string }) => {+ const [first, ...rest] = (e.recipeMessage ?? e.message).split('\n').filter(l => l.trim());+ return { error: 'embedding_width_mismatch', code: 'embedding_width_mismatch', message: first ?? e.message,+ suggestion: rest.join(' ').trim() || 'Run `gbrain doctor --json` to see the brain\'s vector width.' };+ },+ },// ── generic rows: the DB classifier runs before these ──{match: e => named('AIConfigError')(e) || named('AITransientError')(e),diff --cc src/core/cli-flag-registry.generated.tsindex 19eedf7419,e13fe981c1..1d2b76c2c1--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@@ -17,9 -17,9 +17,9 @@@ export const CLI_FLAG_REGISTRY: Record<'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],- 'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--uninstall', '--yes'],- 'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--probe', '--require-db', '--skip-verify', '--source', '--yes'],++ 'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--yes'],'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],- 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--yes'],+ 'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],diff --cc src/core/error-registry.tsindex 21c0489f68,8b2e55ae23..3b6a5796ba--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@@ -211,10 -208,9 +217,10 @@@ 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." },+ revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },revision_required: { class: 'caller', summary: "Review the current policy and supply its expected_policy_epoch before changing disclosure." },revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },@@@ -295,7 -293,15 +304,17 @@@ export interface NoticeEntryexport const NOTICE_CODES = {backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },+ first_run_decisions: { kind: 'ask', summary: 'init finished; the first-run decisions (search mode, harness wiring, …) carry defaults the user may change.' },+ migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },+ no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },+ listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },+ degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence.' },+ source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },+ degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },+ synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },+ think_not_saved: { kind: 'info', summary: 'think save/take persist only for the local CLI, so this answer was not saved.' },+ onboard_opportunities: { kind: 'coaching', summary: 'Onboarding checks found work that would improve this brain (gbrain onboard --check lists it).' },+ features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },+ post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },} as const satisfies Record<string, NoticeEntry>;diff --cc test/cli-contract.serial.test.tsindex 90d5970967,0000000000..9c22ae3e9amode 100644,000000..100644--- a/test/cli-contract.serial.test.ts+++ b/test/cli-contract.serial.test.ts@@@ -1,173 -1,0 +1,185 @@@+/**+ * Agent contract v1 D5: the CLI contract over src/cli/command-table.ts.+ *+ * Part 1 (help): `gbrain <command> --help` for every CLI-only command, with+ * no brain configured, must exit 0, print real (non-stub) help, list only+ * curated flags when the command has a curated help module, and mention+ * `--yes` when the command parses it. Commands that do not meet the contract+ * yet are listed in a shrink-only baseline+ * (test/fixtures/cli-contract/help-baseline.json): a NEW violation fails, and+ * a baseline entry that now passes must be removed+ * (`GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/cli-contract.serial.test.ts`+ * rewrites it, refusing growth).+ *+ * Part 2 (json): every record that declares `json` has one succeeding and one+ * failing invocation here; the success prints the declared shape (one JSON+ * document, or NDJSON lines) and the failure prints a v1 envelope with `code`+ * and `suggestion` (or, exit 3, the confirmation_required payload).+ * Consent-gated exits (3) per command are pinned by+ * test/consent-table.serial.test.ts (C9).+ *+ * Serial: spawns the CLI and writes temporary GBRAIN_HOMEs.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { CLI_COMMANDS } from '../src/cli/command-table.ts';+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';+import { runCli, runCliBatch, type CliResult } from './helpers/cli-spawn.ts';++const BASELINE = join(import.meta.dir, 'fixtures', 'cli-contract', 'help-baseline.json');+const STUB = 'run gbrain --help for the full command list';++const emptyHome = mkdtempSync(join(tmpdir(), 'gbrain-cli-contract-empty-'));+const brainHome = mkdtempSync(join(tmpdir(), 'gbrain-cli-contract-brain-'));+afterAll(() => {+ rmSync(emptyHome, { recursive: true, force: true });+ rmSync(brainHome, { recursive: true, force: true });+});+++/**++ * The command parses `--yes`: the generated acceptance registry lists it AND++ * the command's own module reads the literal (the registry over-approximates++ * from every module a command imports).++ */++function parsesYes(name: string): boolean {++ if (!(CLI_FLAG_REGISTRY[name] ?? []).includes('--yes')) return false;++ const src = join(import.meta.dir, '..', 'src');++ const files = [join(src, 'cli', 'commands', `${name}.ts`), join(src, 'commands', `${name}.ts`), join(src, 'commands', name, 'index.ts')];++ return files.some(f => existsSync(f) && /['"]--yes['"]/.test(readFileSync(f, 'utf8')));++}+++/** The contract violations of one command's --help output. */+async function helpViolations(name: string, r: CliResult): Promise<string[]> {+ const out = `${r.stdout}\n${r.stderr}`;+ const v: string[] = [];+ if (r.exitCode !== 0) v.push('exit');+ if (out.includes(STUB) || out.split('\n').filter(l => l.trim()).length < 3) v.push('stub');+ const record = CLI_COMMANDS.find(c => c.name === name)!;+ if (record.help) {+ const curated = new Set(['--help', ...(await record.help()).help.flags.map(f => f.name)]);+ const listed = [...out.matchAll(/(?<![\w-])--[a-z][a-z0-9-]*/g)].map(m => m[0]);+ if (listed.some(f => !curated.has(f))) v.push('uncurated_flag');+ }- if ((CLI_FLAG_REGISTRY[name] ?? []).includes('--yes') && !out.includes('--yes')) v.push('missing_yes');++ if (parsesYes(name) && !out.includes('--yes')) v.push('missing_yes');+ return v.map(x => `${name}:${x}`);+}++describe('D5 help contract (shrink-only baseline)', () => {+ test('every CLI-only command: --help exits 0, is not a stub, lists curated flags, shows --yes where parsed', async () => {+ const names = CLI_COMMANDS.map(c => c.name);+ const results = await runCliBatch(names.map(n => [n, '--help']), { home: emptyHome, cwd: emptyHome, width: 3, timeoutMs: 60_000 });+ const violations = (await Promise.all(names.map((n, i) => helpViolations(n, results[i])))).flat().sort();+ const baseline: string[] = existsSync(BASELINE) ? JSON.parse(readFileSync(BASELINE, 'utf8')) : [];+ const grown = violations.filter(v => !baseline.includes(v));+ if (process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1' && (grown.length === 0 || !existsSync(BASELINE))) {+ mkdirSync(join(import.meta.dir, 'fixtures', 'cli-contract'), { recursive: true });+ writeFileSync(BASELINE, `${JSON.stringify(violations, null, 2)}\n`);+ return;+ }+ expect(grown, 'new help-contract violations (fix the help; the baseline only shrinks)').toEqual([]);+ expect(baseline.filter(b => !violations.includes(b)), 'fixed: remove these from test/fixtures/cli-contract/help-baseline.json').toEqual([]);+ }, 600_000);+});++interface JsonRow {+ ok: string[];+ fail: string[];+ /** The failing invocation runs against the keyless brain (default: an empty home). */+ failOnBrain?: boolean;+ /** The succeeding invocation runs against an empty home (default: the keyless brain). */+ okOnEmpty?: boolean;+ /** The succeeding invocation needs Postgres: the E2E file (test/e2e/…) that asserts it instead. */+ okE2E?: string;+ /** NDJSON only: zero lines is a valid success (e.g. an export of an empty table). */+ okMayBeEmpty?: true;+}++const EVAL_FIXTURES = join(import.meta.dir, 'fixtures', 'eval-baselines');+const QRELS = join(EVAL_FIXTURES, 'qrels-search.json');+const CAPTURED = join(EVAL_FIXTURES, 'captured-sample.ndjson');++/** One row per command-table record that declares `json`; a new declaration needs a row. */+const JSON_ROWS: Record<string, JsonRow> = {+ errors: { ok: ['errors', 'unknown_flag', '--json'], fail: ['errors', 'definitely_not_a_code', '--json'], okOnEmpty: true },+ init: { ok: ['init', '--pglite', '--no-embedding', '--json'], fail: ['init', '--mcp-only', '--json', '--mcp-url', 'http://127.0.0.1:1/mcp'], okOnEmpty: true },+ doctor: { ok: ['doctor', '--json', '--fast'], fail: ['doctor', '--json'] },+ sync: { ok: ['sync', '--source', 'notes', '--no-pull', '--json'], fail: ['sync', '--source', 'notes', '--json'], failOnBrain: true },+ embed: { ok: ['embed', '--stale', '--json'], fail: ['embed', '--all', '--json'], failOnBrain: true },+ 'db-repair': { ok: ['db-repair', '--json'], fail: ['db-repair', '--json'], failOnBrain: true, okE2E: 'test/e2e/cli-json-commands-postgres.test.ts' },+ dream: { ok: ['dream', '--json', '--phase', 'lint'], fail: ['dream', '--json', '--phase', 'garbage'] },+ 'post-upgrade': { ok: ['post-upgrade', '--json', '--no-autopilot-install'], fail: ['post-upgrade', '--bogus', '--json'], okOnEmpty: true },+ bench: { ok: ['bench', 'publish', '--from', CAPTURED, '--to', 'sample.baseline.ndjson', '--json'], fail: ['bench', 'publish', '--json'], okOnEmpty: true },+ 'eval export': { ok: ['eval', 'export', '--json'], fail: ['eval', 'export', '--json', '--since', 'bogus'], failOnBrain: true, okMayBeEmpty: true },+ 'eval replay': { ok: ['eval', 'replay', '--against', CAPTURED, '--json'], fail: ['eval', 'replay', '--json'], failOnBrain: true },+ 'eval gate': {+ ok: ['eval', 'gate', '--qrels', QRELS, '--embedder', 'deterministic', '--threshold-recall-at-k', '0', '--threshold-first-relevant-hit', '0', '--threshold-expected-top1', '0', '--json'],+ fail: ['eval', 'gate', '--qrels', QRELS, '--embedder', 'deterministic', '--json'], failOnBrain: true,+ },+ 'apply-migrations': { ok: ['apply-migrations', '--dry-run', '--json'], fail: ['apply-migrations', '--json', '--migration', '9.9.9'], failOnBrain: true },+};++function parsedShape(mode: 'document' | 'ndjson', stdout: string): unknown[] {+ if (mode === 'document') return [JSON.parse(stdout)];+ return stdout.split('\n').filter(l => l.trim() !== '').map(l => JSON.parse(l));+}++/** json-declared records, plus `<command> <sub>` for each per-subcommand declaration. */+const JSON_DECLARED: ReadonlyArray<{ name: string; mode: 'document' | 'ndjson' }> = CLI_COMMANDS.flatMap(c => c.json+ ? [{ name: c.name, mode: c.json }]+ : Object.entries(c.jsonSubcommands ?? {}).map(([sub, mode]) => ({ name: `${c.name} ${sub}`, mode })));++function assertFailureShape(name: string, mode: 'document' | 'ndjson', r: CliResult): void {+ expect(r.exitCode, `${name}: failing invocation exits non-zero`).not.toBe(0);+ const docs = parsedShape(mode, r.stdout) as Array<Record<string, unknown>>;+ const last = docs[docs.length - 1];+ if (r.exitCode === 3) {+ expect(last, `${name}: exit 3 carries the consent payload`).toMatchObject({ code: 'confirmation_required' });+ return;+ }+ expect(typeof last.code, `${name}: failure document has code`).toBe('string');+ expect(typeof last.suggestion, `${name}: failure document has suggestion`).toBe('string');+}++describe('D5 json contract: one success and one failure per json-declared command', () => {+ beforeAll(async () => {+ const init = await runCli(['init', '--pglite', '--no-embedding', '--json'], { home: brainHome, cwd: brainHome, timeoutMs: 120_000 });+ if (init.exitCode !== 0) throw new Error(`fixture init failed: ${init.stderr}`);+ const repo = join(brainHome, 'notes');+ mkdirSync(repo);+ writeFileSync(join(repo, 'example.md'), '---\ntitle: Example\n---\nHello world\n');+ const git = (args: string[]) => Bun.spawnSync(['git', '-c', '[email protected]', '-c', 'user.name=fixture', ...args], { cwd: repo });+ git(['init', '-q']); git(['add', '.']); git(['commit', '-qm', 'init']);+ const add = await runCli(['sources', 'add', 'notes', '--path', repo], { home: brainHome, cwd: brainHome, timeoutMs: 60_000 });+ if (add.exitCode !== 0) throw new Error(`fixture sources add failed: ${add.stderr}`);+ }, 240_000);++ test('every json-declared record has a contract row', () => {+ const declared = JSON_DECLARED.map(c => c.name).sort();+ expect(declared).toEqual(Object.keys(JSON_ROWS).sort());+ });++ for (const record of JSON_DECLARED) {+ test(`${record.name} --json: success shape and failure envelope`, async () => {+ const row = JSON_ROWS[record.name];+ if (!row) throw new Error(`no D5 row for json-declared command ${record.name}`);+ const fresh = mkdtempSync(join(tmpdir(), 'gbrain-cli-contract-ok-'));+ try {+ const okHome = row.okOnEmpty ? fresh : brainHome;+ if (row.okE2E) {+ expect(existsSync(join(import.meta.dir, '..', row.okE2E)), `${record.name}: ${row.okE2E} covers the success shape`).toBe(true);+ } else {+ const ok = await runCli(row.ok, { home: okHome, cwd: okHome, timeoutMs: 120_000 });+ expect(ok.exitCode, `${record.name} ok: ${ok.stderr.slice(-800)}`).toBe(0);+ const lines = parsedShape(record.mode, ok.stdout).length;+ if (!row.okMayBeEmpty) expect(lines).toBeGreaterThan(0);+ }+ const failHome = row.failOnBrain ? brainHome : emptyHome;+ assertFailureShape(record.name, record.mode, await runCli(row.fail, { home: failHome, cwd: failHome, timeoutMs: 120_000 }));+ } finally {+ rmSync(fresh, { recursive: true, force: true });+ }+ }, 300_000);+ }+});diff --cc test/cli-json-guard.serial.test.tsindex f06885cde0,be70b9c31e..d400b57424--- a/test/cli-json-guard.serial.test.ts+++ b/test/cli-json-guard.serial.test.ts@@@ -99,119 -99,3 +99,121 @@@ g.flushThenExit(0);`)expect(r.out).toBe('plain\n');}, 20_000);});++// ── D2: command migrations (real CLI subprocesses, isolated GBRAIN_HOME) ──+import { runCli } from './helpers/cli-spawn.ts';+import { mkdirSync } from 'node:fs';++function onlyDocument(stdout: string): Record<string, unknown> {+ const doc = JSON.parse(stdout);+ expect(typeof doc).toBe('object');+ return doc;+}++describe('D2 command migrations: init', () => {+ test('init --pglite --no-embedding --json: one document carrying the first-run decision bundle', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-json-init-'));+ try {+ const r = await runCli(['init', '--pglite', '--no-embedding', '--json'], { home, cwd: home, timeoutMs: 120_000 });+ expect(r.exitCode).toBe(0);+ const doc = onlyDocument(r.stdout);+ expect(doc).toMatchObject({ status: 'success', engine: 'pglite', contract_version: 1 });+ const bundle = (doc.notices as Array<Record<string, any>>).find(n => n.code === 'first_run_decisions')!;+ expect(bundle).toMatchObject({ kind: 'ask', contract_version: 1 });+ expect(bundle.user_message).toContain("Reply 'defaults'");+ const searchMode = bundle.decisions.find((d: { id: string }) => d.id === 'search_mode');+ expect(searchMode.options.map((o: { id: string }) => o.id)).toEqual(['conservative', 'balanced', 'tokenmax']);+ expect(searchMode.options[0].argv).toEqual(['gbrain', 'config', 'set', 'search.mode', 'conservative']);+ // Progress lines and the picker's event went to stderr.+ expect(r.stderr).toContain('Setting up local brain with PGLite');+ expect(r.stdout).not.toContain('search_mode_picker');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ }, 150_000);++ test('init --json usage failure: legacy one-line keys plus the v1 envelope, exit 2', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-json-init-'));+ try {+ const r = await runCli(['init', '--mcp-only', '--json', '--mcp-url', 'http://127.0.0.1:1/mcp', '--oauth-client-id', 'cid', '--oauth-client-secret', 'cs'], { home, cwd: home });+ expect(r.exitCode).toBe(2);+ expect(r.stdout.trim().split('\n')).toHaveLength(1);+ expect(onlyDocument(r.stdout)).toMatchObject({ status: 'error', reason: 'missing_issuer_url', error: 'invalid_params', code: 'invalid_params', contract_version: 1 });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('init --json on a malformed config: config_error document, config untouched', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-json-init-'));+ try {+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), '{broken');+ const r = await runCli(['init', '--pglite', '--json'], { home, cwd: home });+ expect(r.exitCode).toBe(1);+ const doc = onlyDocument(r.stdout);+ expect(doc).toMatchObject({ status: 'error', reason: 'invalid_existing_config', code: 'config_error' });+ expect(typeof doc.suggestion).toBe('string');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});++describe('D2 command migrations: doctor, sync, embed on a keyless brain', () => {+ let home = '';+ const cli = (args: string[]) => runCli(args, { home, cwd: home, timeoutMs: 120_000 });++ test('setup: keyless PGLite brain + a git-backed source', async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-json-cmds-'));+ expect((await cli(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ const repo = join(home, 'notes');+ mkdirSync(repo);+ writeFileSync(join(repo, 'example.md'), '---\ntitle: Example\n---\nHello world\n');+ const git = (args: string[]) => Bun.spawnSync(['git', '-c', '[email protected]', '-c', 'user.name=fixture', ...args], { cwd: repo });+ git(['init', '-q']); git(['add', '.']); git(['commit', '-qm', 'init']);+ expect((await cli(['sources', 'add', 'notes', '--path', repo])).exitCode).toBe(0);+ }, 150_000);++ test('doctor --json --fast: one report document', async () => {+ const r = await cli(['doctor', '--json', '--fast']);+ expect(onlyDocument(r.stdout)).toMatchObject({ schema_version: 2 });+ expect(typeof onlyDocument(r.stdout).health_score).toBe('number');+ }, 120_000);++ test('sync --json success: one envelope; a failing sync: one v1 error document', async () => {+ const ok = await cli(['sync', '--source', 'notes', '--no-pull', '--json']);+ expect(ok.exitCode).toBe(0);+ expect(onlyDocument(ok.stdout)).toMatchObject({ schema_version: 1, source_id: 'notes', added: 1 });+ const bad = await cli(['sync', '--source', 'notes', '--json']);+ expect(bad.exitCode).toBe(1);+ const doc = onlyDocument(bad.stdout);+ expect(typeof doc.code).toBe('string');+ expect(typeof doc.suggestion).toBe('string');+ expect(doc.contract_version).toBe(1);+ }, 120_000);++ test('embed --json: keyless --stale is a result document (exit 0); --all is embedding_disabled (exit 1)', async () => {+ const stale = await cli(['embed', '--stale', '--json']);+ expect(stale.exitCode).toBe(0);+ expect(onlyDocument(stale.stdout)).toMatchObject({ failures: 0 });+ const all = await cli(['embed', '--all', '--json']);+ expect(all.exitCode).toBe(1);- expect(onlyDocument(all.stdout)).toMatchObject({ error: 'embedding_disabled', code: 'embedding_disabled', fix: { argv: ['gbrain', 'embeddings', 'enable', '--help'] } });++ const doc = onlyDocument(all.stdout) as { code?: string; reason?: string; fix?: { argv?: string[] } };++ expect(doc).toMatchObject({ code: 'embedding_disabled', reason: 'disabled_by_choice' });++ expect(doc.fix?.argv?.[0]).toBe('gbrain'); // the readiness enablement command (A7)+ }, 120_000);++ test('doctor --json with no brain: the no_brain envelope', async () => {+ const empty = mkdtempSync(join(tmpdir(), 'gbrain-json-nobrain-'));+ try {+ const r = await runCli(['doctor', '--json'], { home: empty, cwd: empty });+ expect(r.exitCode).toBe(1);+ expect(onlyDocument(r.stdout)).toMatchObject({ code: 'no_brain', fix: { argv: ['gbrain', 'init', '--pglite', '--no-embedding'] } });+ } finally {+ rmSync(empty, { recursive: true, force: true });+ }+ });++ test('teardown', () => { rmSync(home, { recursive: true, force: true }); });+});diff --cc test/e2e/thin-client.test.tsindex bca1b217d5,67b4addaac..2d5130bd1e--- a/test/e2e/thin-client.test.ts+++ b/test/e2e/thin-client.test.ts@@@ -420,13 -420,12 +420,12 @@@ describeWhen('thin-client end-to-end (rGBRAIN_REMOTE_CLIENT_SECRET: 'gbrain_cs_definitely_not_the_real_secret',});expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(1);- // No fabricated results — stdout stays empty on the error path.- expect(r.stdout.trim()).toBe('');+ // No fabricated results: under --json stdout carries only the v1 error envelope (agent contract D1).+ expect(JSON.parse(r.stdout)).toMatchObject({ code: expect.any(String), suggestion: expect.any(String), contract_version: 1 });- // Canonical RemoteMcpError surface. mcp-client maps the non-401 /token- // HTTP failure to reason 'discovery' today ("OAuth discovery failed at- // <issuer>."); allow the 'auth' spelling too so a future 401- // reclassification on the host doesn't false-fail the guard.- expect(r.stderr).toMatch(/OAuth (discovery|auth) failed/);+ // Canonical RemoteMcpError surface: reason 'auth' ("OAuth auth failed.");+ // any other /token status renders as reason 'token' ("OAuth /token+ // failed: ..."), never as a discovery failure.+ expect(r.stderr).toMatch(/OAuth (auth|\/token) failed/);});test('stopped host: routed verbs fail fast with the canonical unreachable error, not a hang', async () => {diff --cc test/fixtures/cli-contract/help-baseline.jsonindex 8553f73a24,0000000000..3d03b4bfbbmode 100644,000000..100644--- a/test/fixtures/cli-contract/help-baseline.json+++ b/test/fixtures/cli-contract/help-baseline.json@@@ -1,63 -1,0 +1,35 @@@+[- "agent:missing_yes",- "auth:missing_yes",- "autopilot:missing_yes",+ "bench:stub",- "calibration:missing_yes",+ "calibration:stub",+ "call:stub",- "capture:missing_yes",+ "check-backlinks:stub",- "check-update:missing_yes",- "claw-test:missing_yes",- "code-callees:missing_yes",+ "code-callees:stub",- "code-callers:missing_yes",+ "code-callers:stub",- "code-def:missing_yes",+ "code-def:stub",- "code-refs:missing_yes",+ "code-refs:stub",+ "config:exit",+ "config:missing_yes",- "connectors:missing_yes",- "dream:missing_yes",+ "embed:exit",- "embed:missing_yes",- "embeddings:missing_yes",- "engine:missing_yes",- "eval:missing_yes",+ "files:missing_yes",+ "files:stub",+ "forget:stub",- "init:missing_yes",+ "lint:stub",- "maintain:missing_yes",+ "notability-eval:stub",- "post-upgrade:missing_yes",- "protocol:missing_yes",+ "publish:stub",+ "quarantine:stub",- "recall:missing_yes",+ "recall:stub",+ "reconcile-links:stub",+ "reindex-code:missing_yes",+ "reindex-code:stub",+ "reindex-frontmatter:missing_yes",+ "reindex-frontmatter:stub",+ "reindex-search-vector:missing_yes",+ "reindex-search-vector:stub",+ "repair-jsonb:stub",+ "report:stub",- "repos:missing_yes",+ "repos:stub",- "self-upgrade:missing_yes",- "serve:missing_yes",- "skillpack-check:missing_yes",+ "skillpack:missing_yes",+ "smoke-test:stub",- "status:missing_yes",+ "takes:missing_yes",- "upgrade:missing_yes",- "whoknows:missing_yes"++ "upgrade:missing_yes"+]diff --cc test/fixtures/goldens/cli/engine-free-db-down.jsonindex 860825eefe,24f12b8723..4ed617ef43--- a/test/fixtures/goldens/cli/engine-free-db-down.json+++ b/test/fixtures/goldens/cli/engine-free-db-down.json@@@ -143,9 -143,34 +143,9 @@@"stderr": [],"stderrFirstLine": null,"stdout": [- "{\"schema_version\":1,\"brain_id\":\"host\",\"reason\":\"conn_refused\",\"tier\":\"auto\",\"marker\":\"GBRAIN_DB_ACCESS conn_refused\",\"diagnosis\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"plan\":[\"bounded reconnect; if the server is down, start it and re-run\"],\"applied\":[],\"fixed\":false,\"remaining\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"error\":\"database_error\",\"code\":\"database_error\",\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"suggestion\":\"Apply the plan: gbrain db-repair --yes\",\"docs\":\"https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#database_error\",\"why\":\"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.\",\"fix\":{\"argv\":[\"gbrain\",\"db-repair\",\"--yes\"],\"command\":\"gbrain db-repair --yes\",\"consent\":[],\"actor\":\"agent\",\"next\":\"run\",\"why\":\"Applies the auto tier the plan names (bounded retries, pending migrations, CREATE EXTENSION vector, starting gbrain's own docker container).\",\"requires_exclusive\":false},\"docs_cmd\":[\"gbrain\",\"errors\",\"database_error\"],\"class\":\"server\",\"retryable\":false,\"contract_version\":1}"- "{",- " \"schema_version\": 1,",- " \"brain_id\": \"host\",",- " \"reason\": \"conn_refused\",",- " \"tier\": \"auto\",",- " \"marker\": \"GBRAIN_DB_ACCESS conn_refused\",",- " \"diagnosis\": {",- " \"reason\": \"conn_refused\",",- " \"transient\": true,",- " \"message\": \"connect ECONNREFUSED <REDACTED:ipv4>:1\",",- " \"remediation\": \"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",",- " \"brainId\": \"host\"",- " },",- " \"plan\": [",- " \"bounded reconnect; if the server is down, start it and re-run\"",- " ],",- " \"applied\": [],",- " \"fixed\": false,",- " \"remaining\": {",- " \"reason\": \"conn_refused\",",- " \"transient\": true,",- " \"message\": \"connect ECONNREFUSED <REDACTED:ipv4>:1\",",- " \"remediation\": \"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",",- " \"brainId\": \"host\"",- " }",- "}"++ "{\"schema_version\":1,\"brain_id\":\"host\",\"reason\":\"conn_refused\",\"tier\":\"auto\",\"marker\":\"GBRAIN_DB_ACCESS conn_refused\",\"diagnosis\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",\"brainId\":\"host\"},\"plan\":[\"bounded reconnect; if the server is down, start it and re-run\"],\"applied\":[],\"fixed\":false,\"remaining\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",\"brainId\":\"host\"},\"error\":\"database_error\",\"code\":\"database_error\",\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"suggestion\":\"Apply the plan: gbrain db-repair --yes\",\"docs\":\"https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#database_error\",\"why\":\"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",\"fix\":{\"argv\":[\"gbrain\",\"db-repair\",\"--yes\"],\"command\":\"gbrain db-repair --yes\",\"consent\":[],\"actor\":\"agent\",\"next\":\"run\",\"why\":\"Applies the auto tier the plan names (bounded retries, pending migrations, CREATE EXTENSION vector, starting gbrain's own docker container).\",\"requires_exclusive\":false},\"docs_cmd\":[\"gbrain\",\"errors\",\"database_error\"],\"class\":\"server\",\"retryable\":false,\"contract_version\":1}"],- "stdoutFirstLine": "{\"schema_version\":1,\"brain_id\":\"host\",\"reason\":\"conn_refused\",\"tier\":\"auto\",\"marker\":\"GBRAIN_DB_ACCESS conn_refused\",\"diagnosis\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"plan\":[\"bounded reconnect; if the server is down, start it and re-run\"],\"applied\":[],\"fixed\":false,\"remaining\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"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.\",\"brainId\":\"host\"},\"error\":\"database_error\",\"code\":\"database_error\",\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"suggestion\":\"Apply the plan: gbrain db-repair --yes\",\"docs\":\"https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#database_error\",\"why\":\"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.\",\"fix\":{\"argv\":[\"gbrain\",\"db-repair\",\"--yes\"],\"command\":\"gbrain db-repair --yes\",\"consent\":[],\"actor\":\"agent\",\"next\":\"run\",\"why\":\"Applies the auto tier the plan names (bounded retries, pending migrations, CREATE EXTENSION vector, starting gbrain's own docker container).\",\"requires_exclusive\":false},\"docs_cmd\":[\"gbrain\",\"errors\",\"database_error\"],\"class\":\"server\",\"retryable\":false,\"contract_version\":1}",- "stdoutFirstLine": "{",++ "stdoutFirstLine": "{\"schema_version\":1,\"brain_id\":\"host\",\"reason\":\"conn_refused\",\"tier\":\"auto\",\"marker\":\"GBRAIN_DB_ACCESS conn_refused\",\"diagnosis\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",\"brainId\":\"host\"},\"plan\":[\"bounded reconnect; if the server is down, start it and re-run\"],\"applied\":[],\"fixed\":false,\"remaining\":{\"reason\":\"conn_refused\",\"transient\":true,\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"remediation\":\"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",\"brainId\":\"host\"},\"error\":\"database_error\",\"code\":\"database_error\",\"message\":\"connect ECONNREFUSED <REDACTED:ipv4>:1\",\"suggestion\":\"Apply the plan: gbrain db-repair --yes\",\"docs\":\"https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#database_error\",\"why\":\"Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port.\",\"fix\":{\"argv\":[\"gbrain\",\"db-repair\",\"--yes\"],\"command\":\"gbrain db-repair --yes\",\"consent\":[],\"actor\":\"agent\",\"next\":\"run\",\"why\":\"Applies the auto tier the plan names (bounded retries, pending migrations, CREATE EXTENSION vector, starting gbrain's own docker container).\",\"requires_exclusive\":false},\"docs_cmd\":[\"gbrain\",\"errors\",\"database_error\"],\"class\":\"server\",\"retryable\":false,\"contract_version\":1}","url": "config"},{@@@ -337,8 -362,8 +337,8 @@@"exitCode": 1,"stderr": ["GBRAIN_DB_ACCESS conn_refused",- "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"- "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check the database URL; `gbrain engine status --probe` names where it comes from (environment variable or the config file under GBRAIN_HOME)",++ "Error [database_error]: Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check the database URL; `gbrain engine status --probe` names where it comes from (environment variable or the config file under GBRAIN_HOME)",+ "Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port. Run: gbrain db-repair"],"stderrFirstLine": "GBRAIN_DB_ACCESS conn_refused","stdout": [],@@@ -350,8 -375,8 +350,8 @@@"exitCode": 1,"stderr": ["GBRAIN_DB_ACCESS conn_refused",- "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"- "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check the database URL; `gbrain engine status --probe` names where it comes from (environment variable or the config file under GBRAIN_HOME)",++ "Error [database_error]: Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check the database URL; `gbrain engine status --probe` names where it comes from (environment variable or the config file under GBRAIN_HOME)",+ "Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port. Run: gbrain db-repair"],"stderrFirstLine": "GBRAIN_DB_ACCESS conn_refused","stdout": [],@@@ -363,8 -388,8 +363,8 @@@"exitCode": 1,"stderr": ["GBRAIN_DB_ACCESS conn_refused",- "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"- "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check the database URL; `gbrain engine status --probe` names where it comes from (environment variable or the config file under GBRAIN_HOME)",++ "Error [database_error]: Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check the database URL; `gbrain engine status --probe` names where it comes from (environment variable or the config file under GBRAIN_HOME)",+ "Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port. Run: gbrain db-repair"],"stderrFirstLine": "GBRAIN_DB_ACCESS conn_refused","stdout": [],diff --cc test/fixtures/goldens/exports/types.jsonindex 949828b29a,6d5d66e64a..8648aca87b--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@@ -5454,7 -5455,7 +5455,7 @@@{"kind": "class","members": [- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_payload_expired\" | \"fetch_failed\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_pricing\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_in_progress\" | \"target_escape\" | \"topology_change_required\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_payload_expired\" | \"fetch_failed\" | \"full_resync_required\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_pricing\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"overlapping_path\" | \"parse_error\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"request_already_submitted\" | \"requirements_changed\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",++ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_payload_expired\" | \"fetch_failed\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_pricing\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",