Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/master (v0.60.44.0 Cat 40 cost wave, v0.60.41.0) into agent-operator-wave; restamp v0.60.45.0

garrytan3a00f2196d90
diff --cc .claude-plugin/plugin.json
index 91614bc527,87bd401c6e..a793d22394
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --cc .codex-plugin/plugin.json
index 6b95c16b16,b1da40391c..5a1dcb8bc9
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --cc BOOTSTRAP_FOR_AGENTS.md
index 7d572e2237,6310a01c76..034cd22b8b
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-runbook-stamp: 0.60.42.0 -->
-<!-- gbrain-runbook-stamp: 0.60.44.0 -->
++<!-- gbrain-runbook-stamp: 0.60.45.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --cc CHANGELOG.md
index 111092ff53,93a13f3602..069e6cc7b8
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,177 -10,68 +10,240 @@@ credits are retained; no result has bee
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
- ## [0.60.42.0] - 2026-10-04
++## [0.60.45.0] - 2026-10-04
+
+**When gbrain hits a problem, it now tells the AI agent running it exactly what to do next, who has to do it, and whether to stop and ask you first.**
+
+Most people don't type gbrain commands. Claude Code, Codex, OpenClaw or another agent runs them for you. Until now a lot of gbrain still talked as if a person sat at the terminal. Errors said what broke but not how to fix it. Paid or risky commands told the agent to "re-run with --yes", which an agent will happily do without asking you. Some commands hung forever waiting for typing that never came. Advice about a degraded search went to a log the model never reads, so the agent told you "you have no notes on that" when the search had simply run in keyword-only mode.
+
+This release gives every error, refusal and recommendation the same shape: a stable code, the reason, the exact next command, who runs it (the agent, you, or the brain's host), and whether the agent must ask you first. Anything that spends money, deletes data, stores a credential, sends your notes off the machine or installs a service now stops and hands the agent the words to relay to you. Nothing hangs on a silent stdin. A new protocol page, [AGENT_OPERATOR_v1](docs/protocol/AGENT_OPERATOR_v1.md), is the one place an agent learns the rules.
+
+| Situation | What the agent got before | What it gets now |
+| --- | --- | --- |
+| A tool call fails over MCP | a bare `internal_error` on most tools | `code`, the reason and a `fix` it can run or relay |
+| Paid remediation without a terminal | it ran, no cap, no question | it stops (exit 3) with the cost and a sentence to ask you |
+| A keyword-only search finds nothing | `[]`, so "you have no notes" | `[]` plus a notice block saying search was degraded |
+| A second `gbrain serve` on the same brain | exit before the handshake, the harness shows a dead server | a working server with one `gbrain_status` tool that explains the fix |
+| `gbrain init` | a scattered set of banners and a made-up "dark mode" memory | one decision bundle: search mode, writeback, harness wiring, skills; reply "defaults" |
+
+Scripts that parse exit codes or `--json` output should read the [behavior changes table](#behavior-changes-for-scripts-and-agents) below before upgrading. The changes are additive where they could be: existing `error` values never change, and the canonical value rides a new `code` field.
+
- ## To take advantage of v0.60.42.0
++## To take advantage of v0.60.45.0
+
+`gbrain upgrade` should do this automatically. There is no schema migration in this release.
+
+1. **Run the orchestrator if the upgrade did not:**
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install
+ ```
+2. **Point your agent at the protocol.** Agents that read `AGENTS.md` pick it up on their own. Others: tell your agent to read `docs/protocol/AGENT_OPERATOR_v1.md` (or run `gbrain errors --changed` for the renamed codes).
+3. **Check scripts and cron jobs** against the behavior changes table below, especially anything that passes `--yes` unattended or treats exit 2 or exit 3 as special.
+4. **Optional: let gbrain stop asking for small paid runs.** Only you can set this, on the brain host:
+ ```bash
+ gbrain config set consent.preapprove.paid.max_usd_per_run 1
+ ```
+5. **Restart every `gbrain serve`** so MCP clients get the new tool catalog and instructions. If a tool seems missing afterwards, restart the MCP server in the harness.
+6. **Verify:**
+ ```bash
+ gbrain doctor --json # agent_contract, harness_wiring, keyless rows report info, not warn
+ gbrain doctor --only harness_wiring --json # read-only smoke: the registered server answers a recall
+ ```
+7. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor` and `~/.gbrain/upgrade-errors.jsonl` if it exists.
+
+### Behavior changes for scripts and agents
+
+| Area | Before | Now | What to change |
+| --- | --- | --- | --- |
+| `gbrain embed --stale` time-budget stop | exit 3 | exit 11 (since v0.60.37.0) | treat 11 as "run `resume_command`"; 3 now only means `confirmation_required` |
+| `gbrain dream --drain` with backlog left | exit 3 | exit 11, `--json` carries `resume_command` | treat 11 as a resumable stop |
+| Other exit-3 sites (`agent run --follow` timeout, `providers test`, `sources harden`, `sources pull`, `sources remove/archive default`, `extract-conversation-facts`) | exit 3 | 124, 1 or 2 ([exit codes](docs/guides/exit-codes.md#changed-in-this-release)) | branch on the new codes |
+| `migrate embeddings`, `reindex-search-vector`, `reindex-code`, `dream retriage`, `sources connect`, `bootstrap harness` without authorization | exit 2 ("pass `--yes`") | exit 3 with the consent payload | stop, relay `user_message`, run `fix.command` only after the user agrees |
+| `pglite-repair`, `reinit-pglite`, `enrich`, `connect --install` without authorization | exit 1 | exit 3 with the consent payload | same |
+| `book-mirror` paid fan-out without authorization | exit 0 ("cancelled", nothing ran) | exit 3 with the consent payload | same |
+| `gbrain doctor --remediate` without a terminal | ran paid and mutating work with no `--yes` and no cap | refuses with exit 3; nothing runs. Repairs (`--include-repairs`) need `--yes --expect <plan_hash>` from `--remediation-plan --json` | relay `user_message`; pass `--yes` (derived cap) or `--max-usd <n>` only after the user agrees |
+| Paid, destructive, credential, egress and install commands without a terminal | "re-run with `--yes`" text | exit 3 with `effects`, `user_message` and an `ask_user` fix | stop and ask; never add `--yes` on your own |
+| `--yes` on paid work without `--max-usd` | no cap unless the command had its own default | runs under a derived cap (estimate x1.5, floor $0.25; the $5 default with no estimate), printed first; exhaustion exits 1 with a resume command | pass `--max-usd <n>` for a bigger job the user approved |
+| Unpriced model (no per-token rate known) | refused whenever a cap was set | warns and runs under a derived or default cap; under a user cap refuses with a fix to look up the rate and run `gbrain pricing set` | register the rate, then retry |
+| `gbrain reindex-frontmatter --json` | `--json` skipped the confirmation | `--json` never implies consent | pass the authorization the payload names |
+| `gbrain jobs submit` on PGLite | queued with no worker to run it | refuses with `no_worker` unless `--follow` or `--queue-only` | add `--follow` (run it now) or `--queue-only` |
+| Invalid input: `autopilot --interval`, `serve --port`, `dream --phase`, `init --mcp-only` missing flags, `delta --since` | exit 1 | exit 2 (`invalid_params`) | treat 2 as "fix the command" |
+| `gbrain doctor --json` with no brain configured | human text or nothing | one `no_brain` envelope with the `gbrain init` fix | parse the document |
+| `gbrain serve` on a brain another serve holds, or with no brain | exited before the MCP handshake | completes the handshake in status-only mode with one `gbrain_status` tool; `--fail-fast` (or `GBRAIN_SERVE_FAIL_FAST=1`) restores the early exit for supervisors | read `gbrain_status`; supervisors pass `--fail-fast` |
+| `gbrain doctor` (plain, `--only`, `--remediation-plan`, MCP `run_doctor`) with an embedding key | sent one paid embedding request on every run | no provider call; `embedding_provider` reports `configured, not probed` with a `paid`+`egress` fix (`--only embedding_provider --probe --yes`) | run the probe only after the user agrees |
+| `gbrain embed`, `jobs submit embed*`, `features --auto-fix` with a billed embedding provider and no terminal | embedded without asking | exit 3 with the consent payload unless `--yes`, `--max-usd`, tokenmax or a preapproval covers it; writes that embed new content are unchanged | cron jobs that backfill on purpose pass `--yes` (or `--max-usd <n>`), or set a preapproval |
+| `doctor --remediation-plan --json` steps | `command` only | each step also carries `fix` with `consent` (`paid` / `destructive`) and `next` | follow `fix.next` |
+| A PGLite brain whose automatic repair failed | later commands kept opening it and wrote to `pg_wal/` | every command exits 3 with the consented `pglite-repair` until the user decides; nothing touches the data directory | relay `user_message`; never move or rebuild the brain files yourself |
+| `gbrain serve` whose configured brain directory is missing (unmounted drive) or whose writer-lock file cannot be opened | exited before the MCP handshake (`internal_error`) | status-only mode: `gbrain_status` names the path (`missing_brain`, `brain_unopenable`); nothing is created at the path | relay it; the server reopens the brain once it is back |
+| `gbrain transcripts recent` while `gbrain serve` holds the brain | `pglite_busy` | reads through the running serve | none |
+| Error envelopes | `error`, `message`, `suggestion` | adds `code`, `fix`, `class`, `retryable`, `docs_cmd`, `contract_version`; `error` unchanged (legacy values frozen) | read `code`, fall back to `error` |
+| Docs pointers in errors | repo-relative paths | absolute URLs pinned to the installed version | open the URL, or run `gbrain errors <code>` offline |
+| MCP results with advice | advice in `_meta` or stderr only | extra `[gbrain notice …]` text blocks plus `_meta.gbrain_notices`; `content[0]` unchanged | parse `content[0]` alone; read the notice blocks |
+| MCP error results | could carry several blocks | exactly one block; notices inside the envelope | parse the one block |
+| MCP tool list on stdio | listed 10 owner-only tools that always refused there | those tools are not listed on stdio; their refusals name the CLI command | use the CLI command the refusal names |
+| MCP advisor on stdio | off | on by default (read-only); remote HTTP stays opt-in | none |
+| MCP `initialize` instructions | one fixed text | generated per surface (`verbs`, `starter`, `full`) from the tools that caller can call | none |
+| Keyless brains (no embedding key) | doctor warned and the health score dropped | doctor reports `severity: info` with the enable command; the score is not penalized | none |
+| stdin reads | could wait forever on an open, silent pipe | 30 s to the first byte, 60 s idle; `GBRAIN_STDIN_TIMEOUT_MS` overrides | close stdin or pipe the payload |
+| Prompts under an agent process or `CI` | prompted whenever stdin was a terminal | decline unless `GBRAIN_INTERACTIVE=1` | answer through the consent payload instead |
+| `--json` stdout for commands that declare it | could mix human text into stdout or print nothing on failure | exactly one JSON document; other output goes to stderr; a fallback document on a silent non-zero exit | parse stdout as one document |
+| `gbrain list/stats/health/tags/timeline --json` (op commands) | printed the human table | print the result as JSON, like every other op | parse stdout as JSON |
+| `gbrain import --json` | empty stdout on a refusal; a keyless brain refused with human text only | one document; on a keyless brain an `embedding_disabled` envelope whose `fix` is the same import with `--no-embed` | parse the document; run `fix.argv` |
+| A command needing a PGLite brain a live `gbrain serve` holds (`import`, `doctor --remediate`, `apply-migrations`, …) | `pglite_busy`, "wait and retry" (never ends) | the same `pglite_busy` plus a two-step `fix`: the user stops that serve (`kill <pid>`, `tell_user_to_run`), then `fix.then` re-runs the command; `apply-migrations` refuses before running instead of recording a failed attempt | relay the first step, then run `fix.then` |
+| `gbrain doctor` while a stdio serve holds the brain | `connection` FAIL, exit 1, "unhealthy" | `connection` warns with the two-step plan; exit 0 | follow the fix |
+| `gbrain doctor --remediate --yes` job steps with no worker (PGLite, or Postgres with no supervisor) | waited 90 s per step, then failed with a timeout | the steps run in-process, as `jobs submit --follow` does | none |
+| `gbrain advisor --json` on a keyless brain | `embeddings_disabled` and `low_embed_coverage` warnings (exit 1) | one `info` finding with the enable command (exit 0 unless something else warns) | none |
+| `gbrain serve --http` on a port already in use | printed its banner and kept the brain locked while serving nothing | exits non-zero with `serve_port_in_use` and the next free port | pick another `--port` |
+| Fix commands (`fix.argv`, `command`, `preview_argv`, `verify.argv`, `then`) | a few named the brain and source; most ran against whatever `GBRAIN_BRAIN_ID`, `GBRAIN_SOURCE` or dotfile the shell had | every gbrain fix names `--brain <id>` (and `--source <id>` where the command routes a source), so it acts on the intended brain from any directory | run fixes exactly as given |
+| `gbrain doctor --remediation-plan` on a brain with pending migrations | applied the migrations before computing the plan | never migrates; the plan carries a `migrations_pending` notice whose fix applies them | run the notice's fix, or `doctor --remediate` after consent |
+| `sources harden` with no id, `migrate` without `--to`, `mcp grant` without a NAME, malformed `backup create/restore` | exit 1 (`sources harden`: `internal_error`) | exit 2, `invalid_params`, with the usage and an example | treat 2 as "fix the command" |
+| `gbrain db-repair` under an ambient `GBRAIN_BRAIN_ID` pointing at a mount | refused, ignoring `--brain host` | `--brain host` repairs the host brain | none |
+
+`gbrain mcp expose` and `gbrain google` still exit 2 when they need confirmation (documented contract v1 legacy); `mcp expose`'s document now also carries the consent fields (`code`, `effects`, `user_message`, `fix`).
+
+### Itemized changes
+
+#### The agent error contract
+
+- One error envelope for the CLI `--json` document, MCP error results and HTTP bodies: `code`, `reason`, `message`, `suggestion`, `why`, `fix` (the exact command or MCP call, with `next` computed for your connection: `run`, `ask_user`, `tell_user_to_run`, `wait` or `report`), `docs`, `docs_cmd`, `class`, `retryable`, `contract_version: 1`. Golden shapes for harness authors live in `test/fixtures/agent-contract/v1/`.
+- Every error code gbrain throws is registered (`src/core/error-registry.ts`) and documented in the generated `docs/guides/error-codes.md`; `gbrain errors <code>` explains one offline and `gbrain errors --changed` lists the frozen `error` / new `code` pairs.
+- Refusals across shared skills, persistence, sync, source reconcile, connectors and company brains name their next step: the number of `OperationError` sites without a suggestion fell from 1,116 to 74 (the rest are listed in TODOS).
+- MCP op handlers stop throwing bare errors: unknown failures name the op and point at `gbrain doctor --json`; mutating calls with an unknown outcome point at the write receipt, never "retry".
+- Scope denials carry one envelope with the client id, its scopes and the exact `gbrain auth` command for the host's operator. A rate-limited `/token` mint on a thin client reports `rate_limited` with the retry delay instead of "OAuth discovery failed". Contributed by @rokas-tarasevicius (#5949).
+- Every engine-opening command on a thin client is refused or routed at connect time, naming the remote equivalent. Contributed by @rokas-tarasevicius (#5950).
+- Every op declares `mutating` and `idempotent`; MCP tool annotations (`readOnlyHint`, `idempotentHint`) and `gbrain --tools-json` (`scope`, `required_scopes`, `mutating`, `idempotent`, `local_only`) read them. Contributed by @rokas-tarasevicius (#5952, #5953).
+
+#### Consent, caps and interaction
+
+- `requireConsent` is the one consent gate for CLI commands: `paid` is authorized by `--yes` (derived cap), `--max-usd`, `spend.posture=tokenmax` or the user's per-run preapproval; `destructive` only by `--yes --expect <plan_hash>` bound to the previewed selection; `credentials`, `egress` and `persistent_install` by `--yes` (or the command's `--apply` / `--trust`). Commands with a consent gate start up observationally: a refusal on an outdated brain leaves the schema untouched.
+- `doctor --remediate`, `pglite-repair` (WAL backup and the restore command on every surface), `reinit-pglite`, `migrate embeddings`, `decide enable/probe`, `connect --install`, `sources connect`, `dream retriage`, `enrich`, `book-mirror`, `reindex-code`, `reindex-search-vector`, `reindex-frontmatter`, `skillpack` trust, `autopilot --install` (with `--dry-run`), `bootstrap harness` and `advisor --apply <id> --yes` ask through it. `spend.posture=tokenmax` keeps its uncapped meaning on `enrich` and `reindex-code`. The [spend controls guide](docs/operations/spend-controls.md#consent-and-caps-for-paid-commands-agent-operator-contract-v1) has the full cap table.
+- `BudgetTracker` knows where its cap came from: an unpriced model warns and runs under a derived or default cap and refuses only under a cap you set, with a fix that asks the agent to look up the rate and register it with `gbrain pricing set`.
+- Prompts and stdin reads go through one module: prompts decline on EOF or timeout and never run under an agent process or `CI` (`GBRAIN_INTERACTIVE=1` for a human there); payload reads time out on a silent pipe. `report`, `capture --stdin`, `connectors auth`, `notability-eval review` and `book-mirror` no longer hang. `connectors auth` without a terminal prints the cookie checklist for the user instead of waiting ([headless lane](docs/guides/chat-connectors.md#headless-lane-an-agent-without-a-terminal)).
+- `gbrain mcp expose` asks through the same gate and keeps its exit 2.
+
+#### CLI machine contract
+
+- Every top-level failure renders the same way: `Error [code]: …`, `Fix:`, `Why:`, `Docs:` on a terminal; one JSON document under `--json`. Commands that declare `--json` write exactly one document (NDJSON for `eval export/replay/gate` and `bench-publish`), and `init`, `apply-migrations`, `post-upgrade`, `sync`, `embed`, `dream`, `db-repair`, `doctor` and `jobs supervisor start --detach` now honor that.
+- Curated `--help` for `doctor`, `import`, `serve`, `apply-migrations`, `autopilot`, `status` and `onboard`, with did-you-mean for unknown flags; 27 more commands answer `--help` without opening the brain.
+- A bare `--` ends options for op commands, so an id that starts with `-` is never read as a flag.
+- Numeric flags are validated instead of silently misbehaving: `jobs submit`, `extract-conversation-facts`, `eval-run-all` (its cost guard can no longer be bypassed with NaN), `sync --watch --interval`, `connectors sync`, `reindex --multimodal/--aliases` and `book-mirror`. Contributed by @masashiono0611 (#5936, #5934, #5933, #5931, #5930, #5937, #5909).
+
+#### Doctor, readiness and the first run
+
+- One readiness model (embeddings, chat model, worker, writeback, backup, tool surface, sync, migrations, harness wiring) feeds doctor, `gbrain://capabilities`, `whoami` and notices, so "turn on embeddings" has one answer everywhere: `gbrain init --force --embedding-model <provider:model>`, which keeps pages and facts (the old `mv brain.pglite` recipe is gone).
+- Doctor checks carry a `fix` or say why there is none; `gbrain doctor --only <check>[,…] --json` runs just those checks read-only and is the verify step every fix points at. New checks: `harness_wiring` (with a smoke test that the registered server answers a recall) and `agent_contract` (recent internal errors, refused unattended runs, exhausted derived caps).
+- A keyless or brand-new brain is no longer scored as broken. Remediation runs free steps even when the score target is unreachable.
+- `gbrain init` emits one decision bundle: search mode, writeback (recommended `salient`), harness wiring and an optional skills scaffold, each with the command that applies it, and one sentence asking the user to reply "defaults". It no longer saves a made-up fact, and the harness registration it prints uses the absolute gbrain path and `--surface verbs`.
+- `jobs stats` tells "no worker is running" apart from "the worker is wedged"; sync refuses a gbrain-owned content directory with `sync_not_applicable` and the right import command.
+- `gbrain post-upgrade` no longer stops right after an up-to-date `apply-migrations`; the schema pass, banners, prompts and recovery checks run on every upgrade again.
+
+#### MCP
+
+- Notices: degraded recall, a source binding that narrowed a read, empty retrieval, unknown parameters, a truncated listing (#5954, contributed by @rokas-tarasevicius), backup coverage, keyless-by-design answers and the post-upgrade summary arrive as extra text blocks the model sees, mirrored in `_meta.gbrain_notices`. Coaching is capped at two per session and can be muted (`gbrain notices mute <code>`, MCP `mute_notice`).
+- `initialize` instructions are generated per surface from the tools the caller can call, within +15% of the old size.
+- A second serve, a missing brain or an unreadable config starts a status-only server with a `gbrain_status` tool; it recovers in place when the owner exits and sends `tools/list_changed`. `serve --fail-fast` keeps the old behaviour for supervisors.
+- Tool descriptions follow one template and state their key and scope needs; `list_jobs` takes a `fields` projection.
++- Composed with v0.60.44.0's cost wave: its measured tool descriptions, lean rows and compact JSON are kept (success results' `content[0]` is compact JSON on every path, error envelopes stay indented). The starter tool list stays under 25,000 characters of what a model receives (24,100; name, description and input schema), and the whole `tools/list` JSON, now carrying an annotation for every tool, is 25,735. Saved-facts and other-names evidence blocks stay plain blocks after `content[0]`; the keyless `degraded_recall` notice is bounded on its own, so the cost wave's result ceiling still pins rows and evidence at 2,540 characters.
+
+#### Docs and skills
+
+- New [agent operator protocol](docs/protocol/AGENT_OPERATOR_v1.md) with six transcripts (three recorded from the journey tests below), the decision table, marker grammar and this release's behavior table. AGENTS.md carries its quick contract.
+- Troubleshooting and the symptom tables in every guide gain Who acts, Consent and Verify columns; verify steps use `gbrain doctor --only <check> --json`.
+- Every skill gains a "When it fails" section pointing at the protocol.
+
+#### Follow-ups from the wave 8 re-pin
+
+- `get_timeline` without a source scope looks the page up by source and slug instead of scanning the whole slug index, so the planner statistics added in v0.60.37.0 no longer slow it down. On gbrain-evals' 1,000-page Cat 7 brain the median call fell from about 0.087 ms to 0.057 ms; on an 11,000-page brain from about 1.06 ms to 0.08 ms on PGLite, with Postgres execution falling from 0.93 ms to 0.06 ms.
+- The empty-source-grant refusal (`fence=no_source_grant`) names the token by `--id` in its fix on every path, including writes refused at submission and `POST /ingest`, which now returns the fix too. When the token can't be named, the fix is `gbrain auth list` instead of a `<name>` placeholder.
+- `edit_page`'s receipt diff lists removed lines before added ones, as `git diff` does. `gbrain skillpack reference` diffs use the same order.
+- `gbrain sources refresh` no longer fails with `refresh_recovery_required` when it starts right after a write. The writer's cleanup is still in progress at that moment and still holds the checkout's lock, so the refresh now waits for it; only recovery that no running process holds is refused.
+
+#### Agent journey tests
+
+- Deterministic end-to-end journeys drive the real CLI and real stdio/HTTP MCP sessions on a keyless brain with stdin closed and as an open silent pipe: init's decision bundle, a clean day-zero doctor, a refused-then-approved remediation (also on a brain with a pending migration), the degraded-recall notice, a caller mistake whose `fix` runs as given, the status-only second serve, every `--json` document, every doctor fix and remediation-plan command, one embedding-enable command on every surface, the `starter` surface, a read-only grant, recovery from another directory with conflicting `GBRAIN_BRAIN_ID` / `GBRAIN_SOURCE`, each exclusive command under a live serve, both shared-HTTP recoveries, the error normaliser across MCP, CLI and the thin client (including a frozen v0.60.37 client), injection inertness, the HTTP view, notice dedupe, Postgres parity and upgrade fixtures for existing scripts, scheduled jobs, harness configs and queued jobs.
+- Fixes they found: an MCP caller mistake on a read tool (wrong type or value) carries a `fix` that re-runs the call with the bad argument corrected; recovery commands name the brain and source they act on (`--brain`, `--source`); doctor warnings for a low brain score and repairable wave findings point at the read-only plan or `gbrain repair <kind>` preview; a skill waiting for content it does not have yet is information, not a warning; init's `--no-embedding` hint prints the same enable command doctor gives; `gbrain call`, `sources refresh --json` and `--brain <unknown>` return the full envelope; notices collected before an error ride in its envelope; hostile page ids land after `--` in fixes; `submit_job` with an unknown outcome points at the job list; usage errors on the persistence lane exit 2; stdio database fixes name the user, not the host admin.
+
+#### Closeout
+
+- Explicit routing is now central: gbrain appends `--brain` and `--source` to every gbrain command in a fix when it renders it, using the brain and source the failing call acted on, and keeps flags a fix already names. Which commands take which flag comes from the command table and each command's code (`CLI_ROUTING_FLAGS`, generated by `bun run build:flag-registry`). Over HTTP only the source id is pinned, where a thin client can send it (a mount id is host topology, and a thin client refuses `--brain`); a thin client pins nothing of its own.
+- `gbrain doctor --remediation-plan` is read-only on an outdated brain: it connects without migrating and reports the pending migrations as a notice.
+- Delegated write errors (`capture`, `forget`, `call` and the persistence lane) keep their legacy JSON keys and add `code`, `fix`, `docs_cmd`, `class`, `retryable` and `contract_version`, as every other `--json` error does. A lost acknowledgment from the local persistence owner reports `owner_unavailable` and points at the write receipt instead of `internal_error`.
+- A missing table (`get_job_stats`, search stats) no longer says "run apply-migrations" while its fix says "run doctor": the suggestion now quotes the fix.
+- `think` over HTTP on a keyless brain no longer names the host's API key variable in its answer.
+- A thin client keeps a remote server's MCP-only fix instead of dropping it: the CLI shows `Fix: call <tool> over MCP with {…}` and `--json` carries it as `tell_user_to_run`.
+
+
+#### Release-gate fixes (Cat 41 after-pass)
+
+The real-agent eval of the candidate still found nine consent-violation steps and one new false "no notes" answer. Each now has a product fix and a test that fails on the old code:
+
+- Plain `gbrain doctor` no longer spends money: it sent one tiny paid embedding request on every run. Doctor, `--only`, `--remediation-plan`, MCP `run_doctor`, readiness, `features` and `onboard --check` make no provider call; the embedding check says "configured, not probed" and its fix is `gbrain doctor --only embedding_provider --probe --yes` (paid + egress, so the agent asks first). Local providers that bill nothing need no consent.
+- Explicit embedding backfills ask first. `gbrain embed` (stale, catch-up, all, a slug, facts, images), `jobs submit embed|embed-backfill|embed-catch-up` and `features --auto-fix` stop with exit 3 and the consent payload (estimate and a `--dry-run` preview) unless `--yes`, `--max-usd`, tokenmax or a preapproval covers them; a user cap below the estimate refuses before anything runs. Every remediation-plan step now carries a `fix` with its effects, so an embed step reads `ask_user` instead of looking free. Writing new content with a configured key still embeds it without asking (that is the feature), and autopilot, cycles and queued jobs keep running under their configured budget; the protocol's consent section says so.
+- A brain whose automatic PGLite repair failed is never opened again until the user decides: gbrain records the failure next to the brain, and every command (stats, doctor, list, …) exits 3 with the consented `gbrain pglite-repair --yes --expect <plan_hash>` and its `--dry-run` preview, without touching a byte of the data directory. The refusal says plainly not to copy, rebuild, move or modify the brain files by hand. `pglite-repair --dry-run`, the consented repair (which clears the record), `reinit-pglite` and engine-free `doctor --only` checks still work; `gbrain serve` starts in status-only mode with `reason: repair_failed`.
+- A stdio agent learns that local session transcripts exist. Searches about the user's own activity (or that come back empty) carry a `local_transcripts` notice naming where the transcripts are and `gbrain transcripts recent --json`; `gbrain://capabilities` and the initialize readiness tail list them too. `gbrain transcripts recent` now reads through a running `gbrain serve` instead of failing on its lock. The stdio connection still cannot call `get_recent_transcripts`.
+- `gbrain serve` with a configured brain directory that is missing (an unmounted drive) or a writer-lock file it cannot open no longer exits before the handshake: it starts in status-only mode, `gbrain_status` names the path, and nothing is created there. It reopens the brain in place once the drive is back.
+
+ ## [0.60.44.0] - 2026-10-03
+
+ **Your agent pays less for every gbrain call: search results, tool results and the tool list are all smaller, and search skips work it does not need.**
+
+ An agent connected to gbrain pays for two things on every turn: the list of tools it can call, and every tool result it has seen so far. Both were heavy. A typical search returned about 23 results of 1,200 characters each, but only a few hundred characters per result were the text the agent needed; the rest was ranking detail it never read, re-sent on every later turn. The starter tool list was about 60,000 characters before the agent asked anything.
+
+ Now a search or query from an agent returns the fields an agent acts on: the text, where it came from, how strong the match is, whether creating a new page would duplicate one, and any safety or provenance warning. Results are compact JSON. The starter tool list is 24,763 characters, with the longer guidance moved to a reference page. Notices about saved facts and other names under a search have a size cap. Your own `gbrain search` on the command line, local or thin client, still shows every field.
+
+ | Per agent call | Before | After |
+ | --- | --- | --- |
+ | Starter tool list (34 tools) | 59,969 characters (13,077 tokens) | 24,763 characters (5,568 tokens) |
+ | Search result rows for an agent | every ranking field, indented JSON | lean rows, compact JSON |
+ | Saved-facts / other-names notice | unbounded | 1,500 / 400 characters, whole items |
+ | Cat 40 model cost per task, held-out world (6 models × 2 repeats) | $0.118 | $0.080 (−32%) |
+ | Cat 40 cost per successful task, held-out world | $0.161 | $0.106 (−34%) |
+ | Cat 40 tasks finished, held-out world (of 600) | 441 (73.5%) | 454 (75.7%) |
+
+ Tokens are cl100k counts. The Cat 40 rows come from gbrain-evals Cat 40 on a world held out from all tuning. They compare this wave with v0.60.35.0, run at the same time on the same harness: success changed by +2.2 points per task (95% CI −0.5 to +5.0), with no new leaks. Wall time per task barely changed (median 61 s before, 64 s after).
+
+ Things to watch: a script or third-party client that reads `page_id`, `cosine`, `keyword_hit` or another ranking field from agent-facing search results now gets lean rows. Pass `fields: "full"` per call, or set `gbrain config set mcp.result_rows full` on the brain host. A thin CLI older than this release gets lean rows until it is upgraded or the host sets that option.
+
+ ## To take advantage of v0.60.44.0
+
+ `gbrain upgrade` installs it. No schema migration runs.
+
+ 1. **Restart every `gbrain serve`** so stdio servers load the new tool list and row shape.
+ 2. **Your agent reads `skills/migrations/v0.60.44.0.md` the next time you talk to it.** It covers the lean rows and how to get full rows back. Nothing in it spends money.
+ 3. **Verify:**
+ ```bash
+ gbrain doctor
+ gbrain config get mcp.result_rows # empty: agents get lean rows
+ ```
+ 4. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor` and `~/.gbrain/upgrade-errors.jsonl` if it exists.
+
+ ### Behavior changes
+
+ - **Remote `search` and `query` callers get lean rows by default.** A row keeps `id`, `slug`, `title`, `type`, `chunk_text`, `score`, `effective_date`, `source_id`, `chunk_id`, `evidence`, `create_safety`, the markers `injection_suspected`, `injection_p`, `unverified`, `content_flag`, `status`, `superseded`, `superseded_by`, `message_id`, `thread_id` and `source_subject` when present, `modality` when not text, `stale` when true, and `delivered: {"truncated": true}` when delivery cut the text. `fields: "full"` per call, `mcp.result_rows: full` per host (DB plane wins over the config file) and gbrain's own thin client (it sends `X-Gbrain-Client: gbrain-remote-cli/<version>`) get every field. `_meta.retrieval.rows` reports the shape. Trusted local callers always get full rows. Examples and a client table: [docs/mcp/README.md](docs/mcp/README.md#search-and-query-result-rows).
+ - **Successful tool results are compact JSON** in the first content block. Error envelopes are unchanged.
+ - **Starter tool descriptions are short.** Every starter tool keeps its purpose, required inputs, consequential defaults, next call and recovery move; the longer text is in [docs/mcp/TOOL_REFERENCE.md](docs/mcp/TOOL_REFERENCE.md). The initialize instructions are unchanged.
+ - **The saved-facts notice is capped at 1,500 characters and the other-names notice at 400**, with whole items and a `(+N more)` count; the first item always shows.
+
+ ### Itemized changes
+
+ #### Result rows and serialization
+
+ - `src/core/search/lean-rows.ts` projects rows at the end of `searchOutput` in `src/core/ops/search.ts`, after capture, response meta and the last-retrieved bump read full rows. `OperationContext.resultRows` is set by all three MCP transports (`src/mcp/result-rows.ts`: the header and dual-plane `mcp.result_rows`); the header selects a row shape only and never gates authority.
+ - `src/mcp/dispatch.ts` serializes successful results with `JSON.stringify(result)`.
+ - Tests: `test/search-lean-rows.test.ts` (field set, escape hatches, `assemble_evidence` and `fetch` from lean rows, truncation under omitted, configured and explicit `return_unit`, the duplicate-page guard), `test/mcp-result-rows-skew.test.ts` (old and new CLI against the host over OAuth HTTP, the legacy bearer transport and stdio, including `mcp.strict_params=reject`), `test/mcp-result-size-ceiling.test.ts` (the model-visible size of a canonical search and query result; re-pin procedure in the file).
+
+ #### Tool list
+
+ - Per-tool schema budgets, hard caps of 1,200 characters per description and 200 per parameter description, the 25,000-character served starter ceiling (with `mcp.publish_skills` on and off), a cl100k token ceiling and the instructions ceiling are pinned by `test/mcp-schema-budget.test.ts`, with the minimum guidance each tool must keep.
+
+ #### Notices
+
+ - `retrievalNoticeBlocks` (`src/mcp/dispatch.ts`) applies the ceilings; boundaries pinned by `test/mcp-notice-ceilings.test.ts`.
+
+ #### Search latency
+
+ - Search runs one indexed check for an active saved fact before scanning saved facts, and skips the scan when there is none. The declared-name scan skips rows without a declaration keyword and runs once per search when the response reads the same rows the other-name search did. Results are byte-identical (`test/search-c5-identical.test.ts`).
+ - Per-search stage profile on the 10,000-page scale harness (PGLite, keyless): primary hybrid search 19.5 ms, projection-readiness check 6.0 ms, unsealed-pages check 0.5 ms, declared-name scans 0.01 ms each; the saved-facts scan does not run in the harness (it runs on the MCP dispatch path, where it took 3.1 ms on this fixture, which has saved facts).
+ - `bun scripts/scale/run.ts --pages 10000 --seed 1`, agent (MCP) search p50: 41.1 ms before and 39.0 ms after this change, same machine and session. On the harness version that also runs v0.60.32.0, v0.60.32.0 measured 95.9 and 90.6 ms and this release 27.4 ms (27.3 ms before the search change); most of that gain is v0.60.37.0's planner statistics.
## [0.60.41.0] - 2026-10-04
**A keyword-only `query` whose answer is in the top five now grades `moderate` again when the question merely uses a word the brain never writes, while questions about a missing attribute or an unknown company still grade `weak` (#5919). Conversation pages can set their own segmentation gap (#5918).**
diff --cc TODOS.md
index a019f4611b,46d29b9812..28643f9d98
--- a/TODOS.md
+++ b/TODOS.md
@@@ -1,58 -1,5 +1,58 @@@
# TODOS
- ## Agent-first operator wave follow-ups (filed 2026-10-03, follow-up from v0.60.42.0)
++## Agent-first operator wave follow-ups (filed 2026-10-03, follow-up from v0.60.45.0)
+
+Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/protocol/AGENT_OPERATOR_v1.md`.
+
+- [ ] **P2 — Tool-call proxy for a second `gbrain serve`.**
+ **What:** a second stdio serve on a held brain answers in status-only mode with one `gbrain_status` tool. **Why:** the user has to move both harnesses to a shared `serve --http` to get memory in the second session. **Fix:** authenticated IPC forwarding to the owning serve, carrying the proxied caller's surface and scopes. **Effort:** L. **Priority:** P2.
+- [ ] **P2 — Status-only mode for `serve --http` lock contention.**
+ **What:** status-only mode covers stdio; a `serve --http` that loses the lock still exits. **Why:** an HTTP client sees a dead endpoint instead of the `gbrain_status` explanation. **Fix:** the same status-only server on the HTTP transport, re-probing with `peekLock()`. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Support policy and removal of legacy shapes.**
+ **What:** legacy JSON shapes, frozen `error` values and duplicate receipt copies stay under contract v1. **Why:** they double the surface harness authors read. **Fix:** a written support policy plus consumer evidence, then removal in `AGENT_OPERATOR_v2`. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Exit 3 for `mcp expose` and `google` under contract v2.**
+ **What:** both still exit 2 for `confirmation_required` (documented v1 legacy); `mcp expose`'s document already carries the consent fields. **Fix:** move them to 3 with the v2 contract. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — `run_doctor` and CLI `doctor` from one registry with a `remote_safe` flag.**
+ **What:** MCP `run_doctor` and CLI `doctor` agree on the same brain through parity tests, but the check lists are still two code paths. **Why:** a new check can land on one surface only. **Fix:** one registry; each entry declares `remote_safe`, and `run_doctor` runs exactly the remote-safe subset. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Submit-time job authorization and pre-upgrade queued jobs.**
+ **What:** `book-mirror`'s paid fan-out asks at the CLI, but the queued child jobs carry no authorization record, and jobs queued before the upgrade run under the configured budget with no consent record. **Fix:** persist the `Authorization` (effects, cap, cap source) on the submitted job and check it in the worker; a pre-upgrade job without one runs under the configured budget and says so. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — `consent.preapprove.paid.max_usd_per_day`.**
+ **What:** only the per-run preapproval ships. **Fix:** a daily preapproval through the durable reservation model (`src/core/minions/budget-meter.ts`, `delegated-policy.ts`) with concurrency and crash-recovery tests, plus the C9 rows. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Onboarding notices over MCP.**
+ **What:** the post-upgrade summary reaches stdio MCP sessions as a notice and the advisor carries the writeback finding, but the onboarding nudges (`onboard_opportunities`) and init's first-run decision bundle reach only CLI callers. **Why:** an agent that only talks MCP never sees them. **Fix:** emit them through the notice channel once per session, under the coaching budget and mute rules. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — Connectors two-step OAuth.**
+ **What:** `connectors auth --try-oauth` refuses headless and hands over the cookie lane. **Fix:** print the authorize URL and exit awaiting consent, then a second command completes with the pasted redirect (the Google connect shape). **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Unify MCP surfaces across wiring paths.**
+ **What:** `bootstrap hooks` registers `full` (`src/commands/bootstrap.ts:~1282`) while the readiness fix and init register `--surface verbs`. **Fix:** one surface choice for every registration path. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — Make `gbrain bootstrap verify` read-only, then mark it `read_only`.**
+ **What:** it is excluded from the verify-field scanner rule until it writes nothing. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — `structuredContent` with per-op `outputSchema`.**
+ **What:** emitted only as a semantic superset of `content`, after client behaviour converges. **Fix:** include Codex and VS Code scenarios proving the body reaches the model. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Re-baseline BrainBench after the wave** if notice blocks change harness behaviour. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — Tier 3 carry-over: D3's remaining curated helps.**
+ **What:** B10 shipped in this release; D3's remaining curated helps are the 33 rows in `test/fixtures/cli-contract/help-baseline.json` (stub helps, `missing_yes`, `exit`). **Fix:** burn them down; the D5 baseline is shrink-only. **Effort:** M. **Priority:** P2.
+- [ ] **P2 — Backfill the last 74 suggestion-less `OperationError` sites (31 files).**
+ **What:** B10 took the scanner baseline from 1,116 sites in 143 files to 74 in 31. What remains: `src/commands/` (persistence-admin 11, repair 6, reindex-code-delegate 5, embed-facts-delegate 5, sync-persistence-delegate 4, extract-stale-delegate 4, capture 4, recall 3, and smaller), `src/cli.ts`, and single-digit core sites (effect-facts 3, effect-targets, company-brain/policy, embed-facts, shared-skills/adapter, source-local-reference-index, and 1-site files). **Fix:** the B10 pattern (`opError` + filled `fix`, receipts by `request_id` for CLI-principal rows only); `scripts/agent-contract-baselines/suggestionless-operation-error.tsv` lists them. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Module-local `fail(code, message)` helpers carry a generic next step.**
+ **What:** `shared-skills/adapter.ts` and `shared-skills/membership.ts` funnel about 40 refusals through one suggestion-less helper each, and `persistence/administration.ts` gives its ~28 parameter checks a shared default. **Fix:** a per-code suggestion table, so each refusal names its own next step. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Ratchet burn-down of the other agent-contract scanner baselines.**
+ **What:** counts at filing (`scripts/agent-contract-baselines/`, after B10): legacy advice keys 237, hand-built command strings 51, marker literals 26, `stdio: 'inherit'` 12, flag text in MCP-visible strings 6, raw "re-run with --yes" 5, in-scope placeholders 4, `throw new Error` in ops 3, non-read-only verify 1; suggestion-less `OperationError` is the 74 above; interactive I/O and retry-on-mutating are at 0. **Fix:** shrink per file as files are touched; the baselines refuse growth. **Effort:** L. **Priority:** P3.
+- [ ] **P3 — `sync_freshness` fix placeholder.**
+ **What:** the check's fail/warn message still says ``gbrain sync --source <id>`` instead of naming each stale source's command, because `checkSyncFreshness` sits at its function-size ceiling. **Fix:** split the function, then emit one filled `fix` per stale source. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Collapse the five error classes into `opError` + the registry.** **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Harness-author community channel** linked from `AGENT_OPERATOR_v1.md`. **Effort:** XS. **Priority:** P3.
+- [ ] **P3 — Recall relevance on tiny keyless brains.** Measure first. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Trim the AGENTS.md pre-install preamble** (owner rewrite). **Effort:** S. **Priority:** P3.
+- [ ] **P3 — MCP elicitation for consent.**
+ **What:** trigger is the first MCP op whose fix has non-empty consent and an MCP-callable re-invocation; stdio first, HTTP needs a session-bound transport. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Doctor report `schema_version: 3`** with a first-class informational status (today `ok` + `severity: 'info'`). **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Retire the `--json` exit-time fallback document** once direct-exit paths reach zero. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Retire the `promptLine` / `promptLineStderr` / `promptYesNo` and legacy `readStdinBounded` shims.** **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Curated annotation titles and a `destructiveHint` / `openWorldHint` review** for every mutating op. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — HTTP session-scoped coaching dedupe** when the transport becomes session-bound (today principal + transport session id, principal only when absent). **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Status-mode recovery for clients that ignore `tools/list_changed`.** Measure per harness and document. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Keep `getStats` / `getHealth` off agent paths** (cross-ref #5061; the readiness cache is the pattern). **Effort:** S. **Priority:** P3.
+
## Foundations 1 follow-ups (filed 2026-10-03, follow-up from v0.60.37.0)
- [ ] **P1 — Mutation attribution for the writers still unattributed.**
diff --cc VERSION
index ec90cee71a,cf91026bc4..705fd763d4
--- a/VERSION
+++ b/VERSION
@@@ -1,1 -1,1 +1,1 @@@
- 0.60.42.0
-0.60.44.0
++0.60.45.0
diff --cc docs/TOOL_CATALOG.md
index 3368d6261b,87cf6e1ddd..25ff219388
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@@ -73,19 -72,19 +73,19 @@@ Every non-localOnly operation on the MC
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
- | `get_ingest_log` | List recent ingestion events (what was imported, from where, which pages changed). | read | yes | |
+ | `get_ingest_log` | Recent ingestion log entries. | read | yes | |
-| `log_ingest` | Log an ingestion event | write | | |
+| `log_ingest` | Record one ingestion event (source type, reference, pages updated, summary) in the brain's ingest log. | write | | |
## insights
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
- | `find_anomalies` | Returns statistical anomalies in recent page activity, grouped by cohort (tag or type). | read | yes | |
+ | `find_anomalies` | Anomalies in recent page activity, grouped by cohort (tag or type) against a baseline. | read | yes | |
| `find_contradictions` | Stored contradiction reports are temporarily available only to trusted local callers without a source filter. | read | | |
| `find_experts` | Answers 'who in my brain knows about <topic>'. | read | | |
-| `find_trajectory` | v0.35.4 — return the chronological claim trajectory for an entity (typed metric values over time, plus auto-detected regressions and narrative drift). | read | | |
+| `find_trajectory` | Return the chronological claim trajectory for an entity (typed metric values over time, plus auto-detected regressions and narrative drift). | read | | |
| `get_calibration_profile` | Read the active calibration profile for a holder. | read | | |
- | `get_recent_salience` | Returns readable pages recently touched and ranked by activity salience and recency. | read | yes | |
+ | `get_recent_salience` | Recently touched pages ranked by salience. | read | yes | |
| `volunteer_context` | Push-based context: volunteer brain pages relevant to a rolling conversation window WITHOUT being asked. | read | | |
## jobs
@@@ -97,26 -96,26 +97,26 @@@
| `get_job` | Get job status and details by ID. | admin | | |
| `get_job_progress` | Get structured progress for a running job. | admin | | |
| `get_job_stats` | Job queue statistics. | admin | | |
-| `list_jobs` | List jobs with optional filters. | admin | | |
-| `pause_job` | Pause a waiting, active, or delayed job | admin | | |
+| `list_jobs` | List background jobs with optional status/queue/name filters; pass fields to project each job to the columns you need. | admin | | |
+| `pause_job` | Pause a waiting, active or delayed background job. | admin | | |
| `replay_job` | Replay a completed/failed/dead job, optionally with modified data | admin | | |
-| `resume_job` | Resume a paused job back to waiting | admin | | |
-| `retry_job` | Re-queue a failed or dead job for retry | admin | | |
-| `send_job_message` | Send a sidechannel message to a running job's inbox | admin | | |
+| `resume_job` | Resume a paused background job (back to waiting). | admin | | |
+| `retry_job` | Re-queue a failed or dead background job. | admin | | |
+| `send_job_message` | Send a sidechannel message to a running job's inbox (for jobs that read steering messages). | admin | | |
- | `submit_agent` | Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. | agent | yes | |
+ | `submit_agent` | Submit an agent job (agent scope; tools and budget bound to your client). | agent | yes | |
| `submit_job` | Submit a background job. | admin | | |
## links
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
-| `add_link` | Create link between pages | write | | |
+| `add_link` | Create a typed link (edge) from one page to another in the same source. | write | | |
| `find_orphans` | Find disconnected pages. | read | | |
- | `get_backlinks` | List a page's incoming links (who points at it). | read | yes | |
+ | `get_backlinks` | List links pointing to a page. | read | yes | |
-| `get_links` | List outgoing links from a page | read | | |
+| `get_links` | List a page's outgoing links (typed edges to other pages). | read | | |
- | `list_link_sources` | List distinct link_source provenances in the brain with edge counts (e.g. | read | yes | |
+ | `list_link_sources` | Link provenances in the brain (e.g. | read | yes | |
-| `remove_link` | Remove link between pages | write | | |
+| `remove_link` | Remove a link between two pages (optionally only one link_type or link_source). | write | | |
- | `traverse_graph` | Traverse link graph from a page. | read | yes | |
+ | `traverse_graph` | Walk the link graph from a page. | read | yes | |
## loops
@@@ -159,23 -158,23 +159,23 @@@
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
- | `cancel_write_request` | Cancel your accepted write before publication starts. | write | yes | |
- | `capture` | Capture a quick note into the brain — the "just remember this" write. | write | yes | |
+ | `cancel_write_request` | Cancel your accepted write before it publishes. | write | yes | |
+ | `capture` | Quick note ("just remember this"): auto-slugged under inbox/ by date + content hash, so recapturing is idempotent. | write | yes | |
| `delete_page` | Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). | write | | |
- | `edit_page` | Change part of an existing page without resending it: prefer this over put_page for small changes to large pages. | write | yes | |
+ | `edit_page` | Change part of a page: prefer this over put_page for small changes. | write | yes | |
| `fetch` | Fetch the full text of one search result by its opaque, source-qualified `id` (OpenAI deep-research contract: the search/fetch pair). | read | | |
-| `get_chunks` | Get content chunks for a page | read | | |
+| `get_chunks` | Return a page's indexed content chunks (the units search ranks). | read | | |
- | `get_page` | Read a page by slug (supports optional fuzzy matching). | read | yes | |
+ | `get_page` | Read a page by slug (fuzzy optional; renamed slugs redirect). | read | yes | |
| `get_raw_data` | Retrieve raw data for a page. | read | | |
| `get_versions` | Page version history. | read | | |
- | `get_write_request` | Read your durable write receipt by request_id. | write | yes | |
- | `list_pages` | List pages with optional filters. | read | yes | |
- | `list_write_requests` | List your currently authorized write receipts in one source, newest first. | write | yes | |
- | `put_page` | Replace a complete canonical Markdown page. | write | yes | |
+ | `get_write_request` | Read the receipt of your write by request_id (after write_pending or a lost reply). | write | yes | |
+ | `list_pages` | List pages with filters. | read | yes | |
+ | `list_write_requests` | List your write receipts in one source, newest first. | write | yes | |
+ | `put_page` | Replace a complete Markdown page: content REPLACES the whole page. | write | yes | |
-| `put_raw_data` | Store raw API response data for a page | write | | |
+| `put_raw_data` | Store a raw provider payload (API response JSON) alongside a page, keyed by source. | write | | |
- | `resolve_slugs` | Fuzzy-match a partial name or slug to existing page slugs. | read | yes | |
+ | `resolve_slugs` | Fuzzy-match a partial slug or title to page slugs. | read | yes | |
-| `restore_page` | v0.26.5 — restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). | write | | |
-| `revert_version` | Revert page to a previous version | write | | |
+| `restore_page` | Restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). | write | | |
+| `revert_version` | Restore a page to an earlier version from its history (a new revision; history is kept). | write | | |
## schema
@@@ -197,9 -196,9 +197,9 @@@
|---|---|---|---|---|
| `assemble_evidence` | Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): the same windows, sections or pages `query` returns with return_unit, packed into token_budget. | read | | |
| `cache_stats` | Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. | admin | | |
- | `query` | Hybrid search with vector + keyword + multi-query expansion. | read | yes | |
- | `search` | Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. | read | yes | |
+ | `query` | Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. | read | yes | |
+ | `search` | Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. | read | yes | |
-| `search_by_image` | v0.36 cross-modal Phase 2: image-as-query retrieval. | read | | |
+| `search_by_image` | Image-as-query retrieval. | read | | |
| `search_modes` | Read-only search-mode dashboard: active mode, EVERY mode-bundle knob resolved with attribution (mode default vs config override), the three frozen bundles, and a reranker_readiness verdict (whether the resolved reranker will actually run; remote callers get the verdict without the host key inventory). | read | | |
| `search_stats` | Search observability over a window: cache hit rate, intent/mode mix, budget drops, rank-1 score drift, graph-signals failure counts. | admin | | |
| `search_tune` | Read-only tuning recommendations derived from the last 7 days of search telemetry: what should change, why, and the paste-ready config command per recommendation — relay them to the user. | admin | | |
diff --cc docs/architecture/key-files/mcp.md
index b1ac7ebcc2,f8c640c813..eb71e23d38
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@@ -3,17 -3,19 +3,19 @@@
[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/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope.
-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`.
++- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope.
-- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.
+- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`.
- `src/mcp/publish-gates.ts` — publish-gate resolution for the honest tools/list. `readPublishGate(engine, config, key)`: dual-plane (DB > file > false), never throws — a FAILED read resolves false (hide-on-doubt matches the default-off consent posture). `disabledOpsForPublishGates(engine, config)`: the op-name set tools/list subtracts; one getConfig read per distinct gate key per call, deliberately NOT memoized so `gbrain config set mcp.publish_skills true` takes effect on the next list without a restart. Call-time gates inside the handlers stay as the fail-closed backstop (their denials carry `detail: 'config_key=<key>'` — the machine-readable denial grammar). Pinned by test/publish-gates.test.ts.
- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).
+ - `src/mcp/result-rows.ts` — the transport side of the `search`/`query` row shape. `resolveResultRowsMode(engine, config)`: dual-plane `mcp.result_rows` (DB > file > 'lean'; a failed DB read falls to the file plane). `resultRowsForRequest(header, hostMode)`: the `X-Gbrain-Client` header naming `gbrain-remote-cli` (sent by `src/core/mcp-client.ts`) selects full rows, otherwise the host mode. The OAuth HTTP transport resolves both per request, the legacy bearer transport per tools/call, and stdio once at start (file plane only when the engine is degraded). The header is unverified and selects a row shape only; it must never gate anything security-relevant. Pinned by `test/mcp-result-rows-skew.test.ts`.
+
- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live listener (another serve) returns the null binding (that serve is the IPC provider). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.
-- `src/mcp/server.ts` — MCP stdio server (generated from operations). `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.
+- `src/mcp/server.ts` — MCP stdio server (generated from operations). Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[] and the probed worker status (`stdioCapabilityReadiness`). `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.
- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.
diff --cc docs/architecture/key-files/runtime.md
index ace0b6844a,d3fca5194c..2f6e0d3c07
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@@ -19,7 -19,7 +19,7 @@@ Current behavior and load-bearing invar
- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
- - `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser.
-- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
++- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser.
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`).
diff --cc docs/mcp/README.md
index e6c2f58c05,f8087af6ad..39232e59b2
--- a/docs/mcp/README.md
+++ b/docs/mcp/README.md
@@@ -37,21 -40,52 +41,71 @@@ Client-specific details: [ChatGPT](CHAT
[opencode](OPENCODE.md), [Perplexity](PERPLEXITY.md),
[OpenClaw](OPENCLAW.md), and the [adapter reference](../guides/harness-adapters.md).
+## A tool call returned an error
+
+Every gbrain tool error is one content block holding a JSON envelope. Read
+`code` (an older server sends only `error`), then follow `fix.next`:
+
+- `run`: call `fix.mcp` (or run `fix.argv` where you have a shell) exactly as given.
+- `ask_user`: relay `user_message` and stop; act only after the user agrees.
+- `tell_user_to_run`: the fix needs the user or the brain host's operator
+ (for example a scope grant or a CLI-only repair); give them `fix.command`.
+- `wait`: retry after the stated delay with the same request.
+- `report`: tell the user what happened; the host operator runs `gbrain doctor --json`.
+
+Then run `fix.verify`, which is always read-only. A mutating call with an
+unknown outcome points at its write receipt (`get_write_request`), never at a
+blind retry. Successful results can carry extra `[gbrain notice …]` text blocks
+after `content[0]`; read them too (a `degraded` notice means an empty result is
+not proof the user has no notes). Full contract, including the scope-failure
+`error`/`code` pairs: [AGENT_OPERATOR_v1](../protocol/AGENT_OPERATOR_v1.md).
++
+ ## Search and query result rows
+
+ `search` and `query` return their rows as compact JSON in the first content
+ block. Remote callers get **lean rows** by default: the fields an agent acts
+ on, without the ranking diagnostics that made each row several times longer
+ than its evidence text.
+
+ A lean row keeps `id` (the `fetch` key), `slug`, `title`, `type`,
+ `chunk_text`, `score`, `effective_date`, `source_id`, `chunk_id` (with
+ `slug` and `source_id`, the `assemble_evidence` hit), `evidence` and
+ `create_safety` (the duplicate-page guard). It also keeps every safety or
+ provenance marker that is present: `injection_suspected`, `injection_p`,
+ `unverified`, `content_flag`, `status`, `superseded`, `superseded_by`,
+ `message_id`, `thread_id`, `source_subject`, `modality` when not `text`,
+ `stale` when true, and `delivered: {"truncated": true}` when evidence
+ delivery cut the text.
+
+ ```json
+ {"query": "acme-example renewal terms"}
+ ```
+
+ ```json
+ [{"slug":"contracts/acme-example-msa","title":"MSA: Acme Example","type":"contract","chunk_text":"Payment terms: Net 45. Renewal is annual.","chunk_id":812,"score":0.91,"source_id":"default","effective_date":"2026-04-02","id":"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FjbWUtZXhhbXBsZS1tc2EiXQ","evidence":"keyword_exact","create_safety":"probable"}]
+ ```
+
+ Pass `fields: "full"` to get every field (`page_id`, `chunk_index`,
+ `chunk_source`, `keyword_hit`, `cosine`, `base_score`, boosts, rerank and
+ graph signals, the full `delivered` object):
+
+ ```json
+ {"query": "acme-example renewal terms", "fields": "full"}
+ ```
+
+ `_meta.retrieval.rows` reports `"lean"` or `"full"` for every remote call.
+
+ | Client | Rows by default | How to get full rows |
+ | --- | --- | --- |
+ | Any MCP client (stdio or HTTP) | lean | `fields: "full"` per call, or the host sets `gbrain config set mcp.result_rows full` |
+ | gbrain thin CLI, this release or later | full (it sends `X-Gbrain-Client`) | nothing to do |
+ | gbrain thin CLI, older release | lean | upgrade the CLI, or the host sets `mcp.result_rows full` |
+ | Trusted local CLI (`gbrain search`, `gbrain call`) | full | nothing to do |
+
+ The host setting is read per request over OAuth HTTP and at start-up for
+ `gbrain serve` (stdio), so restart a stdio server after changing it. The
+ `X-Gbrain-Client` header selects a row shape only; it is not an identity
+ claim and never grants access.
+
+ Say to your agent: *"Search my brain for the acme-example renewal terms and
+ show me every ranking field for the top result."*
diff --cc docs/operations/spend-controls.md
index 6c071e309c,c933b78540..d5479f271a
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@@ -34,47 -34,6 +34,47 @@@ pointing at this switch
over posture. `tokenmax` only governs the default/absent case — it never overrides a
number you typed on the command line.
+## Consent and caps for paid commands (agent operator contract v1)
+
- Since v0.60.42.0 every command that spends money asks for authorization the
++Since v0.60.45.0 every command that spends money asks for authorization the
+same way ([protocol](../protocol/AGENT_OPERATOR_v1.md#consent-and-preapproval)).
+Without a terminal and without authorization, nothing runs: the command exits
+3 with a `confirmation_required` payload whose `user_message` the agent relays
+to the user, and whose `fix` is the exact command to run once they agree.
+`--json` never implies consent.
+
+What authorizes paid work, and the cap it runs under:
+
+| Authorization | Cap | `cap_source` |
+|---|---|---|
+| `--max-usd <n>` / `--max-cost <n>` | `<n>` | `user` |
+| a configured cap for the command (for example `embed.backfill_max_usd`) | that value | `user` |
+| the user's preapproval `consent.preapprove.paid.max_usd_per_run <usd>` (covers runs whose estimate is at or under it) | the preapproved limit | `user` |
+| `--yes` alone | the estimate × 1.5, floor $0.25, printed before the run | `derived` |
+| `--yes` alone, no estimate and no configured cap | the default cap ($5), printed | `default` |
+| `spend.posture=tokenmax` | the derived/default cap above, except `enrich` and `reindex-code` (below) | `derived` / `default` |
+
+- **`tokenmax` on `enrich` and `reindex-code` stays uncapped.** Those two
+ commands already ran without a ceiling under `spend.posture=tokenmax`
+ before the consent wave, so the posture keeps that meaning there: an
+ unattended run proceeds with no ceiling (spend still ledgered). Everywhere
+ else `tokenmax` authorizes the run under the derived cap. An explicit
+ `--max-usd` always wins.
+- **A derived cap that runs out** stops the command with exit 1, a checkpoint
+ and the exact resume command (`--max-usd <n>`); doctor's `agent_contract`
+ check then suggests the preapproval command. Raise the cap only with the
+ user's agreement.
+- **Unpriced models** (a model gbrain has no per-token rate for, for example
+ one released after this version): under a derived or default cap the run
+ **warns and proceeds** (`BUDGET_TRACKER_NO_PRICING` on stderr; the cap
+ cannot meter it). Under a cap the user set (`--max-usd`, a configured cap
+ or a preapproval) it **blocks** with `no_pricing` and nothing is spent: the
+ refusal's `fix` has `inputs` telling the agent to look up the model's
+ per-token rates (for example by web search on the provider's pricing page)
+ and register them with `gbrain pricing set` (see
+ [Registering a model price](#registering-a-model-price)), then retry the
+ same command.
+
## Off switches (`off` / `unlimited` / `none`)
The USD-limit knobs accept `off`, `unlimited`, or `none` (case-insensitive) to mean
diff --cc docs/protocol/MCP_META_CHANNELS.md
index 39cb9a506f,5c5de8619c..95e7df2bd0
--- a/docs/protocol/MCP_META_CHANNELS.md
+++ b/docs/protocol/MCP_META_CHANNELS.md
@@@ -31,9 -31,8 +31,9 @@@ shape for it
| Key | Producer | Contents |
|-----|----------|----------|
| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call |
- | `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `hint` (non-contractual prose) |
+ | `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed) |
| `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]` |
+| `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |
Inbound `_meta` (e.g. `_meta.session_id` inside tool ARGUMENTS) is a
separate, client-to-server plane. The eval-report `_meta.metric_glossary`
diff --cc openclaw.plugin.json
index f180f360f2,c6c8aa1d8c..e77d9f00b8
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@@ -1,7 -1,7 +1,7 @@@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --cc package.json
index 91a538dace,7367b7e049..7590fa452d
--- a/package.json
+++ b/package.json
@@@ -212,7 -207,7 +212,7 @@@
"bun": ">=1.4.0"
},
"license": "MIT",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.56",
"@hono/node-server": "^2.0.5",
diff --cc plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index d907a059a8,c6c8c05086..ad23aac67b
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-coding",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 90c247d23f,5b695020db..b25d8d463d
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-coding",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-coding/README.md
index cbc8f7c9f0,f6d809db19..c615d772f3
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-plugin-tree-stamp: 0.60.42.0 -->
-<!-- gbrain-plugin-tree-stamp: 0.60.44.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.45.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --cc plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 9bf399725e,6ca75a4ee2..8e72d116f0
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-daily",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 686c6d0eae,e00012b411..c9215f199d
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain-daily",
- "version": "0.60.42.0",
- "version": "0.60.44.0",
++ "version": "0.60.45.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --cc plugin-variants/gbrain-daily/README.md
index eea8e5dbe5,c14d960a82..86cb4785f8
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-plugin-tree-stamp: 0.60.42.0 -->
-<!-- gbrain-plugin-tree-stamp: 0.60.44.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.45.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --cc plugin/README.md
index a89f1075f5,29d5cfa11c..804bdab23c
--- a/plugin/README.md
+++ b/plugin/README.md
@@@ -1,4 -1,4 +1,4 @@@
- <!-- gbrain-plugin-tree-stamp: 0.60.42.0 -->
-<!-- gbrain-plugin-tree-stamp: 0.60.44.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.45.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --cc scripts/function-size-baseline.tsv
index 60694e6450,0c3483c9b0..a03634a803
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@@ -61,4 -63,5 +61,4 @@@ src/core/sources-ops.ts addSource 317 s
src/core/think/index.ts runThink 450 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/transcripts/ingest.ts runTranscriptsIngest 317 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/workspace-push.ts workspacePush 312 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
- src/mcp/http-transport.ts startHttpTransport 408 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/mcp/dispatch.ts dispatchToolCall 325 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 eval wave N5-1: hot-memory invalidation after mutating ops (success and failure paths)
+ src/mcp/http-transport.ts startHttpTransport 409 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): dispatch resultRows from X-Gbrain-Client / mcp.result_rows (logic in mcp/result-rows.ts)
diff --cc scripts/module-size-limits.tsv
index 2f17eb42f6,e5f50b98a7..03ddfec3d7
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -36,9 -36,9 +36,9 @@@ src/core/embedding-migration.ts 1569 ra
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
- src/core/config.ts 1824 ratchet +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys
-src/core/config.ts 1824 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts)
++src/core/config.ts 1827 ratchet +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.45.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured)
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
-src/core/ops/pages.ts 644 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso
+src/core/ops/pages.ts 659 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts)
src/core/search/mode.ts 1527 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part
src/commands/eval-longmemeval.ts 1518 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts)
diff --cc skills/migrations/v0.60.11.0.md
index 347cbc6883,f56399e9cf..b46c53cac8
--- a/skills/migrations/v0.60.11.0.md
+++ b/skills/migrations/v0.60.11.0.md
@@@ -84,12 -84,9 +84,12 @@@ user's agreement first
5. **Apply only what the user agreed to**, with their cap:
```bash
- gbrain doctor --remediate --yes --include-repairs --max-usd <n>
+ gbrain doctor --remediate --yes --include-repairs --expect <plan_hash> --max-usd <n>
```
+ `<plan_hash>` is the `plan_hash` from `gbrain doctor --remediation-plan --json`
- (gbrain v0.60.42.0 and later bind repair approval to the previewed plan).
++ (gbrain v0.60.45.0 and later bind repair approval to the previewed plan).
+
Pass `--no-embed` if they want no paid embeddings (then `gbrain embed
--stale` later). If the run stops as budget-exhausted, ask again before
running the printed resume command; the cap is cumulative across resumes.
diff --cc skills/skills.lock.json
index 2507ae4565,6d72c6a181..943de931ac
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@@ -151,7 -151,7 +151,7 @@@
"migrations/v0.59.0.0.md": "7903e547e79ad3429a393d9102a610e2674388bfaa71607431b1cd857b4af939",
"migrations/v0.59.10.0.md": "e0268a05ab184d5518f88747313e772629b2af91db59eacbba728f2ebd9db3cd",
"migrations/v0.59.2.0.md": "b6d61af8ef48c154a26e8d427dd6f6570e99efb82b891728426046eea493247b",
- "migrations/v0.60.11.0.md": "2adc879bad719dcd582bd9ff52d813ee65616b2896ee59c6139d0c78c413f06d",
- "migrations/v0.60.11.0.md": "ad3086df4eceff272f08bf16d674be404b97963292729b280f44268c583f77c5",
++ "migrations/v0.60.11.0.md": "09cc8b85c9c7bd71370671f2be40587250a72874ea978f39c667829f743e39ba",
"migrations/v0.60.20.0.md": "9266863a9f76164c64a72b1be17b8ddb3bb97e1c3c5db9f666b69ebc7a228fdd",
"migrations/v0.60.26.0.md": "30d761ef5a2361bad66053f97b7b659304a591274be33e281f4f6df0d7d5566e",
"migrations/v0.60.27.0.md": "1c3ac6a23ccfce8ad299457799b02958f7d21fcd967c471634f73bdb66f2b603",
diff --cc src/commands/serve-http-mcp.ts
index 39de26d655,344dfd7b99..3021ae5829
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@@ -21,11 -20,9 +21,12 @@@ import { createSkillResources } from '.
import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';
import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
import { hasScope, operationScopesAllowed } from '../core/scope.ts';
-import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, type ToolResult } from '../mcp/dispatch.ts';
+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, type ToolResult } from '../mcp/dispatch.ts';
+import { toAgentError } from '../core/agent-output.ts';
+import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
+import { scopeDeniedError } from '../core/ops/op-fix.ts';
import { resolveStrictParamsMode } from '../mcp/validate-params.ts';
+ import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest, type ResultRowsMode } from '../mcp/result-rows.ts';
import { buildToolDefs } from '../mcp/tool-defs.ts';
import {
filterOpsForSurface,
diff --cc src/core/agent-output.ts
index 319dd10e52,0000000000..88acd6d193
mode 100644,000000..100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@@ -1,881 -1,0 +1,882 @@@
+/**
+ * Agent operator contract v1 (docs/designs/AGENT_OPERATOR_WAVE.md, A0/A1/A6).
+ *
+ * One `Action` (`fix`) for every failure, refusal, degradation and
+ * recommendation; one error envelope (`AgentEnvelope`) for CLI `--json`, MCP
+ * `isError` results and HTTP bodies; one notice wire format. `next` and the
+ * shell `command` are computed here at render time and never stored.
+ *
+ * Everything an agent reads is built from static registry templates plus
+ * interpolated ids that pass through `inertText()`: newlines and marker
+ * tokens are neutralised so a page title can never forge an instruction.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { VERSION } from '../version.ts';
+import { OperationError, __registerOperationErrorRenderer } from './ops/contract.ts';
+import { StructuredAgentError } from './errors.ts';
+import { canonicalCodeFor, codeEntry, codeClass, codeRetryable, exitCodeForCode } from './error-catalogue.ts';
+import { VERB_NAMES } from './verbs.ts';
+import { classifyPgAccessError, formatDbAccessMarker } from './pg-access-classify.ts';
+import { redactConnectionInfo } from './audit/redact-connection-info.ts';
+import { redactUrlsInText } from './url-redact.ts';
+import { recordAgentContractEvent } from './agent-contract-log.ts';
+import { cliRouting, pinRouting, type FixRouting } from './fix-routing.ts';
+
+export const CONTRACT_VERSION = 1 as const;
+
+export type Effect = 'paid' | 'destructive' | 'credentials' | 'egress' | 'persistent_install';
+export type Actor = 'agent' | 'user' | 'host_admin' | 'provider';
+export type Next = 'run' | 'ask_user' | 'tell_user_to_run' | 'wait' | 'report';
+export type Transport = 'cli' | 'stdio' | 'http';
+export type Surface = 'verbs' | 'starter' | 'full';
+export type ErrorClass = 'caller' | 'consent' | 'retryable' | 'unavailable' | 'server' | 'host_only';
+
+export interface McpCall { tool: string; arguments: Record<string, unknown> }
+
+/** A value the agent must obtain before running (e.g. a model's price). argv holds `<name>` only for these. */
+export interface ActionInput { name: string; how: string }
+
+/** Stored/constructed form. Never carries `next` or `command`: both are computed at render time. */
+export interface Action {
+ argv?: string[];
+ mcp?: McpCall;
+ consent: Effect[];
+ actor: Actor;
+ why: string;
+ user_message?: string;
+ verify?: { argv?: string[]; mcp?: McpCall };
+ docs?: string;
+ requires_exclusive: boolean;
+ inputs?: ActionInput[];
+ plan_hash?: string;
+ preview_argv?: string[];
+ then?: Action;
+}
+
+/** Wire form: what an agent reads. */
+export interface RenderedAction extends Omit<Action, 'then' | 'docs'> {
+ command?: string;
+ next: Next;
+ docs?: string;
+ then?: RenderedAction;
+}
+
+export type NoticeKind = 'safety' | 'degraded' | 'coaching' | 'ask' | 'info';
+export interface DecisionOption { id: string; label: string; argv?: string[] }
+export interface Decision { id: string; question: string; options: DecisionOption[]; default: string; default_reason: string }
+
+export interface Notice {
+ code: string;
+ kind: NoticeKind;
+ why: string;
+ fix?: Action;
+ user_message?: string;
+ decisions?: Decision[];
+}
+export interface RenderedNotice extends Omit<Notice, 'fix'> { fix?: RenderedAction; contract_version: 1 }
+
+/** The one error envelope (CLI --json document, MCP isError content[0], HTTP bodies). */
+export interface AgentEnvelope {
+ error: string;
+ code: string;
+ reason?: string;
+ message: string;
+ suggestion: string;
+ why?: string;
+ fix?: RenderedAction;
+ docs?: string;
+ docs_cmd: string[];
+ class: ErrorClass;
+ retryable: boolean;
+ notices?: RenderedNotice[];
+ contract_version: 1;
+ detail?: string; protocol_version?: 1; write_request?: unknown; write_error?: string;
+}
+
+export interface RenderContext {
+ transport: Transport;
+ surface?: Surface;
+ isCallable(opName: string): boolean;
+ preapproved(effects: Effect[], estUsd?: number | null): boolean;
+ principal?: string;
+ /** A1: the brain/source the failing call acted on; renderAction pins them into gbrain argv (src/core/fix-routing.ts). */
+ routing?: FixRouting;
+}
+
+export interface AgentErrorContext {
+ transport: Transport;
+ op?: string;
+ command?: string;
+ mutating?: boolean;
+ idempotent?: boolean;
+ outcome?: 'not_started' | 'failed' | 'unknown' | 'committed' | 'pending';
+ render: RenderContext;
+ /** Additive: the configured DB url + resolved brain id for the GBRAIN_DB_ACCESS classifier row (a mount never reads as host). */
+ db?: { url: string | null; brainId?: string };
+}
+
+export interface CliErrorRender { stdout?: string; stderr?: string; exitCode: number }
+
+/** Attached to OperationContext (MCP) and the CLI dispatch context. */
+export interface NoticeSink { emitNotice(n: Notice): void }
+
+// ── render context defaults ────────────────────────────────────────────────
+
+/** The trusted local CLI: no MCP tool is callable from a shell, nothing is preapproved unless A4 says so. */
+export function cliRenderContext(overrides: Partial<RenderContext> = {}): RenderContext {
+ const routing = cliRouting();
+ return { transport: 'cli', isCallable: () => false, preapproved: () => false, ...(routing ? { routing } : {}), ...overrides };
+}
+
+// ── text safety ────────────────────────────────────────────────────────────
+
+const MARKER_RE = /\[(\/?)(AGENT|SHOW USER|gbrain notice)/gi;
+const MAX_INLINE = 2_000;
+
+/**
+ * Neutralise interpolated text for any agent-visible channel: newlines become
+ * spaces and marker tokens lose their opening bracket, so `[/SHOW USER]` in a
+ * page title renders as `(/SHOW USER]` and cannot close or open a block.
+ */
+export function inertText(value: string, max: number = MAX_INLINE): string {
+ const flat = value.replace(/\r\n|\r|\n|\u2028|\u2029/g, ' ').replace(MARKER_RE, '($1$2');
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
+}
+
+const SAFE_SHELL = /^[A-Za-z0-9_@%+=:,./-]+$/;
+
+/** POSIX shell quoting; the only way a human `command` string is built. */
+export function shellQuote(argv: readonly string[]): string {
+ return argv.map(arg => {
+ if (arg === '') return "''";
+ if (SAFE_SHELL.test(arg)) return arg;
+ return `'${inertText(arg).replace(/'/g, `'\\''`)}'`;
+ }).join(' ');
+}
+
+/**
+ * Split a literal shell command that a legacy site stored as a string (F0's
+ * refusal `fix`, a `suggestion` that is exactly one command) into argv. Only
+ * `gbrain …` commands made of plain or single-quoted words qualify; anything
+ * with pipes, substitutions or placeholders returns undefined (prose stays prose).
+ */
+export function argvFromCommand(command: string): string[] | undefined {
+ const s = command.trim().replace(/^`|`$/g, '');
+ if (!s.startsWith('gbrain ') && s !== 'gbrain') return undefined;
+ const out: string[] = [];
+ const re = /\s*(?:'([^']*)'|([^\s'"`$|;&<>()\\]+))/y;
+ let i = 0;
+ while (i < s.length) {
+ re.lastIndex = i;
+ const m = re.exec(s);
+ if (!m) return undefined;
+ out.push(m[1] ?? m[2]);
+ i = re.lastIndex;
+ while (i < s.length && s[i] === ' ') i++;
+ }
+ return out.length ? out : undefined;
+}
+
+/** `no_pull: true` on MCP, `--no-pull` on the CLI. */
+export function paramRef(ctx: { transport: Transport }, param: string): string {
+ return ctx.transport === 'cli' ? `--${param.replace(/_/g, '-')}` : `${param}: true`;
+}
+
+// ── docs URLs ──────────────────────────────────────────────────────────────
+
+const REPO_BLOB = 'https://github.com/garrytan/gbrain/blob';
+let docsRefOverride: string | null = null;
+
+/** Test seam: pin the ref docsUrl() uses (null restores detection). */
+export function __setDocsRefForTests(ref: string | null): void { docsRefOverride = ref; }
+
+function docsRef(): string {
+ if (docsRefOverride !== null) return docsRefOverride;
+ const root = join(import.meta.dir, '..', '..');
+ return existsSync(join(root, '.git')) ? 'master' : `v${VERSION}`;
+}
+
+/**
+ * Absolute docs URL for a repo-relative anchor (`docs/guides/x.md#y`).
+ * Published package → the `v<VERSION>` tag; source checkout → `master`;
+ * `LLMS_REPO_BASE` (fork override, same knob as build:llms) wins.
+ */
+export function docsUrl(anchor: string): string {
+ if (/^https?:\/\//.test(anchor)) return anchor;
+ const path = anchor.replace(/^\.?\//, '');
+ const forkBase = process.env.LLMS_REPO_BASE?.replace(/\/+$/, '');
+ return forkBase ? `${forkBase}/${path}` : `${REPO_BLOB}/${docsRef()}/${path}`;
+}
+
+// ── next + rendering ───────────────────────────────────────────────────────
+
+/** The published decision table (first matching row wins). */
+export function deriveNext(a: Action, ctx: RenderContext): Next {
+ const callableMcp = a.mcp !== undefined && ctx.isCallable(a.mcp.tool);
+ const mcpOnlyOnCli = ctx.transport === 'cli' && !a.argv?.length && a.mcp !== undefined && !callableMcp;
+ if (!a.argv?.length && !callableMcp && !mcpOnlyOnCli) return 'report';
+ if (a.actor === 'provider') return 'wait';
+ if (a.actor === 'user' || a.actor === 'host_admin' || mcpOnlyOnCli) return 'tell_user_to_run';
+ if (ctx.transport !== 'cli' && !callableMcp) return 'tell_user_to_run';
+ if (a.consent.length > 0 && (a.consent.includes('destructive') || !ctx.preapproved(a.consent))) return 'ask_user';
+ return 'run';
+}
+
+function renderVerify(v: Action['verify'], ctx: RenderContext): RenderedAction['verify'] {
+ if (!v) return undefined;
+ const mcp = v.mcp && ctx.isCallable(v.mcp.tool) ? v.mcp : undefined;
+ if (!v.argv && !mcp) return undefined;
+ return { ...(v.argv ? { argv: pinRouting(v.argv, ctx.routing, { remote: ctx.transport === 'http' }) } : {}), ...(mcp ? { mcp } : {}) };
+}
+
+/** Render an Action for the caller's surface. Key order is part of the v1 goldens. */
+export function renderAction(a: Action, ctx: RenderContext): RenderedAction {
+ const callable = a.mcp && ctx.isCallable(a.mcp.tool) ? a.mcp : undefined;
+ const cliOnlyOnMcp = ctx.transport !== 'cli' && !callable && a.actor === 'agent' && !!a.argv?.length;
+ // The mirror case: an MCP-only fix on the CLI (a remote server's fix on a thin client) is kept as
+ // relay data, not dropped: the user (or their MCP client) calls the tool; the CLI cannot.
+ const relay = ctx.transport === 'cli' && !callable && !a.argv?.length && a.mcp ? a.mcp : undefined;
+ const mcp = callable ?? relay;
+ const actor: Actor = cliOnlyOnMcp ? (ctx.transport === 'http' ? 'host_admin' : 'user') : relay && a.actor === 'agent' ? 'user' : a.actor;
+ const effective: Action = { ...a, mcp, actor };
+ const userMessage = a.user_message ?? (relay ? `Call the ${relay.tool} tool over MCP with ${JSON.stringify(relay.arguments)}; this command line cannot call it.` : undefined);
+ const verify = renderVerify(a.verify, ctx);
+ const remote = { remote: ctx.transport === 'http' };
+ const argv = a.argv ? pinRouting(a.argv, ctx.routing, remote) : undefined;
+ const out: RenderedAction = {
+ ...(argv ? { argv, command: shellQuote(argv) } : {}),
+ ...(mcp ? { mcp } : {}),
+ consent: a.consent,
+ actor,
+ next: deriveNext(effective, ctx),
+ why: inertText(a.why),
+ ...(userMessage !== undefined ? { user_message: inertText(userMessage) } : {}),
+ ...(verify ? { verify } : {}),
+ ...(a.docs ? { docs: docsUrl(a.docs) } : {}),
+ requires_exclusive: a.requires_exclusive,
+ ...(a.inputs?.length ? { inputs: a.inputs } : {}),
+ ...(a.plan_hash ? { plan_hash: a.plan_hash } : {}),
+ ...(a.preview_argv ? { preview_argv: pinRouting(a.preview_argv, ctx.routing, remote) } : {}),
+ ...(a.then ? { then: renderAction(a.then, ctx) } : {}),
+ };
+ return out;
+}
+
+export function renderNotice(n: Notice, ctx: RenderContext): RenderedNotice {
+ return {
+ code: n.code,
+ kind: n.kind,
+ why: inertText(n.why),
+ ...(n.fix ? { fix: renderAction(n.fix, ctx) } : {}),
+ ...(n.user_message !== undefined ? { user_message: inertText(n.user_message) } : {}),
+ ...(n.decisions?.length ? { decisions: n.decisions } : {}),
+ contract_version: CONTRACT_VERSION,
+ };
+}
+
+export const NOTICE_PREFIX = '[gbrain notice ';
+const NOTICE_KIND_ORDER: readonly NoticeKind[] = ['safety', 'degraded', 'ask', 'coaching', 'info'];
+
+/** Stable order for notice blocks: safety, degraded, ask, coaching, info. */
+export function orderNotices<T extends { kind: NoticeKind }>(notices: readonly T[]): T[] {
+ return [...notices].sort((a, b) => NOTICE_KIND_ORDER.indexOf(a.kind) - NOTICE_KIND_ORDER.indexOf(b.kind));
+}
+
+function renderedStep(fix: RenderedAction): string | undefined {
+ if (fix.mcp) return `${fix.mcp.tool} ${JSON.stringify(fix.mcp.arguments)}`;
+ return fix.command;
+}
+
+/** The MCP extra text block for one notice. First line is the fixed prefix clients key on. */
+export function noticeBlock(n: RenderedNotice): string {
+ const lines = [`${NOTICE_PREFIX}${n.code} kind=${n.kind}]`, `why: ${n.why}`];
+ if (n.fix) {
+ const step = renderedStep(n.fix);
+ if (step) lines.push(`fix: ${step}`);
+ lines.push(`next: ${n.fix.next}`);
+ }
+ if (n.user_message) lines.push(`user_message: ${n.user_message}`);
+ for (const d of n.decisions ?? []) {
+ lines.push(`decision ${d.id}: ${inertText(d.question)} (default: ${d.default})`);
+ }
+ return lines.join('\n');
+}
+
+// ── HTTP view ──────────────────────────────────────────────────────────────
+
+const HTTP_DROP_KEYS = new Set(['pid', 'lock_owner', 'path', 'data_dir', 'database_path', 'asset']);
+const ABS_PATH_RE = /(?:^|(?<=[\s'"`(=]))(?:\/(?:home|Users|root|tmp|var|private|opt|srv|mnt|etc)\/[^\s'"`)]*|[A-Za-z]:\\[^\s'"`)]*|~\/[^\s'"`)]*)/g;
+const PID_RE = /\b(PID|pid)\s*[:=]?\s*\d+/g;
+const KEY_NAME_RE = /\b[A-Z][A-Z0-9]*_(?:API_KEY|TOKEN|SECRET)\b/g;
+
+function redactString(s: string): string {
+ return s.replace(ABS_PATH_RE, '<path>').replace(PID_RE, '$1 <redacted>').replace(KEY_NAME_RE, '<provider key>');
+}
+
+/** One transport-keyed redaction pass: http strips local paths, PIDs, key names and host posture keys. */
+export function redactForTransport<T>(value: T, transport: Transport): T {
+ if (transport !== 'http') return value;
+ const walk = (v: unknown): unknown => {
+ if (typeof v === 'string') return redactString(v);
+ if (Array.isArray(v)) return v.map(walk);
+ if (v && typeof v === 'object') {
+ const out: Record<string, unknown> = {};
+ for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
+ if (HTTP_DROP_KEYS.has(k)) continue;
+ out[k] = walk(val);
+ }
+ return out;
+ }
+ return v;
+ };
+ return walk(value) as T;
+}
+
+// ── envelope ───────────────────────────────────────────────────────────────
+
+/** Fields a normaliser row extracts before the shared envelope assembly. */
+export interface EnvelopeParts {
+ error: string;
+ code: string;
+ message: string;
+ suggestion?: string;
+ reason?: string;
+ why?: string;
+ fix?: Action;
+ docs?: string;
+ notices?: Notice[];
+ detail?: string;
+ protocol_version?: 1;
+ write_request?: unknown;
+ write_error?: string;
+ retryable?: boolean;
+}
+
+/** Replace each occurrence of `bare` that is a whole command (not followed by a word, path or more flags). */
+function replaceWholeCommand(text: string, bare: string, step: string): string {
+ let out = '';
+ let from = 0;
+ for (let at = text.indexOf(bare); at >= 0; at = text.indexOf(bare, at + bare.length)) {
+ const rest = text.slice(at + bare.length);
+ if (/^[\w/-]/.test(rest) || /^\s+-/.test(rest)) continue;
+ out += text.slice(from, at) + step;
+ from = at + bare.length;
+ }
+ return from === 0 ? text : out + text.slice(from);
+}
+
+function appendFixToSuggestion(suggestion: string, fix: RenderedAction | undefined, unpinned?: readonly string[]): string {
+ if (!fix) return suggestion;
+ const step = renderedStep(fix);
+ if (!step || suggestion.includes(step)) return suggestion;
+ // Prose that already quotes the fix before its A1 routing pin quotes the pinned command instead (never both).
+ const bare = unpinned?.length && !fix.mcp ? shellQuote(unpinned) : undefined;
+ if (bare && bare !== step) {
+ const replaced = replaceWholeCommand(suggestion, bare, step);
+ if (replaced !== suggestion) return replaced;
+ }
+ const prose = suggestion.trim();
+ return prose ? `${prose.replace(/[.\s]*$/, '.')} Next: ${step}` : `Next: ${step}`;
+}
+
+/** Assemble the envelope from normalised parts. Legacy keys first, in their historical order. */
+export function buildEnvelope(p: EnvelopeParts, ctx: RenderContext): AgentEnvelope {
+ const entry = codeEntry(p.code);
+ const fix = p.fix ? renderAction(p.fix, ctx) : undefined;
+ const suggestion = appendFixToSuggestion(p.suggestion ?? entry?.suggestion ?? '', fix, p.fix?.argv);
+ const docs = p.docs ?? entry?.docs ?? `docs/guides/error-codes.md#${p.code}`;
+ const notices = p.notices?.length ? orderNotices(p.notices).map(n => renderNotice(n, ctx)) : undefined;
+ return {
+ error: p.error,
+ code: p.code,
+ message: p.message,
+ suggestion,
+ docs: docsUrl(docs),
+ ...(p.detail !== undefined ? { detail: p.detail } : {}),
+ ...(p.protocol_version !== undefined ? { protocol_version: p.protocol_version } : {}),
+ ...(p.write_request !== undefined ? { write_request: p.write_request } : {}),
+ ...(p.write_error !== undefined ? { write_error: p.write_error } : {}),
+ ...(p.reason !== undefined ? { reason: p.reason } : {}),
+ ...(p.why !== undefined ? { why: p.why } : {}),
+ ...(fix ? { fix } : {}),
+ docs_cmd: ['gbrain', 'errors', p.code],
+ class: codeClass(p.code),
+ retryable: p.retryable ?? codeRetryable(p.code),
+ ...(notices ? { notices } : {}),
+ contract_version: CONTRACT_VERSION,
+ };
+}
+
+const VERB_SET: ReadonlySet<string> = new Set(VERB_NAMES);
+const isVerbOp = (ctx: AgentErrorContext) => ctx.op !== undefined && VERB_SET.has(ctx.op);
+
+/** The registry's diagnostic default: doctor on the brain host (MCP run_doctor where callable). */
+function diagnosticFix(ctx: AgentErrorContext, why: string): Action {
+ const remoteHost = ctx.transport === 'http';
+ return {
+ argv: ['gbrain', 'doctor', '--json'],
+ ...(ctx.render.isCallable('run_doctor') ? { mcp: { tool: 'run_doctor', arguments: {} } } : {}),
+ consent: [],
+ actor: remoteHost ? 'host_admin' : 'agent',
+ why,
+ requires_exclusive: false,
+ };
+}
+
+/** The journal fields a receipt-bearing error carries (OperationError.receiptFields), never serialized. */
+type ReceiptFields = NonNullable<OperationError['receiptFields']>;
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const TEMPLATE_VALUE: Record<string, RegExp> = {
+ slug: /^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,511}$/,
+ source_id: /^[a-z0-9][a-z0-9_-]{0,63}$/i,
+ request_id: UUID_RE,
+ operation: /^[a-z][a-z0-9_]{0,63}$/,
+};
+
+/**
+ * Fill a registry fix template (`{slug}`, `{source_id}`, `{request_id}`,
+ * `{operation}`) from envelope/receipt fields. Every value must pass its strict
+ * id pattern; one missing or unsafe value drops the whole template (B4, A1
+ * argv safety), so no placeholder ever reaches the wire.
+ */
+export function fillFixTemplate(template: Action, fields: Record<string, string | null | undefined>): Action | undefined {
+ let ok = true;
+ const fill = (v: string): string => v.replace(/\{([a-z_]+)\}/g, (_m, key: string) => {
+ const value = fields[key];
+ if (typeof value !== 'string' || !TEMPLATE_VALUE[key]?.test(value)) { ok = false; return ''; }
+ return value;
+ });
+ const args = (a: Record<string, unknown>) => Object.fromEntries(Object.entries(a).map(([k, v]) => [k, typeof v === 'string' ? fill(v) : v]));
+ const filled: Action = {
+ ...template,
+ ...(template.argv ? { argv: template.argv.map(fill) } : {}),
+ ...(template.mcp ? { mcp: { tool: template.mcp.tool, arguments: args(template.mcp.arguments) } } : {}),
+ };
+ return ok ? filled : undefined;
+}
+
+/** The registry default fix for a code, filled from the fields this error carries (undefined when it has none or cannot be filled). */
+function registryTemplateFix(code: string, fields: Record<string, string | null | undefined> | undefined): Action | undefined {
+ const template = codeEntry(code)?.fix;
+ if (!template || !fields) return undefined;
+ return fillFixTemplate(template, fields);
+}
+
+const RECEIPT_CHANNEL: Record<Transport, string> = { cli: 'local_cli', stdio: 'local_stdio', http: '' };
+
+/**
+ * A1 safe-recovery invariant, principal-aware: a write with an unknown or
+ * pending outcome, or a replayed terminal receipt, is never told to retry. The
+ * fix reads the receipt on the channel that owns it: `gbrain write-request` on
+ * the CLI for a CLI-principal receipt, `get_write_request` over MCP where it is
+ * callable for this principal; another principal's receipt (or no callable
+ * receipt tool) gets the separately authorized host inspection, actor
+ * host_admin. No receipt → no receipt command.
+ */
+function recoveryFix(p: EnvelopeParts, ctx: AgentErrorContext, fields?: ReceiptFields): Action | undefined {
+ const outcomeOpen = ctx.outcome === 'unknown' || ctx.outcome === 'pending';
+ if (!fields && (!ctx.mutating || !outcomeOpen)) return undefined;
+ const receipt = p.write_request as { request_id?: unknown; state?: unknown } | undefined;
+ const requestId = typeof receipt?.request_id === 'string' && UUID_RE.test(receipt.request_id) ? receipt.request_id : undefined;
+ if (!requestId) return undefined;
+ const terminal = typeof receipt?.state === 'string' && ['committed', 'conflict', 'failed', 'cancelled'].includes(receipt.state);
+ const why = terminal
+ ? 'The receipt is final; read it (and the target) before deciding whether a new write is needed.'
+ : 'The write may still commit; its receipt says whether it did. Do not resubmit until the receipt is terminal.';
+ const owner = fields?.principal_kind;
+ const samePrincipal = owner !== 'oauth_client' || !ctx.render.principal || fields?.principal_id === ctx.render.principal;
+ const ownChannel = owner === undefined || samePrincipal && (ctx.transport === 'http' ? !owner.startsWith('local_') : owner === RECEIPT_CHANNEL[ctx.transport]);
+ if (ownChannel && ctx.transport === 'cli') {
+ return { argv: ['gbrain', 'write-request', '--', requestId], consent: [], actor: 'agent', why, requires_exclusive: false };
+ }
+ if (ownChannel && ctx.render.isCallable('get_write_request')) {
+ return { mcp: { tool: 'get_write_request', arguments: { request_id: requestId } }, consent: [], actor: 'agent', why, requires_exclusive: false };
+ }
+ const source = fields && TEMPLATE_VALUE.source_id!.test(fields.source_id) ? [fields.source_id] : [];
+ return {
+ argv: ['gbrain', 'sources', 'writer', 'status', ...source, '--probe', '--json'],
+ consent: [], actor: 'host_admin',
+ why: `${why} This connection cannot read that receipt itself, so the brain host's operator inspects the write on the owner.`,
+ user_message: 'A write gbrain accepted needs a check on the brain host before anything is resubmitted. Please ask whoever runs this brain to run the command shown.',
+ requires_exclusive: false,
+ };
+}
+
+const REFRESH_REFUSALS: ReadonlySet<string> = new Set([
+ 'refresh_not_managed', 'refresh_not_owner', 'refresh_no_upstream', 'fetch_failed', 'refresh_diverged', 'refresh_dirty',
+ 'sync_in_progress', 'refresh_in_progress', 'refresh_drain_timeout', 'refresh_source_changed', 'refresh_recovery_required',
+ 'worktree_refreshing',
+]);
+
+type Row = { match: (e: unknown) => boolean; map: (e: any, ctx: AgentErrorContext) => EnvelopeParts };
+
+/** RemoteMcpError transport reasons (no server envelope) → registry codes. */
+const REMOTE_REASON_CODE: Record<string, string> = {
+ config: 'config_error', discovery: 'unavailable', auth: 'invalid_token', auth_after_refresh: 'invalid_token',
+ rate_limited: 'rate_limited', token: 'unavailable',
+ 'network:timeout': 'timeout', 'network:aborted': 'interrupted', parse: 'internal_error',
+};
+
+const named = (name: string) => (e: unknown) => e instanceof Error && e.name === name;
+
+/** The normaliser table: first matching row wins; the last row is the unknown-throw fallback. */
+const ROWS: Row[] = [
+ {
+ match: e => e instanceof OperationError,
+ map: (e: OperationError, ctx) => {
+ const j = e.toJSON() as Record<string, unknown>;
+ const receiptId = (j.write_request as { request_id?: string } | undefined)?.request_id;
+ let fix = e.fix ?? registryTemplateFix(e.canonicalCode, e.receiptFields ? { ...e.receiptFields, request_id: receiptId } : undefined);
+ if (!fix && REFRESH_REFUSALS.has(e.code) && e.suggestion) {
+ const argv = argvFromCommand(e.suggestion);
+ if (argv) fix = { argv, consent: [], actor: 'agent', why: e.message, requires_exclusive: false };
+ }
+ return {
+ error: e.code, code: canonicalCodeFor(e.canonicalCode), message: e.message, suggestion: e.suggestion,
+ reason: e.reason, why: e.why, fix, docs: e.docs, notices: e.notices, detail: e.detail,
+ protocol_version: e.protocolVersion === 1 ? 1 : undefined,
+ write_request: j.write_request, write_error: e.writeError,
+ };
+ },
+ },
+ {
+ match: e => e instanceof StructuredAgentError,
+ map: (e: StructuredAgentError) => ({
+ error: e.envelope.code, code: canonicalCodeFor(e.envelope.code), message: e.envelope.message,
+ suggestion: e.envelope.hint, docs: e.envelope.docs_url,
+ }),
+ },
+ {
+ match: e => e instanceof Error && (e as { tag?: unknown }).tag === 'BUDGET_EXHAUSTED',
+ map: (e: Error & { reason: string; cap: number; pricing?: { model: string; units: string[]; lookup: string; register_command: string } }, ctx) => {
+ if (e.reason !== 'no_pricing' || !e.pricing) {
+ return { error: 'cost_cap_exceeded', code: 'cost_cap_exceeded', message: e.message, reason: e.reason };
+ }
+ const argv = argvFromPricing(e.pricing.register_command);
+ return {
+ error: 'no_pricing', code: 'no_pricing', message: e.message, reason: 'no_pricing',
+ suggestion: e.pricing.lookup,
+ fix: argv ? {
+ argv, consent: [], actor: ctx.transport === 'cli' ? 'agent' : 'host_admin',
+ why: 'A cost cap needs a price for every model it covers; registering the rate lets the cap be enforced.',
+ requires_exclusive: false,
+ inputs: e.pricing.units.map(u => ({ name: u, how: e.pricing!.lookup })),
+ } : undefined,
+ };
+ },
+ },
+ {
+ match: named('RemoteMcpError'),
+ map: (e: Error & { reason: string; detail?: Record<string, unknown> }) => {
+ const d = e.detail ?? {};
+ const wire = typeof d.code === 'string' ? d.code : REMOTE_REASON_CODE[e.reason === 'network' ? `network:${String(d.kind)}` : e.reason] ?? 'unavailable';
+ const remoteCode = typeof d.canonical_code === 'string' ? d.canonical_code : canonicalCodeFor(wire);
+ return {
+ error: wire, code: remoteCode, message: typeof d.message === 'string' ? d.message : e.message,
+ suggestion: typeof d.suggestion === 'string' ? d.suggestion : undefined,
+ reason: typeof d.reason === 'string' ? d.reason : undefined,
+ why: typeof d.why === 'string' ? d.why : undefined,
+ docs: typeof d.docs === 'string' ? d.docs : undefined,
+ detail: typeof d.server_detail === 'string' ? d.server_detail : undefined,
+ protocol_version: d.protocol_version === 1 ? 1 : undefined,
+ write_request: d.write_request, write_error: typeof d.write_error === 'string' ? d.write_error : undefined,
+ notices: Array.isArray(d.notices) ? d.notices as Notice[] : undefined,
+ fix: d.fix && typeof d.fix === 'object' ? d.fix as Action
+ : e.reason !== 'tool_error' ? { argv: ['gbrain', 'remote', 'doctor'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'remote doctor checks the remote brain URL, OAuth discovery and credentials from this machine.' } : undefined,
+ };
+ },
+ },
+ {
+ // The local persistence owner's IPC lane: unreachable (not sent) or the acknowledgment was lost (outcome unknown).
+ match: named('PersistenceIpcTransportError'),
+ map: (e: Error & { sent: boolean; requestId?: string; toJSON(): { suggestion: string } }) => {
+ const requestId = e.requestId && UUID_RE.test(e.requestId) ? e.requestId : undefined;
+ return {
+ error: 'owner_unavailable', code: 'owner_unavailable', message: e.message, suggestion: e.toJSON().suggestion,
+ ...(e.sent ? { reason: 'outcome_unknown', retryable: false } : { reason: 'not_sent' }),
+ fix: e.sent && requestId
+ ? { argv: ['gbrain', 'write-request', '--', requestId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The write may have committed before the acknowledgment was lost; its receipt says whether it did. Do not resubmit until it is terminal.' }
+ : { argv: ['gbrain', 'sources', 'writer', 'status', '--probe', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows whether the brain\'s persistence owner is running and reachable before anything is repeated.' },
+ };
+ },
+ },
+ {
+ match: named('EmbeddingDisabledError'),
+ map: (e: Error & { fix?: Action }) => ({
+ error: 'embedding_disabled', code: 'embedding_disabled', reason: 'disabled_by_choice',
+ message: e.message.split('\n')[0]!, why: e.fix?.why, fix: e.fix,
+ suggestion: 'Embeddings are off by choice on this brain; keyword search still works. Turning them on needs the user\'s consent.',
+ }),
+ },
+ {
+ 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,
+ }),
+ },
+ {
+ // source-resolver: a caller-selected source (--source, GBRAIN_SOURCE) that is malformed, unregistered or archived.
+ match: named('SourceTargetError'),
+ map: (e: Error) => {
+ const code = e.message.startsWith('Invalid ') ? 'invalid_source' : 'unknown_source';
+ return {
+ error: code, code, message: e.message,
+ suggestion: 'Pass a registered, active source id with --source or GBRAIN_SOURCE (or unset it for the default source); `gbrain sources list --json` shows them.',
+ fix: {
+ argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Lists the source ids this brain has, so the next call can name one that exists.',
+ },
+ };
+ },
+ },
+ {
+ // 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),
+ map: (e: Error & { fix?: string }) => ({
+ error: 'unavailable', code: 'unavailable', message: e.message,
+ reason: e.name === 'AIConfigError' ? 'ai_config' : 'ai_transient',
+ suggestion: e.fix, retryable: e.name === 'AITransientError',
+ }),
+ },
+ {
+ match: named('GBrainError'),
+ map: (e: Error & { problem: string; cause_description: string; fix: string; docs_url?: string }) => ({
+ error: 'config_error', code: 'config_error', message: e.problem,
+ why: e.cause_description || undefined, suggestion: e.fix, docs: e.docs_url,
+ }),
+ },
+ {
+ match: e => !(e instanceof Error) && !!e && typeof e === 'object'
+ && typeof (e as Record<string, unknown>).code === 'string' && typeof (e as Record<string, unknown>).message === 'string'
+ && typeof (e as Record<string, unknown>).class === 'string',
+ map: (e: { class: string; code: string; message: string; hint?: string }) => ({
+ error: e.code, code: canonicalCodeFor(e.code), message: e.message, suggestion: e.hint,
+ }),
+ },
+];
+
+/**
+ * A1 safe recovery for non-journaled mutations: when the outcome is unknown
+ * (no receipt, a failure that may have struck after the work was accepted),
+ * the fix is the op's own status read, never a resubmit.
+ */
+const STATUS_READ: Readonly<Record<string, Action>> = {
+ submit_job: {
+ argv: ['gbrain', 'jobs', 'list', '--json'], mcp: { tool: 'list_jobs', arguments: {} }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The job may have been queued before the failure; the job list shows whether it was before anything is resubmitted.',
+ },
+};
+const OUTCOME_UNKNOWN_CLASSES: ReadonlySet<ErrorClass> = new Set(['server', 'unavailable', 'retryable']);
+
+function statusReadFix(ctx: AgentErrorContext): Action | undefined {
+ const open = ctx.outcome === 'unknown' || ctx.outcome === 'pending';
+ return ctx.op && ctx.mutating && open ? STATUS_READ[ctx.op] : undefined;
+}
+
+/** Index of the first generic row (AIConfigError); rows before it are typed and beat the DB classifier. */
+const FIRST_GENERIC_ROW = ROWS.findIndex(r => r.match(Object.assign(new Error('x'), { name: 'AIConfigError' })));
+
+function argvFromPricing(command: string): string[] | undefined {
+ const s = command.replace(/<([a-z0-9-]+)>/gi, 'PLACEHOLDER_$1');
+ const argv = argvFromCommand(s);
+ return argv?.map(a => a.replace(/^PLACEHOLDER_(.+)$/, '<$1>'));
+}
+
+function dbParts(e: unknown, ctx: AgentErrorContext): EnvelopeParts | undefined {
+ const d = classifyPgAccessError(e, { url: ctx.db?.url ?? null, brainId: ctx.db?.brainId });
+ if (d.reason === 'unknown') return undefined;
+ const verb = isVerbOp(ctx);
+ if (d.reason === 'schema_missing') {
+ return {
+ error: 'unavailable', code: 'unavailable', reason: 'schema_missing', message: d.message,
+ suggestion: 'Run gbrain apply-migrations on the brain host, then retry.',
+ fix: {
+ argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent',
+ why: 'The code expects a table or column this brain does not have yet.', requires_exclusive: true,
+ verify: { argv: ['gbrain', 'doctor', '--json'] },
+ },
+ ...(verb ? { detail: 'schema_missing', protocol_version: 1 as const } : {}),
+ };
+ }
+ return {
+ error: verb ? 'unavailable' : 'database_error', code: verb ? 'unavailable' : 'database_error', reason: d.reason,
+ message: d.message, suggestion: `${formatDbAccessMarker(d)}. ${d.remediation} Run: gbrain db-repair`,
+ fix: {
+ argv: ['gbrain', 'db-repair'], consent: [], actor: 'agent',
+ why: 'db-repair diagnoses the database connection without changing anything.', requires_exclusive: false,
+ },
+ ...(verb ? { detail: d.reason, protocol_version: 1 as const } : {}),
+ };
+}
+
+function unknownParts(e: unknown, ctx: AgentErrorContext): EnvelopeParts {
+ const raw = e instanceof Error ? e.message : String(e);
+ let message = raw;
+ try { message = redactUrlsInText(redactConnectionInfo(raw)); } catch { /* keep raw */ }
+ const where = ctx.op ?? ctx.command ?? 'this operation';
+ const verb = isVerbOp(ctx);
+ const resubmit = ctx.mutating ? ' The write may have partly run: inspect state before resubmitting.' : '';
+ return {
+ error: verb ? 'internal' : 'internal_error', code: verb ? 'internal' : 'internal_error',
+ message: redactForTransport(message, ctx.transport),
+ suggestion: `Server-side failure in ${where}, not a caller mistake.${resubmit} Run \`gbrain doctor --json\` on the brain host; if it repeats, report it to the user.`,
+ fix: statusReadFix(ctx) ?? diagnosticFix(ctx, 'Doctor checks the brain host for the failing dependency.'),
+ ...(verb ? { protocol_version: 1 as const } : {}),
+ };
+}
+
+function genericEnvelope(e: unknown, ctx: AgentErrorContext): AgentEnvelope {
+ let message = 'unclassified failure';
+ try { message = e instanceof Error ? e.message : String(e); } catch { /* hostile value: keep the placeholder */ }
+ const where = ctx.op ?? ctx.command ?? 'this operation';
+ return {
+ error: 'internal_error', code: 'internal_error', message: redactUrlsInText(redactConnectionInfo(redactForTransport(message, ctx.transport))),
+ suggestion: `Server-side failure in ${where}, not a caller mistake. Run \`gbrain doctor --json\` on the brain host; if it repeats, report it to the user.`,
+ docs_cmd: ['gbrain', 'errors', 'internal_error'], class: 'server', retryable: false, contract_version: CONTRACT_VERSION,
+ };
+}
+
+/** Total: never throws; on an internal fault returns the prior generic envelope and logs the class (E11). */
+export function toAgentError(e: unknown, ctx: AgentErrorContext): AgentEnvelope {
+ try {
+ // Typed rows first (OperationError … CredentialError); then the DB-access
+ // classifier, which must win over the generic GBrainError/AI/phase rows
+ // (a connect failure is often a GBrainError); then the unknown fallback.
+ const row = ROWS.find(r => r.match(e));
+ const typed = row && ROWS.indexOf(row) < FIRST_GENERIC_ROW;
+ let parts = typed ? row.map(e, ctx) : dbParts(e, ctx) ?? (row ? row.map(e, ctx) : unknownParts(e, ctx));
+ if (!parts.fix) {
+ const recovery = recoveryFix(parts, ctx, e instanceof OperationError ? e.receiptFields : undefined);
+ if (recovery) parts = { ...parts, fix: recovery };
+ }
+ if (!parts.fix && OUTCOME_UNKNOWN_CLASSES.has(codeClass(parts.code))) {
+ const status = statusReadFix(ctx);
+ if (status) parts = { ...parts, fix: status };
+ }
+ if (!parts.fix && (codeClass(parts.code) === 'server' || codeClass(parts.code) === 'unavailable')) {
+ parts = { ...parts, fix: diagnosticFix(ctx, 'Doctor reports what is missing or failing on the brain host.') };
+ }
+ if (ctx.mutating === true && ctx.idempotent !== true) parts = { ...parts, retryable: false };
+ const env = buildEnvelope(parts, ctx.render);
+ if (env.code === 'internal_error' || env.code === 'internal' || !env.suggestion) {
+ recordAgentContractEvent({ transport: ctx.transport, op: ctx.op, command: ctx.command, code: env.code, has_suggestion: !!env.suggestion, outcome: ctx.outcome });
+ }
+ return ctx.transport === 'http' ? redactForTransport(env, 'http') : env;
+ } catch (fault) {
+ recordAgentContractEvent({
+ transport: ctx.transport, op: ctx.op, command: ctx.command, code: 'internal_error',
+ fault: fault instanceof Error ? fault.name : typeof fault,
+ });
+ return genericEnvelope(e, ctx);
+ }
+}
+
+/** Pure: callers write the strings. TTY order: `Error [code]: msg` / `Fix:` / `Why:` / `Docs:`. */
+export function renderCliError(e: unknown, opts: { json: boolean; command: string; tty: boolean }): CliErrorRender {
+ const env = toAgentError(e, { transport: 'cli', command: opts.command, render: cliRenderContext() });
+ const exitCode = exitCodeForCode(env.code);
+ if (opts.json) return { stdout: `${JSON.stringify(env, null, 2)}\n`, exitCode };
+ const lines = [`Error [${env.code}]: ${env.message}`];
+ const relay = env.fix && !env.fix.command && env.fix.mcp ? `call ${env.fix.mcp.tool} over MCP with ${JSON.stringify(env.fix.mcp.arguments)}` : undefined;
+ lines.push(`Fix: ${env.fix?.command ?? relay ?? env.suggestion}`);
+ if (env.why) lines.push(`Why: ${env.why}`);
+ if (env.docs) lines.push(`Docs: ${env.docs}`);
+ return { stderr: `${lines.join('\n')}\n`, exitCode };
+}
+
+// ── wire builders shared by dispatch, the CLI and the goldens ──────────────
+
+export interface ToolResultShape {
+ content: { type: 'text'; text: string }[];
+ isError?: boolean;
+ _meta?: Record<string, unknown>;
+}
+
+/**
- * MCP success result: `content[0]` is exactly the pre-v1 body (bare arrays
- * included); each notice is one extra prefixed text block, mirrored rendered
- * under `_meta.gbrain_notices`.
++ * MCP success result: `content[0]` is the pre-v1 body (bare arrays included)
++ * as compact JSON (C2: every result is re-sent on each later turn; error
++ * envelopes stay indented); each notice is one extra prefixed text block,
++ * mirrored rendered under `_meta.gbrain_notices`.
+ */
+export function toolResultWithNotices(result: unknown, notices: readonly Notice[], ctx: RenderContext): ToolResultShape {
- const out: ToolResultShape = { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
++ const out: ToolResultShape = { content: [{ type: 'text', text: JSON.stringify(result) }] };
+ if (notices.length === 0) return out;
+ const rendered = orderNotices(notices).map(n => redactForTransport(renderNotice(n, ctx), ctx.transport));
+ for (const n of rendered) out.content.push({ type: 'text', text: noticeBlock(n) });
+ out._meta = { gbrain_notices: rendered };
+ return out;
+}
+
+/** MCP error result: exactly one content block holding the envelope. */
+export function toolErrorResult(envelope: AgentEnvelope): ToolResultShape {
+ return { content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }], isError: true };
+}
+
+/**
+ * Legacy nested error shapes (`{ error: { class, code, message, hint } }`
+ * from code-def/code-refs, phase containment) keep their nesting and gain the
+ * v1 sibling keys.
+ */
+export function withAgentSiblings<T extends Record<string, unknown>>(
+ legacy: T,
+ parts: { code: string; fix?: Action },
+ ctx: RenderContext,
+): T & { code: string; fix?: RenderedAction; docs_cmd: string[]; contract_version: 1 } {
+ return {
+ ...legacy,
+ code: parts.code,
+ ...(parts.fix ? { fix: renderAction(parts.fix, ctx) } : {}),
+ docs_cmd: ['gbrain', 'errors', parts.code],
+ contract_version: CONTRACT_VERSION,
+ };
+}
+
+/**
+ * `{ error: StructuredError }` (code-def/code-refs/brainstorm `--json`) with
+ * the v1 siblings: canonical `code`, an optional diagnostic `fix`, docs_cmd.
+ */
+export function legacyNestedErrorDocument(envelope: { code: string }, fixArgv?: string[]): Record<string, unknown> {
+ return withAgentSiblings({ error: envelope }, {
+ code: canonicalCodeFor(envelope.code),
+ ...(fixArgv ? { fix: { argv: fixArgv, consent: [], actor: 'agent' as const, why: 'Shows the arguments this command needs.', requires_exclusive: false } } : {}),
+ }, cliRenderContext());
+}
+
+/** The `--json` exit-time fallback document: a non-zero exit that wrote no final document. */
+export function fallbackJsonDocument(exitCode: number, lastCode?: string): Record<string, unknown> {
+ return {
+ error: 'command_failed',
+ code: lastCode ?? 'command_failed',
+ message: `The command exited with status ${exitCode} without writing its JSON result.`,
+ suggestion: 'Re-run without --json to read the error on stderr, or run `gbrain doctor --json`.',
+ exit_code: exitCode,
+ contract_version: CONTRACT_VERSION,
+ };
+}
+
+__registerOperationErrorRenderer({
+ fix: a => renderAction(a, cliRenderContext()),
+ notice: n => renderNotice(n, cliRenderContext()),
+});
diff --cc src/core/cli-flag-registry.generated.ts
index e63ffb78c1,42730acd27..445c2927bc
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -23,87 -23,84 +23,87 @@@ export const CLI_FLAG_REGISTRY: Record<
'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'],
- 'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--file', '--follow', '--full', '--fuzzy', '--help', '--http', '--id', '--image', '--include-deleted', '--json', '--kind', '--limit', '--max-turns', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--once', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--refresh-operations', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--types', '--url', '--wait', '--yes'],
- 'book-mirror': ['--accept-pending', '--access', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--fact', '--federated-read', '--follow', '--full', '--help', '--http', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-accept-pending', '--no-confirm', '--no-follow', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--surface', '--take', '--timeline', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--wait', '--yes'],
++ 'book-mirror': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-turns', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--refresh-operations', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--title', '--to', '--url', '--wait', '--yes'],
'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
- 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
+ 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--probe', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
- 'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--dry-run', '--entities', '--federated-read', '--file', '--full', '--fuzzy', '--help', '--holder', '--http', '--id', '--image', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--once', '--page', '--params', '--path', '--phase', '--refresh-operations', '--regenerate', '--scopes', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
- 'calibration': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--fact', '--federated-read', '--full', '--help', '--holder', '--http', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stats', '--surface', '--take', '--timeline', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
++ 'calibration': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--dry-run', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--refresh-operations', '--regenerate', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
- 'capture': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--full', '--fuzzy', '--help', '--http', '--id', '--image', '--include-deleted', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--once', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--refresh-operations', '--request-id', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--to', '--type', '--types', '--url', '--wait', '--what', '--where', '--who', '--yes'],
- 'capture': ['--accept-pending', '--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--fact', '--federated-read', '--file', '--follow', '--force', '--full', '--help', '--http', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--no-accept-pending', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--request-id', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--stdin', '--surface', '--take', '--timeline', '--timeout', '--trusted-extraction', '--type', '--types', '--url', '--wait', '--what', '--where', '--who', '--yes'],
++ 'capture': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--refresh-operations', '--request-id', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--to', '--type', '--url', '--wait', '--what', '--where', '--who', '--yes'],
'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--brain', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],
'claw-test': ['--agent', '--apply', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--version', '--yes'],
- 'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
- 'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
- 'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
- 'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
+ 'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
+ 'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
+ 'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
+ 'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],
'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],
- 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--help', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--out', '--path', '--pattern', '--pglite', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--session', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],
+ 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--harness', '--help', '--http', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--only', '--out', '--path', '--pattern', '--probe', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--suite', '--surface', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],
'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
- 'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days'],
+ 'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
- 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
- 'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
+ 'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],
+ 'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--operations', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
- 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
+ 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
+ 'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
- 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--federated-read', '--file', '--follow', '--force', '--full', '--fuzzy', '--help', '--http', '--id', '--image', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--once', '--order', '--output', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
- 'enrich': ['--accept-pending', '--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fact', '--federated-read', '--follow', '--force', '--full', '--help', '--http', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--no-accept-pending', '--order', '--output', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--reenrich-after', '--resume', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stats', '--status', '--surface', '--take', '--thin', '--thin-threshold', '--timeline', '--timeout', '--trusted-extraction', '--types', '--url', '--wait', '--workers', '--yes'],
- 'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],
++ 'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--order', '--output', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
+ 'errors': ['--brain', '--changed', '--help', '--json', '--source'],
+ 'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
- 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
- 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
+ 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
+ 'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],
- 'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],
+ 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--expect', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],
'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],
'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],
- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--seat', '--session', '--show-current', '--show-toplevel', '--source'],
- 'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-renames', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
+ 'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
+ 'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
- 'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--fact', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--take', '--target', '--thin', '--thin-threshold', '--timeline', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--image', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
++ 'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],
- 'loops': ['--all', '--as-of', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--top', '--type'],
+ 'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
- 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],
- 'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],
+ 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],
+ 'models': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status', '--to'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
- 'onboard': ['--access', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--fact', '--federated-read', '--from-pages', '--full', '--help', '--history', '--http', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slugs', '--source', '--sources', '--stats', '--surface', '--take', '--target-score', '--timeline', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'notices': ['--brain', '--help', '--json', '--source'],
- 'onboard': ['--access', '--add', '--allowed-operations', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--from-pages', '--full', '--fuzzy', '--help', '--history', '--http', '--id', '--image', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--once', '--only', '--page', '--params', '--path', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--types', '--url', '--yes'],
++ 'onboard': ['--access', '--add', '--allowed-operations', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--from-pages', '--full', '--fuzzy', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--url', '--yes'],
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
- 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--vectors', '--yes'],
- 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],
+ 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
- 'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--entities', '--federated-read', '--file', '--full', '--fuzzy', '--help', '--http', '--id', '--image', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--once', '--page', '--params', '--path', '--refresh-operations', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--types', '--url', '--yes'],
- 'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--fact', '--federated-read', '--full', '--help', '--http', '--json', '--kind', '--limit', '--mode', '--multimodal', '--page', '--path', '--session', '--since', '--slugs', '--source', '--sources', '--stats', '--surface', '--synthesize', '--take', '--target', '--timeline', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
++ 'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],
- 'recall': ['--accept-pending', '--access', '--add', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--image', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--once', '--page', '--params', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--refresh-operations', '--request-id', '--rollup', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--supersessions', '--surface', '--timeout', '--to', '--today', '--types', '--url', '--wait', '--watch', '--yes'],
- 'recall': ['--accept-pending', '--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--fact', '--federated-read', '--follow', '--full', '--grep', '--help', '--http', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--no-accept-pending', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stats', '--supersessions', '--surface', '--take', '--timeline', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--wait', '--watch', '--yes'],
++ 'recall': ['--accept-pending', '--access', '--add', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--refresh-operations', '--request-id', '--rollup', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--supersessions', '--surface', '--timeout', '--to', '--today', '--url', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'reindex': ['--accept-pending', '--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
- 'reindex-code': ['--accept-pending', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--wait', '--workers', '--yes'],
- 'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
+ 'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
- 'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],
- 'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],
- 'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
+ 'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--scopes', '--source', '--timeout'],
+ 'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--remediation-plan', '--source', '--stale', '--yes'],
+ 'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
@@@ -122,95 -119,12 +122,95 @@@
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
- 'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
- 'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
+ 'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
- 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
- 'waiting': ['--all', '--as-of', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--top', '--type'],
+ 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
- 'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--full', '--fuzzy', '--help', '--http', '--id', '--image', '--include-deleted', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--once', '--page', '--params', '--path', '--refresh-operations', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--types', '--url', '--yes'],
- 'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--fact', '--federated-read', '--full', '--help', '--http', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--page', '--path', '--session', '--since', '--slugs', '--source', '--sources', '--stats', '--surface', '--take', '--timeline', '--trusted-extraction', '--types', '--url', '--yes'],
++ 'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--url', '--yes'],
+};
+
+// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
+// src/core/fix-routing.ts): '--brain' when the command opens its brain (not a
+// pre-connect command, or its code reads the global brain option); '--source'
+// when the command-table record declares routes_source (consumption-checked).
+export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
+ 'advisor': ['--brain'],
+ 'agent': ['--brain'],
+ 'anomalies': ['--brain'],
+ 'auth': ['--brain'],
+ 'autopilot': ['--brain'],
+ 'backfill': ['--brain'],
+ 'backup': ['--brain'],
+ 'book-mirror': ['--brain'],
+ 'brainstorm': ['--brain'],
+ 'calibration': ['--brain', '--source'],
+ 'call': ['--brain'],
+ 'capture': ['--brain', '--source'],
+ 'code-callees': ['--brain', '--source'],
+ 'code-callers': ['--brain', '--source'],
+ 'code-def': ['--brain', '--source'],
+ 'code-refs': ['--brain', '--source'],
+ 'compile-context': ['--brain', '--source'],
+ 'config': ['--brain'],
+ 'connectors': ['--brain'],
+ 'conversation-parser': ['--brain'],
+ 'db-repair': ['--brain'],
+ 'decide': ['--brain'],
+ 'doctor': ['--brain'],
+ 'dream': ['--brain', '--source'],
+ 'edges-backfill': ['--brain', '--source'],
+ 'embed': ['--brain', '--source'],
+ 'embeddings': ['--brain'],
+ 'enrich': ['--brain', '--source'],
+ 'eval': ['--brain'],
+ 'export': ['--brain', '--source'],
+ 'extract': ['--brain', '--source'],
+ 'extract-conversation-facts': ['--brain'],
+ 'facts': ['--brain', '--source'],
+ 'features': ['--brain'],
+ 'files': ['--brain', '--source'],
+ 'forget': ['--brain'],
+ 'founder': ['--brain'],
+ 'graph-query': ['--brain', '--source'],
+ 'import': ['--brain', '--source'],
+ 'jobs': ['--brain'],
+ 'loops': ['--brain', '--source'],
+ 'lsd': ['--brain'],
+ 'maintain': ['--brain'],
+ 'mcp': ['--brain'],
+ 'migrate': ['--brain'],
+ 'models': ['--brain'],
+ 'notability-eval': ['--brain'],
+ 'onboard': ['--brain'],
+ 'orphans': ['--brain'],
+ 'pages': ['--brain'],
+ 'pricing': ['--brain'],
+ 'projections': ['--brain'],
+ 'quarantine': ['--brain'],
+ 'recall': ['--brain', '--source'],
+ 'reconcile-links': ['--brain'],
+ 'reindex': ['--brain'],
+ 'reindex-code': ['--brain', '--source'],
+ 'reindex-frontmatter': ['--brain'],
+ 'reindex-search-vector': ['--brain'],
+ 'repair': ['--brain'],
+ 'repos': ['--brain'],
+ 'retrieval-upgrade': ['--brain'],
+ 'salience': ['--brain'],
+ 'serve': ['--brain'],
+ 'skillopt': ['--brain'],
+ 'sources': ['--brain'],
+ 'status': ['--brain'],
+ 'storage': ['--brain'],
+ 'sweep': ['--brain', '--source'],
+ 'sync': ['--brain', '--source'],
+ 'takes': ['--brain'],
+ 'think': ['--brain', '--source'],
+ 'transcripts': ['--brain', '--source'],
+ 'waiting': ['--brain', '--source'],
+ 'watch': ['--brain', '--source'],
+ 'whoknows': ['--brain'],
};
diff --cc src/core/operations-descriptions.ts
index 43bb0a2e00,44a931df50..c40b16d668
--- a/src/core/operations-descriptions.ts
+++ b/src/core/operations-descriptions.ts
@@@ -58,54 -46,13 +46,13 @@@ export const GET_RECENT_TRANSCRIPTS_DES
// ──────────────────────────────────────────────────────────────────────────────
export const LIST_PAGES_DESCRIPTION =
- "List pages with optional filters. " +
- "For 'what's recent / what did I touch this week' questions, use list_pages " +
- "with sort=updated_desc instead of semantic search. " +
- "Default 50 rows; remote callers are capped at 100 (local CLI callers' explicit " +
- "limits are honored). A result with exactly `limit` rows may be truncated. " +
- "For exhaustive listing, page with updated_after=<last row's updated_at_iso> + " +
- "updated_after_slug=<last row's slug> until a page returns fewer rows than the " +
- "limit (the keyset forces sort=updated_asc; a bare updated_after cursor skips " +
- "rows sharing the cursor timestamp).";
+ "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows (remote max 100); a full page may be truncated: continue with updated_after + updated_after_slug from the last row.";
export const QUERY_DESCRIPTION =
- "Hybrid search with vector + keyword + multi-query expansion. " +
- "Prefer `query` for concept / synonym / landscape questions ('all the X that " +
- "do Y', 'the landscape of Z') — expansion recovers synonym- and " +
- "outcome-phrased matches a single embedding misses. Still top-K, and the " +
- "default count when `limit` is omitted depends on the configured search " +
- "mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param " +
- "description); pass `limit` explicitly for a stable count regardless of " +
- "mode. When the answer needs the surrounding conversation or section, pass " +
- "`return_unit` ('page' / 'section' / 'window') to get that evidence in one call " +
- "instead of get_page per hit; conversation pages already come back whole by default (return_unit " +
- "'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens " +
- "`search` is cheaper (no expansion LLM call). " +
- "For personal/emotional questions ('what's going on with me', 'anything notable', " +
- "'how am I feeling'), prefer get_recent_salience or find_anomalies (raw " +
- "transcripts are owner-only: `gbrain transcripts recent` on the brain host). Semantic search returns polished pages and misses " +
- "recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' " +
- "mean impressive — they often mean difficult or emotionally charged. " +
- "Needs an embedding key for semantic recall and a chat-model key for expansion; " +
- "without them it runs keyword-only and a degraded_recall notice says so (a thin " +
- "result is then not proof of absence).";
- "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies, get_recent_transcripts. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). fields: \"full\" adds diagnostics.";
++ "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies; raw transcripts: `gbrain transcripts recent` on the brain host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key, else keyword-only; expansion needs a chat-model key. fields: \"full\" adds diagnostics.";
export const SEARCH_DESCRIPTION =
- "Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. " +
- "Best for exact known tokens, names, and structured-field lookups. A populated " +
- "result set is NOT proof of coverage — for concept / synonym / landscape " +
- "questions use `query` (adds multi-query expansion); for exhaustive " +
- "enumeration use list_pages pagination. " +
- "Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; " +
- "conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). " +
- "For personal/emotional questions, " +
- "prefer get_recent_salience or find_anomalies — they surface activity bursts " +
- "without needing a search term. " +
- "For code-symbol questions (callers, callees, definitions, blast radius), use " +
- "code_callers / code_callees / code_def / code_refs instead — those return " +
- "structural graph data, not text chunks. " +
- "For agent memory reads (saved facts + budget-packed retrieval), prefer the " +
- "`recall` verb.";
+ "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal questions: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.";
// ──────────────────────────────────────────────────────────────────────────────
// v0.32.6 — contradiction probe MCP surface (M3)
diff --cc src/core/ops/chunks.ts
index 2a6756f1ef,72e4f59fb7..a7737c6fb6
--- a/src/core/ops/chunks.ts
+++ b/src/core/ops/chunks.ts
@@@ -14,16 -14,13 +14,15 @@@ import { federatedSearchScope, parseSou
const resolve_slugs: Operation = {
name: 'resolve_slugs',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Fuzzy-match a partial name or slug to existing page slugs. Use when a slug is uncertain before get_page, links or tags. Needs read scope. On no matches: search for the name instead.',
- description: 'Fuzzy-match a partial slug or title to page slugs.',
++ description: 'Fuzzy-match a partial slug or title to page slugs. Use when a slug is uncertain. Needs read scope.',
params: {
- partial: { type: 'string', required: true, description: "Partial slug or title text to match, e.g. 'alice-ex' or 'meeting notes'. This is the search text param — there is no `text` param." },
+ partial: { type: 'string', required: true, description: "Partial slug or title, e.g. 'alice-ex'." },
source_id: {
type: 'string',
- description:
- "Scope resolution to a single source. Defaults to OperationContext.sourceId; when unset, an unqualified resolve spans every federated source (matching search/get_page). Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",
+ description: "One source, or '__all__'.",
},
},
handler: async (ctx, p) => {
diff --cc src/core/ops/facts.ts
index ba49a2d110,a6d4a906d4..397f4a794e
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@@ -202,26 -201,23 +202,25 @@@ function recallEvidencePlan(ctx: Operat
const recall: Operation = {
name: 'recall',
+ mutating: false,
+ idempotent: true,
outputRedaction: { retrieval: { localVerbatim: ['facts'] } },
- description:
- 'MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.',
+ description: 'MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. Remote callers see world facts only. One card: entity; reasoning: synthesize.',
params: {
- entity: { type: 'string', description: 'Entity slug (canonical). Returns facts about this entity newest first, each labelled with its source_id. Across several granted sources, same-slug entities that no entity-identity group links are different entities: facts comes back empty and ambiguous_entity names each (source_id, entity_slug); pass source_id to read one.' },
- query: { type: 'string', description: 'MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error).' },
- budget_tokens: { type: 'number', description: 'MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count.' },
- budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'Optional packing order. facts_first preserves legacy behavior (default). query_first packs the ranked page prefix before facts only with a nonblank query and positive finite budget; a positive budget below one token keeps neither arm. No query or inactive budget preserves legacy behavior. Neither policy skips oversized items or truncates. Supplying this option adds budget_packing accounting. Keep fact-focused/entity-filtered questions on facts_first.' },
- source_id: { type: 'string', description: 'Optional concrete source id for both facts and page results. Narrows the caller’s authorized scope, including an explicit default; a denied, missing, or archived source fails rather than widening. Omit to preserve the existing context/grant scope.' },
- since: { type: 'string', description: 'ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only, on event time (valid_from, falling back to created_at); composes with `entity` and `session_id`. An unparseable value is rejected (invalid_params).' },
- session_id: { type: 'string', description: 'Source session id (e.g. topic-A). Returns facts captured in that session.' },
- include_expired: { type: 'boolean', description: 'When true, include expired_at IS NOT NULL rows. Default false.' },
- supersessions: { type: 'boolean', description: 'When true, return only the supersession audit log (facts with superseded_by set), newest first by COALESCE(expired_at, valid_until).' },
- limit: { type: 'number', description: 'Per-arm cap: max fact rows AND max search results. Default 50, cap 100.' },
- grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied in SQL before the limit, so matches on high-cardinality entities are found even outside the newest-N window.' },
- include_pending: { type: 'boolean', description: 'v0.32: when true, response includes pending_consolidation_count (facts not yet promoted to takes by the dream-cycle consolidate phase). One round trip; backward-compatible (field omitted when false).' },
- return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: "Evidence unit for the results[] arm (needs `query`; default config search.return_unit = 'auto'). 'window' adds neighbor chunks, 'section' the enclosing section or conversation rounds, 'page' the whole page/session (best for multi-session questions), 'auto' the whole page for conversation pages and the ranked chunk unchanged for everything else (budget_tokens or budget_policy without return_unit keeps chunk packing). Non-chunk units return one result per page with `delivered` metadata and a top-level `delivery` block; the evidence is budgeted by budget_tokens (default 6000, auto 24000) and then packed by recall's usual rules." },
- return_window: { type: 'number', description: "Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1)." },
+ entity: { type: 'string', description: 'Entity slug; facts about it, newest first.' },
+ query: { type: 'string', description: 'Also search pages (results[] arm).' },
+ budget_tokens: { type: 'number', description: 'Token budget; facts pack first.' },
+ budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'facts_first (default) or query_first.' },
+ source_id: { type: 'string', description: 'Narrow to one source you may read.' },
+ since: { type: 'string', description: 'Facts since (ISO 8601 or "8 hours ago").' },
+ session_id: { type: 'string', description: 'Facts captured in this session.' },
+ include_expired: { type: 'boolean', description: 'Include expired facts.' },
+ supersessions: { type: 'boolean', description: 'Only the supersession audit log.' },
+ limit: { type: 'number', description: 'Per-arm max (default 50, cap 100).' },
+ grep: { type: 'string', description: 'Substring of the fact text.' },
+ include_pending: { type: 'boolean', description: 'Add pending count.' },
+ return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: 'Evidence unit for results[] (see search).' },
+ return_window: { type: 'number', description: 'Window size 1-3.' },
},
scope: 'read',
verb: true,
@@@ -610,17 -606,14 +609,16 @@@ const dropAll = <T>(items: T[]) => ({ i
const context_pack: Operation = {
name: 'context_pack',
+ mutating: false,
+ idempotent: true,
outputRedaction: { retrieval: { localVerbatim: ['facts'] } },
- description:
- 'MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing entities — entity cards + open threads + hot facts, zero-LLM, sub-second. Call at session start (warm cold context) and after compaction (rehydrate what the summary lost). WORLD-ONLY by default; pass include_private (honored for LOCAL trusted callers only) to widen all arms. budget_tokens packs server-side (response reports budget_used + dropped_count; cards pack first, then facts). Branch on structured fields, never prose. protocol_version rides every response.',
+ description: 'MEMORY VERB (v1): budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction.',
params: {
- entities: { type: 'string', required: true, description: 'Comma-separated entity names/slugs to bundle. Capped at 8.' },
- budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Cards pack first, then facts; each item costs its rendered line and the envelope + section headers are reserved, so `text` fits the budget. Response adds budget_tokens, budget_used (tokens of `text`), dropped_count.' },
- since: { type: 'string', description: 'ISO 8601 datetime. When set, open-thread events are filtered to those after this cursor.' },
- session_id: { type: 'string', description: 'Opaque session id; keys the hot-memory cache and (on the push path) the session cursor.' },
- include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
+ entities: { type: 'string', required: true, description: 'Comma-separated names or slugs (max 8).' },
+ budget_tokens: { type: 'number', description: 'Token budget; cards pack first.' },
+ since: { type: 'string', description: 'Only open-thread events after this ISO time.' },
+ session_id: { type: 'string', description: 'Opaque session id.' },
+ include_private: { type: 'boolean', description: 'Local trusted callers only.' },
},
scope: 'read',
verb: true,
@@@ -727,18 -720,15 +725,17 @@@
const delta: Operation = {
name: 'delta',
+ mutating: false,
+ idempotent: true,
outputRedaction: { retrieval: { localVerbatim: ['facts'] } },
- description:
- 'MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts; threads are never dropped). protocol_version rides every response.',
+ description: 'MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. Keep a cursor with session_id, or pass since.',
params: {
- since: { type: 'string', description: 'ISO 8601 cursor. Returns pages/facts/thread-events newer than this timestamp. Optional when session_id carries an established cursor.' },
- since_slug: { type: 'string', description: 'Stateless keyset resume: pass back `next_cursor.slug` from the previous response (paired with `since`=next_cursor.since) to page through pages sharing one timestamp. Ignored when session_id is set (the session cursor carries it).' },
- entities: { type: 'string', description: 'Optional comma-separated entity scope for thread-event deltas. Capped at 8.' },
- budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Pages pack first, then facts; each item costs its rendered line and the envelope + section headers + every thread line are reserved, so `text` fits the budget. Threads are never dropped (budget_used can exceed the budget only when the header + threads alone do). Response adds budget_tokens, budget_used (tokens of `text`), dropped_count.' },
- session_id: { type: 'string', description: 'Opaque session id. Drives the per-session cursor: the first call establishes it, each call advances it to the newest DELIVERED change (at-least-once — with has_more:true the undelivered tail returns on the next wake). Without it, pass an explicit `since` for a stateless delta.' },
- include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
+ since: { type: 'string', description: 'ISO 8601 cursor (or use session_id).' },
+ since_slug: { type: 'string', description: 'next_cursor.slug from the previous response.' },
+ entities: { type: 'string', description: 'Entity scope for thread events (max 8).' },
+ budget_tokens: { type: 'number', description: 'Token budget; pages pack first.' },
+ session_id: { type: 'string', description: 'Opaque session id; keeps a cursor.' },
+ include_private: { type: 'boolean', description: 'Local trusted callers only.' },
},
scope: 'read',
verb: true,
diff --cc src/core/ops/ingest-log.ts
index f1b0b55f1d,7ccbfe1cba..2fcb686c57
--- a/src/core/ops/ingest-log.ts
+++ b/src/core/ops/ingest-log.ts
@@@ -44,12 -43,10 +44,12 @@@ const log_ingest: Operation =
const get_ingest_log: Operation = {
name: 'get_ingest_log',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'retrieval',
- description: 'List recent ingestion events (what was imported, from where, which pages changed). Use when checking whether a source was already ingested. Needs read scope.',
- description: 'Recent ingestion log entries.',
++ description: 'Recent ingestion log entries. Use when checking what was already imported.',
params: {
- limit: { type: 'number', description: 'Max entries (default 20)' },
+ limit: { type: 'number', description: 'Default 20.' },
},
handler: async (ctx, p) => {
// Source-scope the log for remote callers (scalar grant → single-element
diff --cc src/core/ops/jobs.ts
index d397145da6,eb18e6fab8..1e69f8e683
--- a/src/core/ops/jobs.ts
+++ b/src/core/ops/jobs.ts
@@@ -338,16 -236,15 +338,16 @@@ function delegationDenied(ctx: Operatio
// (agent.use_gateway_loop is auto-on for submit_agent jobs).
const submit_agent: Operation = {
name: 'submit_agent',
+ idempotent: false,
outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },
- description: 'Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. Requires the `agent` OAuth scope. Tools, source, slug prefixes, max concurrency, and daily budget are bound at OAuth client registration time.',
+ description: 'Submit an agent job (agent scope; tools and budget bound to your client). Poll get_agent_job.',
params: {
- prompt: { type: 'string', required: true, description: 'User prompt for the agent' },
- model: { type: 'string', description: 'provider:model string (defaults to models.tier.subagent)' },
- allowed_tools: { type: 'array', description: 'Subset of bound_tools the agent may invoke', items: { type: 'string' } },
- allowed_slug_prefixes: { type: 'array', description: 'Subset of delegated_slug_prefixes for writes; omit for a job-owned namespace', items: { type: 'string' } },
- max_turns: { type: 'number', description: 'Max LLM turns (default 20, hard cap 100)' },
- queue: { type: 'string', description: 'Queue name (default "default")' },
+ prompt: { type: 'string', description: 'Task prompt.', required: true },
+ model: { type: 'string', description: 'provider:model (default: subagent tier).' },
+ allowed_tools: { type: 'array', description: 'Subset of your bound tools.', items: { type: 'string' } },
+ allowed_slug_prefixes: { type: 'array', description: 'Subset of your write prefixes.', items: { type: 'string' } },
+ max_turns: { type: 'number', description: 'Default 20, max 100.' },
+ queue: { type: 'string', description: 'Default "default".' },
},
mutating: true,
scope: 'agent',
@@@ -512,12 -392,10 +512,12 @@@
*/
const get_agent_job: Operation = {
name: 'get_agent_job',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'retrieval',
- description: 'Poll an agent job submitted via submit_agent. Returns a trimmed status view (id, status, timestamps, error_text, result) plus queue_position (waiting jobs ahead in claim order; 0 = next) while the job is still waiting. Requires the `agent` OAuth scope; only jobs owned by the calling client are visible.',
- description: 'Poll a submit_agent job: status, result, queue_position.',
++ description: 'Poll a submit_agent job: status, result, queue_position. Needs agent scope.',
params: {
- id: { type: 'number', required: true, description: 'Job id returned by submit_agent' },
+ id: { type: 'number', description: 'Job id.', required: true },
},
scope: 'agent',
handler: async (ctx, p) => {
@@@ -659,11 -527,10 +659,11 @@@ const list_jobs: Operation =
const cancel_job: Operation = {
name: 'cancel_job',
+ idempotent: false,
outputRedaction: { exempt: 'admin-scoped job introspection: job params and results are operator data, not retrieved brain text' },
- description: 'Cancel a waiting, active, or delayed job. Agent-scoped tokens (no admin) can cancel only jobs they own.',
- description: 'Cancel a waiting, active or delayed job you may manage.',
++ description: 'Cancel a waiting, active or delayed job you may manage. Needs admin scope.',
params: {
- id: { type: 'number', required: true, description: 'Job ID' },
+ id: { type: 'number', description: 'Job id.', required: true },
},
mutating: true,
scope: 'admin',
diff --cc src/core/ops/links.ts
index 1f18d93283,c721557c32..7643344824
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@@ -323,12 -318,10 +323,12 @@@ const get_links: Operation =
const get_backlinks: Operation = {
name: 'get_backlinks',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'retrieval',
- description: 'List a page\'s incoming links (who points at it). Use when finding everything that mentions or relates to an entity. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.',
- description: 'List links pointing to a page.',
++ description: 'List links pointing to a page. Use when finding what mentions an entity.',
params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose incoming links to list.' },
+ slug: { type: 'string', description: 'Page slug.', required: true },
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
},
@@@ -380,15 -371,13 +380,15 @@@ const DEFAULT_TRAVERSE_DEPTH = 5
const traverse_graph: Operation = {
name: 'traverse_graph',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'retrieval',
- description: `Traverse link graph from a page. Remote callers default to bidirectional edges (GraphPath[]) at depth ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} (pass depth explicitly for deeper walks); trusted local no-filter callers keep the legacy node shape at depth ${DEFAULT_TRAVERSE_DEPTH}.`,
+ description: `Walk the link graph from a page. Remote callers get bidirectional paths at depth ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} by default.`,
params: {
- slug: { type: 'string', required: true, description: "Slug of the page to start the traversal from, e.g. 'people/alice-example'. This is the start-node param — there is no `start` or `root` param." },
- depth: { type: 'number', description: `Max traversal depth (capped at ${TRAVERSE_DEPTH_CAP}). Default ${DEFAULT_TRAVERSE_DEPTH}, except a remote call that lets direction default to 'both' uses ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} (bidirectional path enumeration is combinatorial on hubs); an explicit depth is always honored up to the cap.` },
- link_type: { type: 'string', description: 'Filter to one link type (per-edge filter, traversal only follows matching edges)' },
- direction: { type: 'string', enum: ['in', 'out', 'both'], description: "Traversal direction ('in', 'out', or 'both'). Remote callers default to 'both'; trusted local no-filter callers keep the legacy outgoing-node output." },
+ slug: { type: 'string', description: 'Start page slug.', required: true },
+ depth: { type: 'number', description: `Max depth (cap ${TRAVERSE_DEPTH_CAP}).` },
+ link_type: { type: 'string', description: 'Follow only this link type.' },
+ direction: { type: 'string', description: 'Remote default both.', enum: ['in', 'out', 'both'] },
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
},
diff --cc src/core/ops/page-edit.ts
index 1f3e38abd0,e3a44f938e..5960703c88
--- a/src/core/ops/page-edit.ts
+++ b/src/core/ops/page-edit.ts
@@@ -9,15 -9,14 +9,15 @@@ import { EDIT_PAGE_MAX_EDITS, parsePage
const edit_page: Operation = {
name: 'edit_page',
+ idempotent: true,
outputRedaction: { exempt: "the diff is the caller's own authorized view of the page it just edited (the get_page boundary), secret-redacted when created because the receipt retains it" },
- description: 'Change part of an existing page without resending it: prefer this over put_page for small changes to large pages. Read get_page with include_content:true and pass its revision as expected_revision. Each edit replaces old_text with new_text; edits apply in order, each to the text the previous edit produced, and each old_text must match exactly once in that content. Protected takes and facts sections never match (use the takes_* operations or remember/forget). All edits publish together or none do, through the same receipts, fences and write-through as put_page. Returns the new revision and a unified diff of your view (at most 8 KB). Refusals name the edit: edit_no_match, edit_ambiguous_match (with match_count), edit_protected_span, edit_invalid; a stale revision returns revision_conflict with current_revision. Retain request_id and repeat identical arguments after a pending receipt.',
+ description: 'Change part of a page: prefer this over put_page for small changes. expected_revision is the revision from get_page include_content:true. Each old_text must match exactly once; edits apply in order, all or none. Stale revision: revision_conflict.',
params: {
- slug: { type: 'string', required: true, description: 'Slug of the existing page to edit.' },
- expected_revision: { type: 'string', required: true, description: 'The `revision` from get_page include_content:true. The edit is refused if the page changed since.' },
+ slug: { type: 'string', description: 'Page slug.', required: true },
+ expected_revision: { type: 'string', required: true, description: 'revision from get_page include_content:true.' },
edits: {
type: 'array', required: true,
- description: `1 to ${EDIT_PAGE_MAX_EDITS} replacements, applied in order and all or nothing.`,
+ description: `1 to ${EDIT_PAGE_MAX_EDITS} {old_text, new_text} replacements.`,
items: {
type: 'object',
properties: {
diff --cc src/core/ops/pages.ts
index dfaaec3346,7a69ca9478..078a1a52ca
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@@ -75,16 -74,15 +75,16 @@@ function stripPrivacyFencesForRemoteRea
const get_page: Operation = {
name: 'get_page',
+ idempotent: true,
outputRedaction: { exempt: 'explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)' },
- description: 'Read a page by slug (supports optional fuzzy matching). Slug aliases left by renames redirect to the canonical page in the source that owns the alias (archived sources excluded); a redirected read reports `resolved_slug`. To edit a page, pass include_content: true — the returned `content` field is the canonical full markdown (frontmatter + body + timeline sentinel); edit THAT and pass it back to put_page to round-trip losslessly. Reassembling compiled_truth/timeline by hand risks dropping sections. Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (the soft-delete recovery window). `timeline` is only the markdown section after the timeline sentinel; entries written by add_timeline_entry or extraction live in timeline rows, which include_timeline_entries: true returns as `timeline_entries` (the same rows get_timeline returns).',
+ description: 'Read a page by slug (fuzzy optional; renamed slugs redirect). To edit, pass include_content:true and send `content` to put_page, or use edit_page. Timeline rows need include_timeline_entries.',
params: {
- slug: { type: 'string', required: true, description: 'Page slug' },
- fuzzy: { type: 'boolean', description: 'Enable fuzzy slug resolution (default: false)' },
- include_content: { type: 'boolean', description: '#2225: include the canonical serialized `content` field (frontmatter + body + timeline sentinel) for lossless get→edit→put_page round-trips. Default false — it roughly duplicates compiled_truth + timeline, so read-only callers should not pay for it.' },
- include_deleted: { type: 'boolean', description: 'v0.26.5: surface soft-deleted pages with deleted_at populated (default: false). Used by restore workflows.' },
- include_timeline_entries: { type: 'boolean', description: '#5709: also return `timeline_entries`, the page\'s timeline rows (the same rows and filtering as get_timeline for this caller). Default false to keep the payload small.' },
- source_id: { type: 'string', description: "#4329: scope the lookup to a single source (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId / the caller's grant. '__all__' spans every source for trusted local callers, your granted sources for remote callers." },
+ slug: { type: 'string', description: 'Page slug.', required: true },
+ fuzzy: { type: 'boolean', description: 'Fuzzy slug match.' },
+ include_content: { type: 'boolean', description: 'Full markdown + revision, for editing.' },
+ include_deleted: { type: 'boolean', description: 'Include soft-deleted pages.' },
+ include_timeline_entries: { type: 'boolean', description: 'Also return timeline rows.' },
+ source_id: { type: 'string', description: "One source, or '__all__'." },
},
handler: async (ctx, p) => {
const slug = p.slug as string;
@@@ -284,14 -281,13 +284,14 @@@ const fetch_page: Operation =
const put_page: Operation = {
name: 'put_page',
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences; automatic graph links are skipped for untrusted writes. A stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG.',
+ description: 'Replace a complete Markdown page: content REPLACES the whole page. Read get_page include_content:true; pass its revision as expected_revision (omit to create). Keep a request_id UUID; retry with identical arguments. Remote callers: graph links are skipped; a stdio `gbrain serve` sweeps them later, `gbrain serve --http` does not self-sweep. Small changes: edit_page.',
params: {
...PAGE_MUTATION_PARAMS,
- slug: { type: 'string', required: true, description: 'Page slug' },
- content: { type: 'string', required: true, description: 'Complete markdown content with YAML frontmatter. REPLACES the entire page; this is not a partial edit. Read the canonical page first with `get_page include_content:true` before modifying it.' },
- allow_empty: { type: 'boolean', required: false, description: 'Allow overwriting an existing non-empty page with empty/whitespace-only content (default: false). Without it, put_page rejects the empty overwrite — the empty-stdin failure class.' },
+ slug: { type: 'string', description: 'Page slug.', required: true },
+ content: { type: 'string', required: true, description: 'Complete markdown with frontmatter; read get_page include_content:true first.' },
+ allow_empty: { type: 'boolean', required: false, description: 'Allow emptying a non-empty page.' },
// v0.39.3.0 provenance write-through (WARN-8 + A1 + CV6). Optional fields
// for trusted local callers (capture CLI, autopilot, dream cycle). Remote
// MCP callers (ctx.remote !== false) have their values OVERRIDDEN with
diff --cc src/core/ops/persistence.ts
index dfaf65ddf4,ca1005c787..48e0675c63
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@@ -133,9 -121,8 +133,9 @@@ const requestParam = { type: 'string' a
export const persistenceOperations: Operation[] = [
{
name: 'get_write_request',
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Read your durable write receipt by request_id. Requires write scope and this operation in the current grant. Foreign, missing, and no-longer-accessible requests return the same not_found error; private journal input and recovery bytes are never returned.',
+ description: 'Read the receipt of your write by request_id (after write_pending or a lost reply).',
params: { request_id: requestParam },
scope: 'write', mutating: false, area: 'pages',
cliHints: { name: 'write-request', positional: ['request_id'] },
@@@ -150,13 -137,12 +150,13 @@@
},
{
name: 'list_write_requests',
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'List your currently authorized write receipts in one source, newest first. Useful when an acknowledgment was lost. Results and pagination exclude other principals and inaccessible targets; no private payloads or cross-principal queue counts are exposed.',
- description: 'List your write receipts in one source, newest first.',
++ description: 'List your write receipts in one source, newest first. Use when a request_id was lost.',
params: {
- source_id: { type: 'string', description: 'Source to inspect. Defaults to the caller’s resolved source.' },
- limit: { type: 'number', default: 25, description: 'Number of visible receipts, 1–100. Default 25.' },
- before: { type: 'string', description: 'Opaque next cursor from the previous response.' },
+ source_id: { type: 'string', description: 'Default: yours.' },
+ limit: { type: 'number', default: 25, description: '1-100 (default 25).' },
+ before: { type: 'string', description: 'next cursor from the previous page.' },
},
scope: 'write', mutating: false, area: 'pages',
cliHints: { name: 'write-requests' },
@@@ -183,9 -169,8 +183,9 @@@
},
{
name: 'cancel_write_request',
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Cancel your accepted write before publication starts. Returns the actual receipt: running/recovering or already-terminal requests may remain unchanged. Cancellation cannot undo published bytes or a committed fact withdrawal.',
+ description: 'Cancel your accepted write before it publishes. Returns the actual receipt.',
params: { request_id: requestParam },
scope: 'write', mutating: true, area: 'pages',
cliHints: { name: 'cancel-write-request', positional: ['request_id'] },
diff --cc src/core/ops/request-tools.ts
index 078126c4fb,49abb7874e..fe8f2a3a54
--- a/src/core/ops/request-tools.ts
+++ b/src/core/ops/request-tools.ts
@@@ -116,13 -112,8 +116,9 @@@ async function visibleOpsForCaller
const request_tools: Operation = {
name: 'request_tools',
+ idempotent: false,
outputRedaction: 'no_stored_text',
- description:
- 'Discover this brain\'s tool catalog and optionally unlock a wider tool surface for your client. ' +
- 'No arguments → the catalog visible to YOUR credentials, grouped by area (tool names + one-line summaries). ' +
- '{tools: ["name", ...]} → full read-only schemas for the visible subset of those names (unknown/hidden names are silently omitted). ' +
- '{surface: "verbs"|"starter"|"full"} → persist that tool surface for this client (bounded by the server ceiling; denied when an operator pinned the surface; ~5 changes/hour), then re-issue tools/list to see the new catalog.',
+ description: 'More tools: no arguments lists your catalog; {tools: [names]} returns schemas; {surface} persists a wider surface for your OAuth client.',
area: 'discovery',
// FOV-4: callable by read OR agent scope — discovery for every token class.
agentCallable: true,
diff --cc src/core/ops/search.ts
index 744ea0ba1e,a9202f5bdf..48b648f0af
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@@ -768,9 -742,9 +741,8 @@@ const query: Operation =
// searchVector branch and the text hybrid path below).
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
-- // v0.27.1: image-similarity branch. Bypasses hybridSearch (which is
-- // text-only); embeds the image via embedMultimodal and runs a direct
-- // vector search against the embedding_image column.
++ // Image-similarity branch: bypasses the text-only hybridSearch, embeds the
++ // image via embedMultimodal and searches the embedding_image column.
if (imageData) {
const dates = resolveSearchDateBounds({
since: typeof p.since === 'string' ? p.since : undefined,
diff --cc src/core/ops/skills-catalog.ts
index 1c5ec4f91d,ec768fdbd3..11b259bff9
--- a/src/core/ops/skills-catalog.ts
+++ b/src/core/ops/skills-catalog.ts
@@@ -123,9 -116,7 +121,9 @@@ const sharedSkillMutationParams: Operat
expected_revision: { type: 'string', description: 'Current revision UUID; JSON null for creation.' },
};
const get_skill_asset: Operation = {
- name: 'get_skill_asset', description: 'Read a bounded, owner-approved file from an exact sealed skill revision. Does not execute downloaded bytes.',
+ name: 'get_skill_asset', description: 'Read an approved file from an exact skill revision (data only; never executed).',
+ mutating: false,
+ idempotent: true,
outputRedaction: { exempt: 'skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions' },
scope: 'read', publishGateKey: 'mcp.publish_skills',
cliHints: { name: 'skill-asset', positional: [] },
@@@ -222,14 -203,8 +220,10 @@@ const retain_skill_revision: Operation
const list_brain_skillpack: Operation = {
name: 'list_brain_skillpack',
+ mutating: false,
+ idempotent: true,
outputRedaction: { exempt: 'skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions' },
- description:
- 'List brain-resident skillpacks this brain ships (per-source). Returns each pack\'s skills, ' +
- 'one-line descriptions, the schema pack it targets + whether that matches this brain, and a ' +
- 'git scaffold spec. Read-only; gated by mcp.publish_skills. After orienting, call this and ' +
- 'ask the user whether to install any pack the brain offers (gbrain skillpack scaffold <spec>).',
+ description: 'Skillpacks this brain ships, with skills and a scaffold spec to offer the user.',
publishGateKey: 'mcp.publish_skills',
params: {},
handler: async (ctx) => {
diff --cc src/core/ops/sources.ts
index 67cca090d2,03b7a94640..6ae63b0d8b
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@@ -15,32 -13,10 +15,25 @@@ import { resolveAuthCapabilities } fro
// --- v0.28: whoami + sources management ---
+/** A source id from params, validated for argv; an unsafe id is left out rather than interpolated. */
+function sourceIdArg(id: unknown): string[] {
+ return isValidSourceId(id) ? [id] : [];
+}
+
+/** B6: managed source lifecycle runs only on the verified owner CLI; the refusal names the exact host command. */
+function managedLifecycleRefusal(ctx: OperationContext, args: string[]) {
+ return hostOnlyError(ctx, 'writer_coordinator_required',
+ 'Managed source lifecycle requires the verified owner CLI. An ordinary MCP grant does not confer owner administration authority.',
+ ['gbrain', ...args],
+ 'With managed persistence on, adding or removing a source changes the brain\'s writer topology, which only its owner CLI may do.');
+}
+
const whoami: Operation = {
name: 'whoami',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description:
- 'Introspect the calling identity. Returns one of three transport shapes: ' +
- '{transport: "oauth", client_id, client_name, scopes, expires_at, source_id, federated_read}, ' +
- '{transport: "legacy", token_name, scopes, expires_at: null}, or ' +
- '{transport: "local", scopes: []}, or {transport: "stdio", scopes: []} ' +
- 'for the auth-less stdio MCP pipe. Throws unknown_transport when the ' +
- 'context is ambiguous (remote=true without auth and no transport marker) ' +
- '(fail-closed). Every shape also carries `readiness` (the setup gaps of this install, each with its fix); stdio scopes are the grant of the verified registration.',
+ description: 'Your identity: transport, scopes and, over OAuth, client, source_id and federated_read.',
params: {},
scope: 'read',
handler: async (ctx) => {
diff --cc src/core/ops/timeline.ts
index b7c6b18254,f3d04bf359..5195c8a943
--- a/src/core/ops/timeline.ts
+++ b/src/core/ops/timeline.ts
@@@ -20,16 -19,15 +20,16 @@@ import
const add_timeline_entry: Operation = {
name: 'add_timeline_entry',
+ idempotent: true,
outputRedaction: 'retrieval',
- description: 'Append an entry to the canonical Markdown timeline and structured timeline store in one committed write. Exact replay changes neither store.',
+ description: 'Append a dated entry to a page timeline. Replaying the same entry changes nothing.',
params: {
request_id: WRITE_REQUEST_PARAM,
- slug: { type: 'string', required: true, description: 'Slug of the page whose timeline to append to.' },
- date: { type: 'string', required: true, description: "Entry date, strict YYYY-MM-DD (e.g. '2026-04-03'). Timestamps and non-calendar dates are rejected." },
- summary: { type: 'string', required: true, description: 'One-line summary of what happened on that date.' },
- detail: { type: 'string', description: 'Longer free-text detail behind the summary.' },
- source: { type: 'string', description: "Provenance ref for the entry, e.g. a meeting slug like 'meetings/2026-04-03' or a URL." },
+ slug: { type: 'string', description: 'Page slug.', required: true },
+ date: { type: 'string', required: true, description: 'YYYY-MM-DD.' },
+ summary: { type: 'string', required: true, description: 'One line.' },
+ detail: { type: 'string', description: 'Longer text.' },
+ source: { type: 'string', description: 'Provenance slug or URL.' },
},
mutating: true,
scope: 'write',
diff --cc src/core/verbs.ts
index 316201ca51,bebc4b6708..1cd8c68b92
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@@ -60,19 -60,11 +60,12 @@@ const PROVENANCE_MAX = 500
const remember: Operation = {
name: 'remember',
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description:
- 'MEMORY VERB (v1): save one fact to durable agent memory — the protocol write verb. ' +
- 'provenance is REQUIRED (free text, e.g. "conversation 2026-06-12", "user said in chat", "import: notes.md"). ' +
- 'Set `entity` whenever the fact is about a specific person/company/project — entity-scoped recall will not find it otherwise. ' +
- 'ttl accepts duration shorthand ("30d", "12h") or an absolute ISO 8601 timestamp; ISO-8601 durations like "P30D" are rejected with a fix. ' +
- 'visibility defaults to "world" (readable by every agent connected to this brain; pass "private" for local-CLI-only facts). ' +
- 'Response: branch on `status` (inserted|duplicate|superseded), never on `status_text` (human rendering only). ' +
- 'On duplicate, `id` is the EXISTING fact\'s id. For bulk extraction from a raw transcript use extract_facts instead.',
+ description: 'MEMORY VERB (v1): save one fact; provenance required. Set `entity` when the fact has a subject, or entity-scoped recall misses it. Branch on `status` (inserted|duplicate|superseded). write_pending carries a receipt: poll get_write_request.',
params: {
...PAGE_MUTATION_PARAMS,
- fact: { type: 'string', required: true, description: 'The fact to remember, one claim per call.' },
+ fact: { type: 'string', description: 'One claim.', required: true },
provenance: {
type: 'string',
required: true,
@@@ -178,17 -158,10 +165,12 @@@
const entity: Operation = {
name: 'entity',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'retrieval',
- description:
- 'MEMORY VERB (v1): inspect ONE known person/company/project card — zero LLM calls, sub-100ms. ' +
- 'Resolution: alias > exact title > slug-suffix; ties break on most-recently-touched. ' +
- 'NEVER errors on a miss: returns found:false plus near-miss suggestions with create_safety hints ' +
- '(exists | probable | unknown — whether writing a new page would duplicate). ' +
- 'Routing: for facts/snippets retrieval use recall; for broad questions needing reasoning use synthesize (expensive).',
+ description: 'MEMORY VERB (v1): one known person/company/project card, zero LLM. A miss returns found:false with near matches and create_safety, so you do not duplicate a page. Facts: recall.',
params: {
- name: { type: 'string', required: true, description: 'Free-text name, alias, or slug (e.g. "Alice Example", "people/alice-example").' },
+ name: { type: 'string', required: true, description: 'Name, alias or slug (e.g. "Alice Example").' },
},
scope: 'read',
verb: true,
@@@ -235,21 -208,12 +217,14 @@@ const SYNTHESIS_FAILURE_CODES: Record<s
const synthesize: Operation = {
name: 'synthesize',
+ mutating: false,
+ idempotent: true,
outputRedaction: 'retrieval',
- description:
- '[EXPENSIVE / SLOW — makes LLM calls, seconds-to-minutes latency, costs money] ' +
- 'MEMORY VERB (v1): answer a broad question using cross-page LLM reasoning with citations and gap analysis. ' +
- 'Prefer recall (facts/snippets) or entity (one known card, zero LLM) for lookups — use synthesize only when the answer ' +
- 'requires combining evidence across pages. Response carries a best-effort cost block (model, tokens, usd_estimate) ' +
- 'plus compose-status fields (synthesis_status, pages_gathered, takes_gathered, warnings); when the LLM compose step ' +
- 'fails but retrieval succeeded, `answer` degrades to an extractive digest of retrieved pages ' +
- '(synthesis_status: "extractive_fallback") instead of an error.',
+ description: '[EXPENSIVE / SLOW: LLM calls, costs money] MEMORY VERB (v1): answer a broad question across pages with citations. For lookups use recall or entity.',
params: {
- question: { type: 'string', required: true, description: 'The question to answer.' },
- since: { type: 'string', description: 'Optional temporal window start (ISO 8601 date or datetime).' },
- until: { type: 'string', description: 'Optional temporal window end (ISO 8601 date or datetime).' },
+ question: { type: 'string', description: 'The question.', required: true },
+ since: { type: 'string', description: 'Window start (ISO 8601).' },
+ until: { type: 'string', description: 'Window end (ISO 8601).' },
},
scope: 'read',
verb: true,
@@@ -364,17 -324,12 +339,13 @@@
const forget: Operation = {
name: 'forget',
+ idempotent: true,
outputRedaction: 'no_stored_text',
- description:
- 'MEMORY VERB (v1): expire a remembered fact by id — the protocol delete verb. ' +
- '`id` is the opaque string id returned by remember and recall (facts[].fact_id) — never a page slug. ' +
- 'Idempotent: forgetting an already-expired fact returns expired:false (success), unknown id returns a not_found error. ' +
- 'The fact is expired (audit trail kept), not deleted.',
+ description: 'MEMORY VERB (v1): expire a remembered fact by its fact_id (never a page slug). Idempotent; the audit trail is kept.',
params: {
request_id: WRITE_REQUEST_PARAM,
- id: { type: 'string', required: true, description: 'Opaque fact id from remember/recall (facts[].fact_id). Never a page slug.' },
- reason: { type: 'string', description: 'Optional reason, written to the fact\'s audit trail. Default: "forgotten".' },
+ id: { type: 'string', required: true, description: 'fact_id from remember or recall.' },
+ reason: { type: 'string', description: 'Audit note (default "forgotten").' },
},
mutating: true,
scope: 'write',
diff --cc src/mcp/http-transport.ts
index 14e847f0f4,4a3270f385..7946bd7b99
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@@ -33,14 -33,12 +33,15 @@@ import { resolveAuthCapabilities } fro
import type { BrainEngine } from '../core/engine.ts';
import { buildToolDefs } from './tool-defs.ts';
import { resolveMcpInstructions } from './instructions.ts';
+import { httpInstructionTools } from './initialize-context.ts';
import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
import { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';
+import { scopeDeniedError } from '../core/ops/op-fix.ts';
+import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
import type { AuthInfo } from '../core/operations.ts';
import { VERSION } from '../version.ts';
-import { dispatchToolCall, requestLogStatusForResult } from './dispatch.ts';
+import { dispatchToolCall, requestLogStatusForResult, errorResult } from './dispatch.ts';
+ import { GBRAIN_CLIENT_HEADER, resolveResultRowsMode, resultRowsForRequest } from './result-rows.ts';
import { parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, clampSurface, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
diff --cc src/mcp/server.ts
index e906e56303,4ee1e220d6..14fc75f87d
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@@ -8,9 -7,10 +8,10 @@@ import { isCallable, publishGatesFromDi
import { VERSION } from '../version.ts';
import { buildToolDefs } from './tool-defs.ts';
import { dispatchToolCall, buildOperationContext } from './dispatch.ts';
-import { validateParams, parseStrictParamsMode } from './validate-params.ts';
+import { findInvalidParam, schemaInvalidParams, parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, allowedOpNames, clampSurface, isReadOnlyOperation, type McpAccess, type McpSurface } from './surface.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
+ import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';
import type { Operation } from '../core/operations.ts';
import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { loadConfig } from '../core/config.ts';
@@@ -300,6 -282,13 +301,10 @@@ export async function startMcpServer(en
// `mcp.strict_params` flip needs a serve restart here (deliberate; the
// OAuth HTTP path re-reads dual-plane per request).
const strictParams = parseStrictParamsMode(config?.mcp?.strict_params) === 'reject';
- // C1: search/query row shape for this pipe, resolved once at boot like
- // strict_params (restart to flip). Stdio has no thin-client identity: the
- // thin client only speaks HTTP.
- // A degraded engine is not touched: the file plane decides.
++ // C1: row shape resolved once at boot like strict_params (stdio has no thin client; a degraded engine reads the file plane).
+ const resultRows = isEngineDegraded(engine)
+ ? parseResultRowsMode(config?.mcp?.result_rows) ?? 'lean'
+ : await resolveResultRowsMode(engine, config);
// Generate tool definitions from operations. Extracted to buildToolDefs so
// the subagent tool registry (v0.15+) can call the same mapper against a
diff --cc templates/bootstrap/template-repo/README.md
index 368f4a53ac,1d1bc359b5..0c1b04ece4
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@@ -1,6 -1,6 +1,6 @@@
# gbrain agent workspace — template
- <!-- gbrain-template-stamp: 0.60.42.0 -->
-<!-- gbrain-template-stamp: 0.60.44.0 -->
++<!-- gbrain-template-stamp: 0.60.45.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --cc test/fixtures/goldens/cli/help-and-errors.json
index efda04698a,a1ab1569d7..2dd82bd490
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@@ -673,60 -668,37 +673,37 @@@
"stdout": [
"Usage: gbrain query <query> [options]",
"",
- "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience or find_anomalies (raw transcripts are owner-only: `gbrain transcripts recent` on the brain host). Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged. Needs an embedding key for semantic recall and a chat-model key for expansion; without them it runs keyword-only and a degraded_recall notice says so (a thin result is then not proof of absence).",
- "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies, get_recent_transcripts. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). fields: \"full\" adds diagnostics.",
++ "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies; raw transcripts: `gbrain transcripts recent` on the brain host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key, else keyword-only; expansion needs a chat-model key. fields: \"full\" adds diagnostics.",
"",
"Options:",
- " <query> Question or topic text for hybrid retrieval with expansion (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params.",
- " --image Base64-encoded image bytes for image-similarity search (CLI: --image <path>).",
- " --image-mime MIME type for the image bytes (auto-derived from path on CLI; required when calling op directly).",
- " --limit Max results. Omitted or 0 resolves from the active search mode (10 conservative / 25 balanced / 50 tokenmax by default, or the configured `search.searchLimit` override) — for both text queries and image-similarity queries (`image` param).",
- " --offset Skip first N results (for pagination)",
- " --types Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters.",
- " --snippet-chars Cap each result's chunk_text at N characters (a \"… [truncated]\" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. (#3800)",
- " --return-unit Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').",
- " 'chunk' — the ranked chunk only (~300-450 tokens per result).",
- " 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).",
- " 'section' — the enclosing markdown section, or the conversation rounds around the hit.",
- " 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.",
- " 'auto' — the whole page for conversation pages (conversation/transcript/chat/meeting/slack/imessage types, chat/ or conversations/ slugs), the ranked chunk unchanged for everything else. When no hit is a conversation the response is exactly the chunk response.",
- "Non-chunk units return one result per page, packed into token_budget (default 6000, auto 24000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated; reason under auto) per result and `delivery` in the response meta.",
- " --return-window Neighbor chunks on each side for return_unit 'window' (integer 1-3, default 1).",
- " --token-budget Token budget. Chunk mode, and whenever return_unit is omitted: caps the cumulative chunk payload (results that would overflow are skipped). Explicit non-chunk return_unit: the budget for delivered evidence (default search.return_budget_default = 6000, auto 24000; remote max search.return_budget_max_remote = 32000).",
- " --expand Request multi-query expansion (default: true in every search mode, regardless of search.expansion). Set false to opt out. Requires configured embedding and expansion providers; a cloud expander receives the query and may charge for the call. Response metadata expansion_applied reports whether variants were actually used.",
- " --detail Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)",
- " --mode Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.",
- " --lang Filter to chunks where content_chunks.language matches (e.g., typescript, python, ruby)",
- " --symbol-kind Filter to chunks where content_chunks.symbol_type matches (e.g., function, class, method, type, interface)",
- " --near-symbol Anchor retrieval at this qualified symbol name (e.g., BrainEngine.searchKeyword). Enables A2 two-pass.",
- " --walk-depth Structural walk depth 1-2. Default 0 (off). Expands anchors through code_edges with 1/(1+hop) decay.",
- " --salience v0.29.1 salience boost — emotional_weight + take_count, NO time component.",
- " 'off' — default for entity / canonical / definitional queries",
- " 'on' — surface emotionally-weighted + take-rich pages",
- " 'strong' — aggressive mattering tilt",
- "Omit and gbrain auto-detects from query text. Independent of `recency`.",
- " --recency v0.29.1 recency boost — per-prefix age decay, NO mattering signal.",
- " 'off' — default for canonical truth",
- " 'on' — daily/, media/x/, chat/ decay aggressively; concepts/, originals/, writing/ stay evergreen",
- " 'strong' — multiplies the recency factor by 1.5 (use for 'today' / 'right now')",
- "Omit and gbrain auto-detects. Independent of `salience` (orthogonal axes).",
- " --since v0.29.1 — filter to pages whose effective_date is >= this. ISO-8601 (YYYY-MM-DD or full timestamp) OR relative ('7d', '2w', '1y'). Replaces deprecated `afterDate`.",
- " --until v0.29.1 — filter to effective_date <= this. Same format as `since`. Replaces deprecated `beforeDate`. YYYY-MM-DD lands at end-of-day.",
- " --source-id v0.34: scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers. For remote callers, '__all__' uses the same scope as omission: an OAuth grant when present, otherwise the transport-computed federated sources for grantless local stdio.",
- " --cross-modal v0.36 cross-modal search routing.",
- " 'text' (default for non-image-intent queries) — text-only path, no behavior change vs v0.35.",
- " 'image' — route the query through Voyage multimodal-3 + the embedding_image column. Best for 'show me photos of...' phrasings.",
- " 'both' — run text AND image searches in parallel; merge via weighted RRF.",
- " 'auto' — same effect as omitting the field; intent classifier decides based on query phrasing.",
- " --embedding-column v0.36: route vector search through a non-default embedding column. Defaults to 'embedding' (the brain's primary column) unless `search_embedding_column` config sets a different default. Per-call override for A/B benchmarking across providers (e.g. 'embedding_voyage', 'embedding_openai'). Column MUST be declared in the `embedding_columns` config registry — unknown names throw with a paste-ready hint listing valid columns.",
- " --adaptive-return v0.41.33 — return a TIGHT, intent-sized result set instead of the full top-K. YOU (the agent) set this per query to serve the user well:",
- " TRUE when the user's question has a small, specific answer — a lookup ('what is X', 'who is Y', 'what's my <thing>', 'what did Z decide'), a single-fact recall, or when you'll route the result into a precise downstream step (a classifier, a decision, an exact citation). The user gets the answer, not a wall of loosely-related pages, and you spend fewer tokens reading noise.",
- " Omit / FALSE for breadth — 'everything about X', 'list all', 'what do I know about Y', exploration, brainstorming, or any time you'd rather see more candidates and judge for yourself. Recall matters more there, so take the full top-K.",
- "Safe by construction: it NEVER returns empty when there are matches (you always get at least the top hit), and it only applies to the first page (omit when paginating). Caps come from config (search.adaptive_return_entity_max / _other_max; default 2 / 6) — pass `limit` 1 alongside this for a hard single-answer cap.",
- " --autocut v0.42.3.0 — autocut is the SMART DEFAULT (already ON when the reranker runs, which it does in the default search mode). It returns only the confident cluster by cutting where the relevance score drops off a cliff, so an obvious single answer comes back as 1 result and a genuine handful comes back as that handful — not a fixed wall of 20+.",
- " You almost never set this. Pass FALSE only to FORCE the full top-K when you deliberately want breadth — broad exploration, 'show me everything about X', enumeration where you'd rather over-collect and judge for yourself, or when you suspect the top hit is wrong and want to see the alternatives.",
- " TRUE is redundant in default mode (it's already on); it only matters to override a brain whose config turned autocut off.",
- "Safe by construction: never returns empty when there are matches, only applies to the first page (omit when paginating), and is a no-op when no reranker scored the results (so it can't cut on an untrustworthy signal). Distinct from `adaptive_return`: autocut cuts on the score cliff; adaptive_return caps by question intent. Leave both unset for the smart default.",
- " --relational v0.43 — relational recall arm. SMART DEFAULT (on in balanced/tokenmax). When the question is about a RELATIONSHIP ('who invested in widget-co', 'who introduced me to alice', 'what connects fund-a and fund-b'), the brain resolves the named entity and walks its typed-edge graph (invested_in, works_at, founded, …), surfacing the answer even when no passage mentions both sides. Pure no-op for non-relational questions. Pass FALSE to force lexical/vector-only retrieval (e.g. debugging why a graph answer appeared). You almost never set this."
+ " <query> Question or topic (required unless image).",
+ " --image Base64 image for image search.",
+ " --image-mime MIME type of image.",
+ " --limit Default 10/25/50 by search mode.",
+ " --offset Rows to skip.",
+ " --types Page types, e.g. ['person'].",
+ " --snippet-chars Max chars per chunk_text (0 = full).",
+ " --return-unit chunk, window, section, page or auto (default; whole page for conversations).",
+ " --return-window Neighbor chunks each side for window (1-3).",
+ " --token-budget Token cap on the returned evidence.",
+ " --expand Default true; false skips the expansion LLM call.",
+ " --detail low (compiled truth only), medium (default) or high (all chunks).",
+ " --fields lean (remote default) or full.",
+ " --mode Local callers only.",
+ " --lang Code language.",
+ " --symbol-kind Code symbol type.",
+ " --near-symbol Anchor code symbol.",
+ " --walk-depth Code walk depth 1-2.",
+ " --salience Boost emotional pages (default: auto).",
+ " --recency Boost recent pages (default: auto).",
+ " --since On/after: YYYY-MM-DD or 7d/2w/1y.",
+ " --until On/before.",
+ " --source-id One source, or '__all__'.",
+ " --cross-modal Default auto.",
+ " --embedding-column Registered embedding column.",
+ " --adaptive-return true when one specific answer is wanted (fewer rows; never returns empty); omit for breadth.",
+ " --autocut Default on (never returns empty); false gives full top-K for breadth. Cuts at the score cliff, unlike adaptive_return.",
+ " --relational Relationship-graph arm (default on)."
]
},
{
diff --cc test/fixtures/goldens/cli/tools-json.json
index a04fead0e8,19f02971fe..94df72e6fb
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@@ -2,8 -2,8 +2,8 @@@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 234393,
- "stdoutSha256": "8f7de2af4351fa1ceff0b80a2f5b61373e59aff23425909b0b42d18194b7a8b1",
- "stdoutBytes": 171828,
- "stdoutSha256": "63b1c4278bade0ea6ab1590f30f150ddde4cfd6e47826a582bffecee58e2cf43",
++ "stdoutBytes": 195922,
++ "stdoutSha256": "84cea9f9f0609dacd782cab325973e93a39c5f21879e3f122d17468b6d5d63e1",
"toolNames": [
"remember",
"entity",
@@@ -164,10 -163,7 +164,10 @@@
],
"tools": [
{
- "description": "MEMORY VERB (v1): save one fact to durable agent memory — the protocol write verb. provenance is REQUIRED (free text, e.g. \"conversation 2026-06-12\", \"user said in chat\", \"import: notes.md\"). Set `entity` whenever the fact is about a specific person/company/project — entity-scoped recall will not find it otherwise. ttl accepts duration shorthand (\"30d\", \"12h\") or an absolute ISO 8601 timestamp; ISO-8601 durations like \"P30D\" are rejected with a fix. visibility defaults to \"world\" (readable by every agent connected to this brain; pass \"private\" for local-CLI-only facts). Response: branch on `status` (inserted|duplicate|superseded), never on `status_text` (human rendering only). On duplicate, `id` is the EXISTING fact's id. For bulk extraction from a raw transcript use extract_facts instead.",
+ "description": "MEMORY VERB (v1): save one fact; provenance required. Set `entity` when the fact has a subject, or entity-scoped recall misses it. Branch on `status` (inserted|duplicate|superseded). write_pending carries a receipt: poll get_write_request.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
"name": "remember",
"parameters": {
"entity": "string?",
@@@ -246,14 -241,10 +246,14 @@@
"provenance"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "MEMORY VERB (v1): inspect ONE known person/company/project card — zero LLM calls, sub-100ms. Resolution: alias > exact title > slug-suffix; ties break on most-recently-touched. NEVER errors on a miss: returns found:false plus near-miss suggestions with create_safety hints (exists | probable | unknown — whether writing a new page would duplicate). Routing: for facts/snippets retrieval use recall; for broad questions needing reasoning use synthesize (expensive).",
+ "description": "MEMORY VERB (v1): one known person/company/project card, zero LLM. A miss returns found:false with near matches and create_safety, so you do not duplicate a page. Facts: recall.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "entity",
"parameters": {
"name": "string"
@@@ -270,14 -260,10 +270,14 @@@
"name"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "[EXPENSIVE / SLOW — makes LLM calls, seconds-to-minutes latency, costs money] MEMORY VERB (v1): answer a broad question using cross-page LLM reasoning with citations and gap analysis. Prefer recall (facts/snippets) or entity (one known card, zero LLM) for lookups — use synthesize only when the answer requires combining evidence across pages. Response carries a best-effort cost block (model, tokens, usd_estimate) plus compose-status fields (synthesis_status, pages_gathered, takes_gathered, warnings); when the LLM compose step fails but retrieval succeeded, `answer` degrades to an extractive digest of retrieved pages (synthesis_status: \"extractive_fallback\") instead of an error.",
+ "description": "[EXPENSIVE / SLOW: LLM calls, costs money] MEMORY VERB (v1): answer a broad question across pages with citations. For lookups use recall or entity.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "synthesize",
"parameters": {
"question": "string",
@@@ -304,14 -289,10 +304,14 @@@
"question"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "MEMORY VERB (v1): expire a remembered fact by id — the protocol delete verb. `id` is the opaque string id returned by remember and recall (facts[].fact_id) — never a page slug. Idempotent: forgetting an already-expired fact returns expired:false (success), unknown id returns a not_found error. The fact is expired (audit trail kept), not deleted.",
+ "description": "MEMORY VERB (v1): expire a remembered fact by its fact_id (never a page slug). Idempotent; the audit trail is kept.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
"name": "forget",
"parameters": {
"id": "string",
@@@ -338,14 -318,10 +338,14 @@@
"id"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "Read a page by slug (supports optional fuzzy matching). Slug aliases left by renames redirect to the canonical page in the source that owns the alias (archived sources excluded); a redirected read reports `resolved_slug`. To edit a page, pass include_content: true — the returned `content` field is the canonical full markdown (frontmatter + body + timeline sentinel); edit THAT and pass it back to put_page to round-trip losslessly. Reassembling compiled_truth/timeline by hand risks dropping sections. Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (the soft-delete recovery window). `timeline` is only the markdown section after the timeline sentinel; entries written by add_timeline_entry or extraction live in timeline rows, which include_timeline_entries: true returns as `timeline_entries` (the same rows get_timeline returns).",
+ "description": "Read a page by slug (fuzzy optional; renamed slugs redirect). To edit, pass include_content:true and send `content` to put_page, or use edit_page. Timeline rows need include_timeline_entries.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_page",
"parameters": {
"fuzzy": "boolean?",
@@@ -387,14 -362,10 +387,14 @@@
"slug"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences; automatic graph links are skipped for untrusted writes. A stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG.",
+ "description": "Replace a complete Markdown page: content REPLACES the whole page. Read get_page include_content:true; pass its revision as expected_revision (omit to create). Keep a request_id UUID; retry with identical arguments. Remote callers: graph links are skipped; a stdio `gbrain serve` sweeps them later, `gbrain serve --http` does not self-sweep. Small changes: edit_page.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
"name": "put_page",
"parameters": {
"allow_empty": "boolean?",
@@@ -506,14 -471,10 +506,14 @@@
"slug"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "List pages with optional filters. For 'what's recent / what did I touch this week' questions, use list_pages with sort=updated_desc instead of semantic search. Default 50 rows; remote callers are capped at 100 (local CLI callers' explicit limits are honored). A result with exactly `limit` rows may be truncated. For exhaustive listing, page with updated_after=<last row's updated_at_iso> + updated_after_slug=<last row's slug> until a page returns fewer rows than the limit (the keyset forces sort=updated_asc; a bare updated_after cursor skips rows sharing the cursor timestamp).",
+ "description": "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows (remote max 100); a full page may be truncated: continue with updated_after + updated_after_slug from the last row.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "list_pages",
"parameters": {
"include_deleted": "boolean?",
@@@ -640,14 -590,10 +640,14 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "admin"
},
{
- "description": "Capture a quick note into the brain — the \"just remember this\" write. Auto-derives a stable inbox/ slug from the content date + hash (recapturing identical text is idempotent), merges frontmatter, refuses binary/empty payloads, then delegates to put_page (inheriting its fences and provenance stamping). Prefer capture for quick notes and put_page when you need to control the slug, type, or an existing page's content. For structured facts about entities, prefer remember.",
+ "description": "Quick note (\"just remember this\"): auto-slugged under inbox/ by date + content hash, so recapturing is idempotent. Use put_page to control slug or type; remember for facts about entities.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
"name": "capture",
"parameters": {
"content": "string",
@@@ -748,14 -688,10 +748,14 @@@
"id"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Change part of an existing page without resending it: prefer this over put_page for small changes to large pages. Read get_page with include_content:true and pass its revision as expected_revision. Each edit replaces old_text with new_text; edits apply in order, each to the text the previous edit produced, and each old_text must match exactly once in that content. Protected takes and facts sections never match (use the takes_* operations or remember/forget). All edits publish together or none do, through the same receipts, fences and write-through as put_page. Returns the new revision and a unified diff of your view (at most 8 KB). Refusals name the edit: edit_no_match, edit_ambiguous_match (with match_count), edit_protected_span, edit_invalid; a stale revision returns revision_conflict with current_revision. Retain request_id and repeat identical arguments after a pending receipt.",
+ "description": "Change part of a page: prefer this over put_page for small changes. expected_revision is the revision from get_page include_content:true. Each old_text must match exactly once; edits apply in order, all or none. Stale revision: revision_conflict.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
"name": "edit_page",
"parameters": {
"edits": "array",
@@@ -812,14 -747,10 +812,14 @@@
"edits"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "Read your durable write receipt by request_id. Requires write scope and this operation in the current grant. Foreign, missing, and no-longer-accessible requests return the same not_found error; private journal input and recovery bytes are never returned.",
+ "description": "Read the receipt of your write by request_id (after write_pending or a lost reply).",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_write_request",
"parameters": {
"request_id": "string"
@@@ -836,14 -766,10 +836,14 @@@
"request_id"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "List your currently authorized write receipts in one source, newest first. Useful when an acknowledgment was lost. Results and pagination exclude other principals and inaccessible targets; no private payloads or cross-principal queue counts are exposed.",
- "description": "List your write receipts in one source, newest first.",
++ "description": "List your write receipts in one source, newest first. Use when a request_id was lost.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "list_write_requests",
"parameters": {
"before": "string?",
@@@ -869,14 -794,10 +869,14 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "Cancel your accepted write before publication starts. Returns the actual receipt: running/recovering or already-terminal requests may remain unchanged. Cancellation cannot undo published bytes or a committed fact withdrawal.",
+ "description": "Cancel your accepted write before it publishes. Returns the actual receipt.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
"name": "cancel_write_request",
"parameters": {
"request_id": "string"
@@@ -893,16 -813,13 +893,17 @@@
"request_id"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (adds multi-query expansion); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.",
+ "description": "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal questions: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "search",
"parameters": {
+ "fields": "string?",
"limit": "number?",
"mode": "string?",
"offset": "number?",
@@@ -916,11 -833,18 +917,19 @@@
"token_budget": "number?",
"types": "array?"
},
+ "required_scopes": [],
"schema": {
"properties": {
+ "fields": {
+ "description": "lean (remote default) or full.",
+ "enum": [
+ "lean",
+ "full"
+ ],
+ "type": "string"
+ },
"limit": {
- "description": "Max results (default 20)",
+ "description": "Max results (default 20).",
"type": "number"
},
"mode": {
@@@ -992,14 -916,10 +1001,14 @@@
"query"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience or find_anomalies (raw transcripts are owner-only: `gbrain transcripts recent` on the brain host). Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged. Needs an embedding key for semantic recall and a chat-model key for expansion; without them it runs keyword-only and a degraded_recall notice says so (a thin result is then not proof of absence).",
- "description": "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies, get_recent_transcripts. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). fields: \"full\" adds diagnostics.",
++ "description": "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies; raw transcripts: `gbrain transcripts recent` on the brain host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key, else keyword-only; expansion needs a chat-model key. fields: \"full\" adds diagnostics.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "query",
"parameters": {
"adaptive_return": "boolean?",
@@@ -1566,14 -1434,10 +1584,14 @@@
"slug"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "List a page's incoming links (who points at it). Use when finding everything that mentions or relates to an entity. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
- "description": "List links pointing to a page.",
++ "description": "List links pointing to a page. Use when finding what mentions an entity.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_backlinks",
"parameters": {
"all_sources": "boolean?",
@@@ -1600,29 -1463,20 +1618,29 @@@
"slug"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "List distinct link_source provenances in the brain with edge counts (e.g. citation-graph, manual, markdown)",
+ "description": "Link provenances in the brain (e.g. markdown, manual) with edge counts.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "list_link_sources",
"parameters": {},
+ "required_scopes": [],
"schema": {
"properties": {},
"required": [],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Traverse link graph from a page. Remote callers default to bidirectional edges (GraphPath[]) at depth 2 (pass depth explicitly for deeper walks); trusted local no-filter callers keep the legacy node shape at depth 5.",
+ "description": "Walk the link graph from a page. Remote callers get bidirectional paths at depth 2 by default.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "traverse_graph",
"parameters": {
"all_sources": "boolean?",
@@@ -1669,14 -1522,10 +1687,14 @@@
"slug"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Append an entry to the canonical Markdown timeline and structured timeline store in one committed write. Exact replay changes neither store.",
+ "description": "Append a dated entry to a page timeline. Replaying the same entry changes nothing.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
"name": "add_timeline_entry",
"parameters": {
"date": "string",
@@@ -1979,14 -1782,10 +1997,14 @@@
"slug"
],
"type": "object"
- }
+ },
+ "scope": "admin"
},
{
- "description": "List the skills this agent's brain publishes. A skill is a named prose instruction set (NOT executable code) that teaches you how to do a task using this server's other tools. Returns a flat catalog — each entry has a name, one-line description, triggers (phrasings that should invoke it), and `usable_tools` / `unavailable_tools` (which tools the skill calls that you CAN vs CANNOT call given this server + your access). To actually use a skill, call get_skill with its name, read the returned prose, and follow it — calling the correspondingly-named tools on THIS server. The response also carries an `instructions` envelope explaining this protocol. On a shared brain, use schema_version:2 for source-qualified identities, immutable revisions, pagination and complete declared requirements. Only authorized sources and owner-approved file classes are visible; pre-migration servers retain their legacy prose catalog. Read-scope; published only when the brain owner enabled mcp.publish_skills.",
+ "description": "Skills: prose instruction sets (NOT executable code) for tasks with this server's tools, with triggers, usable_tools and unavailable_tools. Use one via get_skill.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "list_skills",
"parameters": {
"cursor": "string?",
@@@ -2021,14 -1819,10 +2039,14 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Fetch one skill's full instructions by name. Returns `{name, frontmatter (sanitized), body, usable_tools, unavailable_tools, client_guidance}`. The `body` is prose — read it as your operating instructions for this task, and when it says to search / store / look something up, call the same-named MCP tool on THIS server. There is nothing to 'execute' — the value is the instructions plus your tool calls back to this server. Tools listed in `unavailable_tools` won't work for you (not exposed here, or beyond your access) — adapt accordingly. Size-capped; read-scope; requires the owner to have enabled mcp.publish_skills. On a shared brain, pass schema_version:2 with qualified_id and revision from discovery to fetch exact instructions and their approved dependency manifest. get_skill_asset retrieves declared files from that revision as data; downloading never grants execution or tool permissions.",
+ "description": "Fetch a skill's prose and follow it: when it says search or store, call the same-named MCP tool here. There is nothing to execute. unavailable_tools won't work for you.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_skill",
"parameters": {
"expected_brain_id": "string?",
@@@ -2078,17 -1871,12 +2096,17 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "List brain-resident skillpacks this brain ships (per-source). Returns each pack's skills, one-line descriptions, the schema pack it targets + whether that matches this brain, and a git scaffold spec. Read-only; gated by mcp.publish_skills. After orienting, call this and ask the user whether to install any pack the brain offers (gbrain skillpack scaffold <spec>).",
+ "description": "Skillpacks this brain ships, with skills and a scaffold spec to offer the user.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "list_brain_skillpack",
"parameters": {},
+ "required_scopes": [],
"schema": {
"properties": {},
"required": [],
@@@ -2123,14 -1901,10 +2141,14 @@@
"properties": {},
"required": [],
"type": "object"
- }
+ },
+ "scope": "admin"
},
{
- "description": "Read a bounded, owner-approved file from an exact sealed skill revision. Does not execute downloaded bytes.",
+ "description": "Read an approved file from an exact skill revision (data only; never executed).",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_skill_asset",
"parameters": {
"expected_brain_id": "string?",
@@@ -2788,14 -2477,10 +2806,14 @@@
"slug"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Fuzzy-match a partial name or slug to existing page slugs. Use when a slug is uncertain before get_page, links or tags. Needs read scope. On no matches: search for the name instead.",
- "description": "Fuzzy-match a partial slug or title to page slugs.",
++ "description": "Fuzzy-match a partial slug or title to page slugs. Use when a slug is uncertain. Needs read scope.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "resolve_slugs",
"parameters": {
"partial": "string",
@@@ -2886,14 -2560,10 +2904,14 @@@
"summary"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "List recent ingestion events (what was imported, from where, which pages changed). Use when checking whether a source was already ingested. Needs read scope.",
- "description": "Recent ingestion log entries.",
++ "description": "Recent ingestion log entries. Use when checking what was already imported.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_ingest_log",
"parameters": {
"limit": "number?"
@@@ -3132,14 -2758,10 +3150,14 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "admin"
},
{
- "description": "Cancel a waiting, active, or delayed job. Agent-scoped tokens (no admin) can cancel only jobs they own.",
- "description": "Cancel a waiting, active or delayed job you may manage.",
++ "description": "Cancel a waiting, active or delayed job you may manage. Needs admin scope.",
+ "idempotent": false,
+ "local_only": false,
+ "mutating": true,
"name": "cancel_job",
"parameters": {
"id": "number"
@@@ -3316,14 -2907,10 +3334,14 @@@
"payload"
],
"type": "object"
- }
+ },
+ "scope": "admin"
},
{
- "description": "Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. Requires the `agent` OAuth scope. Tools, source, slug prefixes, max concurrency, and daily budget are bound at OAuth client registration time.",
+ "description": "Submit an agent job (agent scope; tools and budget bound to your client). Poll get_agent_job.",
+ "idempotent": false,
+ "local_only": false,
+ "mutating": true,
"name": "submit_agent",
"parameters": {
"allowed_slug_prefixes": "array?",
@@@ -3371,14 -2957,10 +3389,14 @@@
"prompt"
],
"type": "object"
- }
+ },
+ "scope": "agent"
},
{
- "description": "Poll an agent job submitted via submit_agent. Returns a trimmed status view (id, status, timestamps, error_text, result) plus queue_position (waiting jobs ahead in claim order; 0 = next) while the job is still waiting. Requires the `agent` OAuth scope; only jobs owned by the calling client are visible.",
- "description": "Poll a submit_agent job: status, result, queue_position.",
++ "description": "Poll a submit_agent job: status, result, queue_position. Needs agent scope.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_agent_job",
"parameters": {
"id": "number"
@@@ -3977,17 -3498,12 +3995,17 @@@
"claim"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "Introspect the calling identity. Returns one of three transport shapes: {transport: \"oauth\", client_id, client_name, scopes, expires_at, source_id, federated_read}, {transport: \"legacy\", token_name, scopes, expires_at: null}, or {transport: \"local\", scopes: []}, or {transport: \"stdio\", scopes: []} for the auth-less stdio MCP pipe. Throws unknown_transport when the context is ambiguous (remote=true without auth and no transport marker) (fail-closed). Every shape also carries `readiness` (the setup gaps of this install, each with its fix); stdio scopes are the grant of the verified registration.",
+ "description": "Your identity: transport, scopes and, over OAuth, client, source_id and federated_read.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "whoami",
"parameters": {},
+ "required_scopes": [],
"schema": {
"properties": {},
"required": [],
@@@ -4171,14 -3662,10 +4189,14 @@@
"path"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Discover this brain's tool catalog and optionally unlock a wider tool surface for your client. No arguments → the catalog visible to YOUR credentials, grouped by area (tool names + one-line summaries). {tools: [\"name\", ...]} → full read-only schemas for the visible subset of those names (unknown/hidden names are silently omitted). {surface: \"verbs\"|\"starter\"|\"full\"} → persist that tool surface for this client (bounded by the server ceiling; denied when an operator pinned the surface; ~5 changes/hour), then re-issue tools/list to see the new catalog.",
+ "description": "More tools: no arguments lists your catalog; {tools: [names]} returns schemas; {surface} persists a wider surface for your OAuth client.",
+ "idempotent": false,
+ "local_only": false,
+ "mutating": true,
"name": "request_tools",
"parameters": {
"surface": "string?",
@@@ -4207,14 -3693,10 +4225,14 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Returns readable pages recently touched and ranked by activity salience and recency. Unrestricted local reads include deterministic 0..1 emotional_weight, take density, and recency decay. Holder-restricted reads count only permitted active takes, use zero emotional_weight, and select recent pages by updated_at; unrestricted local reads retain take-driven touches. Use this when the user asks what's been going on, what's notable, what's hot, anything crazy happening, or for any open-ended 'current state' question about themselves or their work. Do NOT run a semantic search for these — salience surfaces what's unusual without needing a search term.",
+ "description": "Recently touched pages ranked by salience. Use this when the user asks what's been going on, what's notable, anything crazy happening. Do NOT run a semantic search for these.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "get_recent_salience",
"parameters": {
"days": "number?",
@@@ -4248,14 -3729,10 +4266,14 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "Returns statistical anomalies in recent page activity, grouped by cohort (tag or type). Use this for questions about what stood out, what's unusual, or what changed recently. Returns explanatory cohorts (e.g. '15 pages tagged wedding touched on 2026-04-28, baseline 0.3/day') so you can speak about patterns the user wouldn't have searched for. Cohort kinds: tag, type. Year cohort is deferred to a later release.",
+ "description": "Anomalies in recent page activity, grouped by cohort (tag or type) against a baseline. Use for what stood out, what's unusual or changed. Cohort kinds: tag, type.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "find_anomalies",
"parameters": {
"lookback_days": "number?",
@@@ -5028,14 -4399,10 +5046,14 @@@
"turn_text"
],
"type": "object"
- }
+ },
+ "scope": "write"
},
{
- "description": "MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.",
+ "description": "MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. Remote callers see world facts only. One card: entity; reasoning: synthesize.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "recall",
"parameters": {
"budget_policy": "string?",
@@@ -5126,14 -4492,10 +5144,14 @@@
},
"required": [],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing entities — entity cards + open threads + hot facts, zero-LLM, sub-second. Call at session start (warm cold context) and after compaction (rehydrate what the summary lost). WORLD-ONLY by default; pass include_private (honored for LOCAL trusted callers only) to widen all arms. budget_tokens packs server-side (response reports budget_used + dropped_count; cards pack first, then facts). Branch on structured fields, never prose. protocol_version rides every response.",
+ "description": "MEMORY VERB (v1): budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "context_pack",
"parameters": {
"budget_tokens": "number?",
@@@ -5170,14 -4531,10 +5188,14 @@@
"entities"
],
"type": "object"
- }
+ },
+ "scope": "read"
},
{
- "description": "MEMORY VERB (v1): \"what changed since T\" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts; threads are never dropped). protocol_version rides every response.",
+ "description": "MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. Keep a cursor with session_id, or pass since.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
"name": "delta",
"parameters": {
"budget_tokens": "number?",
diff --cc test/fixtures/goldens/search-c5/notices.json
index 0000000000,dccc1af926..b7a4c52336
mode 000000,100644..100644
--- a/test/fixtures/goldens/search-c5/notices.json
+++ b/test/fixtures/goldens/search-c5/notices.json
@@@ -1,0 -1,437 +1,449 @@@
+ {
+ "with": {
+ "search NULA billing contact": {
+ "content": [
+ "[{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":0.9836065573770493,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":0.4838709677419355,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
+ "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in contracts/numbat-labs-msa).",
- "Saved facts (remember) matching this query, newest first; recall returns more:\n- The billing contact for Numbat Labs is New Person. [entity: numbat-labs; saved 2026-09-01; provenance: user update]"
++ "Saved facts (remember) matching this query, newest first; recall returns more:\n- The billing contact for Numbat Labs is New Person. [entity: numbat-labs; saved 2026-09-01; provenance: user update]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 4,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 49,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "saved_facts": [
+ {
+ "id": 1,
+ "fact": "The billing contact for Numbat Labs is New Person.",
+ "entity_slug": "numbat-labs",
+ "kind": "fact",
+ "valid_from": "2026-09-01 00:00:00+00",
+ "source": "user update"
+ }
+ ],
+ "other_names": [
+ {
+ "name": "Numbat Labs",
+ "alias": "NULA",
+ "slug": "contracts/numbat-labs-msa"
+ }
+ ],
+ "rows": "lean"
+ }
+ },
+ "search Numbat Labs payment terms": {
+ "content": [
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
- "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs)."
++ "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs).",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 3,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "other_names": [
+ {
+ "name": "Numbat Labs",
+ "alias": "NULA",
+ "slug": "crm/numbat-labs"
+ }
+ ],
+ "rows": "lean"
+ }
+ },
+ "search OCFR renewal": {
+ "content": [
+ "[{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight, also known as OCFR. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
+ "Other names in these results (documents may use either; search the one you have not tried): OCFR = Ocelot Freight (declared in crm/ocelot-freight).",
- "Saved facts (remember) matching this query, newest first; recall returns more:\n- Ocelot Freight renewal moves to the platform team. [entity: ocelot-freight; saved 2026-09-02; provenance: user update]"
++ "Saved facts (remember) matching this query, newest first; recall returns more:\n- Ocelot Freight renewal moves to the platform team. [entity: ocelot-freight; saved 2026-09-02; provenance: user update]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 59,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "saved_facts": [
+ {
+ "id": 2,
+ "fact": "Ocelot Freight renewal moves to the platform team.",
+ "entity_slug": "ocelot-freight",
+ "kind": "fact",
+ "valid_from": "2026-09-02 00:00:00+00",
+ "source": "user update"
+ }
+ ],
+ "other_names": [
+ {
+ "name": "Ocelot Freight",
+ "alias": "OCFR",
+ "slug": "crm/ocelot-freight"
+ }
+ ],
+ "rows": "lean"
+ }
+ },
+ "search renewal quote": {
+ "content": [
- "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]"
++ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 1,
+ "retrieved_count": 1,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 30,
+ "dropped": 0,
+ "kept": 1
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "query Numbat Labs payment terms": {
+ "content": [
+ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Account code: NULA. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"}]",
- "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs)."
++ "Other names in these results (documents may use either; search the one you have not tried): NULA = Numbat Labs (declared in crm/numbat-labs).",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 3,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "other_names": [
+ {
+ "name": "Numbat Labs",
+ "alias": "NULA",
+ "slug": "crm/numbat-labs"
+ }
+ ],
+ "crag": {
+ "confidence": "moderate",
+ "reason": "keyword_exact_top",
+ "query_shape": "factual"
+ },
+ "rows": "lean"
+ }
+ },
+ "query OCFR renewal owner": {
+ "content": [
+ "[{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight, also known as OCFR. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
- "Other names in these results (documents may use either; search the one you have not tried): OCFR = Ocelot Freight (declared in crm/ocelot-freight)."
++ "Other names in these results (documents may use either; search the one you have not tried): OCFR = Ocelot Freight (declared in crm/ocelot-freight).",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 59,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "other_names": [
+ {
+ "name": "Ocelot Freight",
+ "alias": "OCFR",
+ "slug": "crm/ocelot-freight"
+ }
+ ],
+ "crag": {
+ "confidence": "moderate",
+ "reason": "keyword_exact_top",
+ "query_shape": "factual"
+ },
+ "rows": "lean"
+ }
+ }
+ },
+ "without": {
+ "search NULA billing contact": {
+ "content": [
- "[{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5081967213114754,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":0.4998656275194841,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]"
++ "[{\"slug\":\"contracts/amendment-one\",\"title\":\"Amendment No. 1: NULA\",\"type\":\"note\",\"chunk_text\":\"Executed amendment for NULA: payment terms change to Net 30.\",\"chunk_id\":3,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL2FtZW5kbWVudC1vbmUiXQ\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5081967213114754,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"},{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":0.4998656275194841,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 3,
+ "retrieved_count": 3,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 74,
+ "dropped": 0,
+ "kept": 3
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "search Numbat Labs payment terms": {
+ "content": [
- "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs . Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"}]"
++ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs . Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"}]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 44,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "search OCFR renewal": {
+ "content": [
- "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"},{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":0.5041322314049587,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"}]"
++ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"},{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":0.5041322314049587,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"}]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "search renewal quote": {
+ "content": [
- "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]"
++ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"}]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 1,
+ "retrieved_count": 1,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 30,
+ "dropped": 0,
+ "kept": 1
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "rows": "lean"
+ }
+ },
+ "query Numbat Labs payment terms": {
+ "content": [
- "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs . Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"}]"
++ "[{\"slug\":\"contracts/numbat-labs-msa\",\"title\":\"MSA: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Master services agreement with Numbat Labs . Payment terms: Net 45.\",\"chunk_id\":2,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"keyword_exact\",\"create_safety\":\"probable\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY29udHJhY3RzL251bWJhdC1sYWJzLW1zYSJd\"},{\"slug\":\"crm/numbat-labs\",\"title\":\"CRM record: Numbat Labs\",\"type\":\"note\",\"chunk_text\":\"Account record. Segment: mid-market. Billing contact: Old Person.\",\"chunk_id\":1,\"score\":0.5948760330578512,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL251bWJhdC1sYWJzIl0\"}]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 44,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "crag": {
+ "confidence": "moderate",
+ "reason": "keyword_exact_top",
+ "query_shape": "factual"
+ },
+ "rows": "lean"
+ }
+ },
+ "query OCFR renewal owner": {
+ "content": [
- "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"},{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":0.5041322314049587,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"}]"
++ "[{\"slug\":\"notes/renewal-playbook\",\"title\":\"Renewal playbook\",\"type\":\"note\",\"chunk_text\":\"Confirm the billing contact, check payment terms, send the renewal quote 60 days before the term ends.\",\"chunk_id\":5,\"score\":1,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0Iiwibm90ZXMvcmVuZXdhbC1wbGF5Ym9vayJd\"},{\"slug\":\"crm/ocelot-freight\",\"title\":\"CRM record: Ocelot Freight\",\"type\":\"note\",\"chunk_text\":\"Account record for Ocelot Freight. Renewal owner: the platform team.\",\"chunk_id\":4,\"score\":0.5041322314049587,\"source_id\":\"default\",\"effective_date\":\"DATE\",\"evidence\":\"weak_semantic\",\"create_safety\":\"unknown\",\"id\":\"gbrain-page:v1:WyJkZWZhdWx0IiwiY3JtL29jZWxvdC1mcmVpZ2h0Il0\"}]",
++ "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (embed_unavailable): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\".\nfix: gbrain init --force --embedding-model voyage:voyage-4 --embedding-dimensions 1024\nnext: tell_user_to_run\nuser_message: Semantic search needs an embedding API key. Voyage AI works with this brain; if you add a key (<provider key>), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are."
+ ],
+ "retrieval": {
+ "returned_count": 2,
+ "retrieved_count": 2,
+ "vector_enabled": false,
+ "expansion_applied": false,
+ "cache": "disabled",
+ "token_budget": {
+ "budget": 12000,
+ "used": 54,
+ "dropped": 0,
+ "kept": 2
+ },
+ "degraded": [
+ {
+ "stage": "embed_unavailable",
+ "reason": "no_provider"
+ }
+ ],
+ "projection_readiness": {
+ "status": "ready",
+ "ready": true
+ },
+ "crag": {
+ "confidence": "weak",
+ "reason": "keyword_relaxed_top",
+ "query_shape": "factual",
+ "escalate_to_think": true
+ },
+ "rows": "lean"
+ }
+ }
+ }
+ }
diff --cc test/mcp-backup-nag.serial.test.ts
index 6b5c756086,bcc8881d66..7bbbbc6a97
--- a/test/mcp-backup-nag.serial.test.ts
+++ b/test/mcp-backup-nag.serial.test.ts
@@@ -111,8 -111,13 +111,13 @@@ type CallOpts = { remote?: boolean; tra
// Default transport is 'stdio' — the ONLY transport the notice fires on.
// Trust-pin tests pass 'http' / undefined explicitly.
+ /** Remote callers get lean rows (C1): the fixture row minus its page_id diagnostic. */
+ function leanResults(): unknown[] {
+ return nextResults.map(r => { const { page_id: _p, ...lean } = r as Record<string, unknown>; return lean; });
+ }
+
-function callSearch(opts: CallOpts = {}) {
- return dispatchToolCall(engineStub, 'search', { query: 'anything at all' }, {
+async function callSearch(opts: CallOpts = {}) {
+ const out = await dispatchToolCall(engineStub, 'search', { query: 'anything at all' }, {
remote: true,
transport: 'stdio',
sourceId: 'default',
diff --cc test/mcp-result-size-ceiling.test.ts
index 0000000000,b8b5a70ffb..3b83c51829
mode 000000,100644..100644
--- a/test/mcp-result-size-ceiling.test.ts
+++ b/test/mcp-result-size-ceiling.test.ts
@@@ -1,0 -1,93 +1,104 @@@
+ /**
+ * E3 + C2 (cost wave): the model-visible size of a canonical remote `search`
+ * and `query` result on a deterministic fixture brain, pinned beside the C3
+ * schema ceiling (test/mcp-schema-budget.test.ts). Every result stays in an
+ * agent's context and is re-sent on every later turn, so a change that grows
+ * it (pretty-printing content[0] grew a search result by about a quarter)
+ * must fail here rather than show up as a cost regression in an eval.
+ *
+ * The fixture has no embedding key; the first test proves the keyword
+ * fallback ran, so the bytes are deterministic. The measured text is every
+ * content block an agent sees: content[0] plus the notice blocks (saved
- * facts, other names).
++ * facts, other names); the keyless degraded_recall notice has its own bound.
+ *
+ * Re-pin procedure (when a change grows the result on purpose): run
+ * `PRINT_RESULT_SIZES=1 bun test test/mcp-result-size-ceiling.test.ts`,
+ * set the ceiling to ceil(measured x 1.05), and say why in the commit
+ * message. Never raise a ceiling to absorb pretty-printing or a dropped lean
+ * projection: those are the regressions this file exists to catch.
+ */
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+ import { importFromContent } from '../src/core/import-file.ts';
+ import { serializeMarkdown } from '../src/core/markdown.ts';
+ import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';
+ import { withEnv } from './helpers/with-env.ts';
+
+ /** ceil(measured x 1.05) on the fixture below. */
+ const CEILINGS = { search: 2540, query: 2540 };
++/**
++ * The keyless fixture also gets the operator contract's degraded_recall
++ * notice (F3) on every HTTP call. It is bounded on its own so the ceilings
++ * above keep pinning rows and evidence blocks at their cost-wave size; a
++ * keyed brain (Cat 40) never sees it. 629 measured at v0.60.45.0, x 1.05.
++ */
++const DEGRADED_NOTICE_MAX_CHARS = 661;
++const isDegradedNotice = (text: string) => text.startsWith('[gbrain notice degraded_recall ');
+
+ const PAGES: Array<[string, string, string]> = [
+ ['crm/numbat-labs', 'CRM record: Numbat Labs', 'Account record. Account code: NULA. Segment: mid-market. Renewal owner: the platform team. Billing contact: Old Person.'],
+ ['contracts/numbat-labs-msa', 'MSA: Numbat Labs', 'Master services agreement with Numbat Labs (account code NULA). Payment terms: Net 45. Renewal is annual with a 60 day notice window.'],
+ ['contracts/amendment-one', 'Amendment No. 1: NULA', 'Executed amendment for NULA: payment terms change to Net 30 from the next invoice.'],
+ ['notes/renewal-playbook', 'Renewal playbook', 'The renewal playbook: confirm the billing contact, check payment terms, and send the renewal quote 60 days before the term ends.'],
+ ['notes/billing-faq', 'Billing FAQ', 'Billing contacts change often. Confirm the current billing contact before sending an invoice or a renewal quote.'],
+ ];
+
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const [slug, title, body] of PAGES) {
+ await importFromContent(engine, slug, serializeMarkdown({}, body, '', { type: 'note', title, tags: [] }), { noEmbed: true, forceRechunk: true });
+ }
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, valid_from) VALUES
+ ('default', 'numbat-labs', 'The billing contact for Numbat Labs is New Person.', 'fact', 'world', 'user update', '2026-09-01'),
+ ('default', 'numbat-labs', 'Numbat Labs renewal quote goes to the billing contact.', 'fact', 'world', 'user update', '2026-09-02')`);
+ }, 120_000);
+
+ afterAll(async () => { await engine?.disconnect(); });
+
+ async function visible(name: 'search' | 'query'): Promise<{ res: ToolResult; text: string }> {
+ const args = name === 'query' ? { query: 'Numbat Labs billing contact renewal', expand: false } : { query: 'Numbat Labs billing contact renewal' };
+ const res = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, name, args, { remote: true, transport: 'http', sourceId: 'default' }));
+ expect(res.isError).not.toBe(true);
- return { res, text: res.content.map(c => c.text).join('\n') };
++ const degraded = res.content.filter(c => isDegradedNotice(c.text));
++ expect(degraded.length).toBe(1);
++ expect(degraded[0].text.length).toBeLessThanOrEqual(DEGRADED_NOTICE_MAX_CHARS);
++ return { res, text: res.content.filter(c => !isDegradedNotice(c.text)).map(c => c.text).join('\n') };
+ }
+
+ describe('canonical remote result size', () => {
+ for (const name of ['search', 'query'] as const) {
+ test(`${name}: keyword fallback (deterministic), notices present`, async () => {
+ const { res } = await visible(name);
+ expect((res._meta?.retrieval as { vector_enabled?: boolean }).vector_enabled).toBe(false);
+ expect(res.content.length).toBeGreaterThan(1);
+ });
+
+ test(`${name}: content[0] is compact JSON (C2)`, async () => {
+ const { res } = await visible(name);
+ const text = res.content[0].text;
+ expect(text).toBe(JSON.stringify(JSON.parse(text)));
+ expect(text).not.toContain('\n ');
+ });
+
+ test(`${name}: model-visible text stays under its ceiling`, async () => {
+ const { text } = await visible(name);
+ if (process.env.PRINT_RESULT_SIZES === '1') process.stderr.write(`[result-size] ${name}: ${text.length} chars (ceiling ${Math.ceil(text.length * 1.05)})\n`);
+ expect(text.length).toBeLessThanOrEqual(CEILINGS[name]);
+ });
+
+ test(`${name}: the ceiling catches pretty-printing or full rows coming back`, async () => {
+ const { res, text } = await visible(name);
+ const rest = text.length - res.content[0].text.length;
+ const body = JSON.parse(res.content[0].text);
+ expect(JSON.stringify(body, null, 2).length + rest).toBeGreaterThan(CEILINGS[name]);
+ const full = await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, () => dispatchToolCall(engine, name,
+ { query: 'Numbat Labs billing contact renewal', ...(name === 'query' ? { expand: false } : {}), fields: 'full' },
+ { remote: true, transport: 'http', sourceId: 'default' }));
- expect(full.content.map(c => c.text).join('\n').length).toBeGreaterThan(CEILINGS[name]);
++ expect(full.content.filter(c => !isDegradedNotice(c.text)).map(c => c.text).join('\n').length).toBeGreaterThan(CEILINGS[name]);
+ });
+ }
+ });
diff --cc test/mcp-schema-budget.test.ts
index 0000000000,ee3ee76cfb..d568d03ddc
mode 000000,100644..100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@@ -1,0 -1,152 +1,169 @@@
+ /**
+ * C3 (cost wave): the starter-surface tool list is re-sent to the model on
+ * every turn, so its size is a cost every connected agent pays. This file
+ * pins:
+ * - the served starter list (Cat 40 configuration: `gbrain serve --surface
+ * starter`, no skill grants) at 25,000 characters or less, with
+ * `mcp.publish_skills` on (fresh-init default) and off, and its cl100k
- * token count;
++ * token count, both measured on what a model receives (name,
++ * description, inputSchema: the Cat 40 harness and the Anthropic/OpenAI
++ * tool APIs drop MCP `annotations`), plus a separate ceiling on the whole
++ * tools/list JSON including the annotations;
+ * - the initialize instructions at their recorded size, so guidance cut
+ * from the schemas cannot move there instead;
+ * - a per-tool budget (the whole tool definition) for every starter op,
+ * under the hard caps of 1,200 characters per description and 200 per
+ * parameter description;
+ * - the minimum guidance each tool must keep (DX-14): purpose, required
+ * input, consequential defaults, the next call, the recovery move.
+ * The longer pre-cut guidance lives in docs/mcp/TOOL_REFERENCE.md.
+ *
+ * Raising a number here needs a reason in the commit message and a check
- * that the served list still fits 25,000 characters. Measured on this
- * branch: 24,763 characters, 5,568 cl100k tokens (was 59,969 / 13,077).
++ * that the served list still fits 25,000 characters. Measured on the cost
++ * wave: 24,763 characters, 5,568 cl100k tokens (was 59,969 / 13,077), whole
++ * JSON. v0.60.45.0 (agent operator wave merged): 24,100 model-visible
++ * characters / 5,414 tokens; 25,735 with annotations, which the wave's
++ * contract derives for every op from its required mutating/idempotent tags.
++ * Per-tool budgets below cover the whole definition, annotations included;
++ * the rows the merge raised are the annotation bytes (+22 to +36) plus the
++ * F10 template text that brought sub-60-character descriptions up to
++ * purpose + next step + scope, and query's key-dependence sentence.
+ */
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+ import { operations, type Operation } from '../src/core/operations.ts';
+ import { filterOpsForSurface, STARTER_OPS } from '../src/mcp/surface.ts';
+ import { buildToolDefs } from '../src/mcp/tool-defs.ts';
+ import { stdioVisibleTools } from '../src/mcp/server.ts';
+ import { GBRAIN_MCP_INSTRUCTIONS } from '../src/mcp/instructions.ts';
+ import { cl100kAvailable, estimateTokens } from '../src/core/chunkers/token-estimate.ts';
+
+ const SERVED_STARTER_MAX_CHARS = 25_000;
+ const SERVED_STARTER_MAX_TOKENS = 5_700;
-const INSTRUCTIONS_MAX_CHARS = 4_042;
++/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.45.0). */
++const SERVED_STARTER_MAX_JSON_CHARS = 26_000;
++/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */
++const INSTRUCTIONS_MAX_CHARS = 4_628;
+ const DESCRIPTION_HARD_CAP = 1_200;
+ const PARAM_DESCRIPTION_HARD_CAP = 200;
+
+ /** Per-tool budget: JSON.stringify of the served tool definition. */
+ const TOOL_BUDGETS: Record<string, number> = {
- add_timeline_entry: 630, cancel_job: 250, cancel_write_request: 330, capture: 1250, context_pack: 760,
- delete_skill: 810, delta: 830, edit_page: 1090, entity: 460, find_anomalies: 500, forget: 560, get_agent_job: 220,
- get_backlinks: 350, get_ingest_log: 200, get_page: 810, get_recent_salience: 630, get_skill: 910,
- get_skill_asset: 780, get_write_request: 300, join_brain: 560, leave_brain: 540, list_brain_skillpack: 200,
- list_link_sources: 190, list_pages: 1090, list_skills: 640, list_write_requests: 390, put_page: 1320,
- put_skill: 1420, query: 3220, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 330, search: 1760,
- submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 660, whoami: 190,
++ add_timeline_entry: 640, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,
++ delete_skill: 810, delta: 830, edit_page: 1090, entity: 460, find_anomalies: 520, forget: 560, get_agent_job: 270,
++ get_backlinks: 430, get_ingest_log: 280, get_page: 810, get_recent_salience: 660, get_skill: 910,
++ get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
++ list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,
++ put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,
++ submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 680, whoami: 230,
+ };
+
+ /** DX-14: phrases each tool's description must keep. */
+ const MINIMUM_GUIDANCE: Record<string, string[]> = {
+ search: ['no LLM expansion', 'top 20', 'NOT proof of coverage', '`query`', 'list_pages', 'return_unit', 'fields: "full"'],
+ query: ['expansion', 'Still top-K', 'return_unit', 'list_pages', '`search` is cheaper', 'LLM call', 'fields: "full"'],
+ put_page: ['REPLACES the whole page', 'get_page include_content:true', 'expected_revision', 'request_id', 'edit_page'],
+ edit_page: ['prefer this over put_page', 'expected_revision', 'exactly once', 'all or none', 'revision_conflict'],
+ get_page: ['include_content:true', 'put_page', 'edit_page'],
+ list_pages: ['sort=updated_desc', 'Default 50', 'truncated', 'updated_after_slug'],
+ capture: ['inbox/', 'idempotent', 'put_page', 'remember'],
+ remember: ['provenance', '`entity`', '`status`', 'write_pending', 'get_write_request'],
+ recall: ['entity', '`query`', 'world facts only', 'synthesize'],
+ entity: ['zero LLM', 'found:false', 'create_safety', 'recall'],
+ forget: ['fact_id', 'Idempotent'],
+ synthesize: ['[EXPENSIVE', 'recall', 'entity'],
+ context_pack: ['session start', 'compaction'],
+ delta: ['session_id', 'since'],
+ get_write_request: ['request_id', 'write_pending'],
+ list_write_requests: ['newest first'],
+ cancel_write_request: ['receipt'],
+ request_tools: ['{tools', '{surface}'],
+ list_skills: ['NOT executable code', 'get_skill', 'usable_tools', 'unavailable_tools'],
+ get_skill: ['same-named MCP tool', 'nothing to execute', 'unavailable_tools'],
+ get_recent_salience: ['Use this when the user asks', 'Do NOT run a semantic search'],
+ find_anomalies: ['grouped by cohort', 'Cohort kinds: tag, type'],
+ submit_agent: ['agent scope', 'get_agent_job'],
+ get_agent_job: ['submit_agent', 'queue_position'],
+ whoami: ['source_id', 'federated_read'],
+ traverse_graph: ['depth'],
+ };
+
-const size = (ops: Operation[]) => JSON.stringify(buildToolDefs(ops)).length - 2 - Math.max(0, ops.length - 1);
++const json = (ops: Operation[]) => JSON.stringify(buildToolDefs(ops)).length - 2 - Math.max(0, ops.length - 1);
++/** What a model receives per tool: the harness bridges forward name, description and inputSchema only. */
++const modelVisible = (ops: Operation[]) => buildToolDefs(ops).map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
++const size = (ops: Operation[]) => JSON.stringify(modelVisible(ops)).length - 2 - Math.max(0, ops.length - 1);
+
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 120_000);
+ afterAll(async () => { await engine?.disconnect(); });
+
+ async function served(publishSkills: boolean): Promise<Operation[]> {
+ await engine.setConfig('mcp.publish_skills', String(publishSkills));
+ return stdioVisibleTools(engine, filterOpsForSurface(operations, 'starter'));
+ }
+
+ describe('served starter tool list (Cat 40 configuration)', () => {
+ test('publish_skills on (the fresh-init default): 34 tools within 25,000 characters', async () => {
+ const ops = await served(true);
+ expect(ops.map(o => o.name)).toContain('get_skill');
+ expect(ops.length).toBe(34);
+ expect(size(ops)).toBeLessThanOrEqual(SERVED_STARTER_MAX_CHARS);
++ expect(json(ops)).toBeLessThanOrEqual(SERVED_STARTER_MAX_JSON_CHARS);
+ });
+
+ test('publish_skills off: within 25,000 characters', async () => {
+ const ops = await served(false);
+ expect(ops.map(o => o.name)).not.toContain('get_skill');
+ expect(size(ops)).toBeLessThanOrEqual(SERVED_STARTER_MAX_CHARS);
+ });
+
+ test('cl100k token ceiling', async () => {
+ if (!cl100kAvailable()) return;
- expect(estimateTokens(JSON.stringify(buildToolDefs(await served(true))))).toBeLessThanOrEqual(SERVED_STARTER_MAX_TOKENS);
++ expect(estimateTokens(JSON.stringify(modelVisible(await served(true))))).toBeLessThanOrEqual(SERVED_STARTER_MAX_TOKENS);
+ });
+
+ test('initialize instructions stay at or below their recorded size', () => {
+ expect(GBRAIN_MCP_INSTRUCTIONS.length).toBeLessThanOrEqual(INSTRUCTIONS_MAX_CHARS);
+ });
+ });
+
+ describe('per-tool schema budgets', () => {
+ const starter = operations.filter(o => STARTER_OPS.has(o.name));
+
+ test('every starter op has a budget', () => {
+ expect(starter.map(o => o.name).sort()).toEqual(Object.keys(TOOL_BUDGETS).sort());
+ });
+
+ for (const op of operations.filter(o => STARTER_OPS.has(o.name))) {
+ test(`${op.name} fits its budget and the hard caps`, () => {
+ const [def] = buildToolDefs([op]);
+ expect(JSON.stringify(def).length).toBeLessThanOrEqual(TOOL_BUDGETS[op.name]);
+ expect(op.description.length).toBeLessThanOrEqual(DESCRIPTION_HARD_CAP);
+ const walk = (p: { description?: string; items?: unknown; properties?: Record<string, unknown> }, path: string): void => {
+ expect((p.description ?? '').length, path).toBeLessThanOrEqual(PARAM_DESCRIPTION_HARD_CAP);
+ if (p.items) walk(p.items as never, `${path}[]`);
+ for (const [k, v] of Object.entries(p.properties ?? {})) walk(v as never, `${path}.${k}`);
+ };
+ for (const [k, p] of Object.entries(op.params)) walk(p as never, `${op.name}.${k}`);
+ });
+ }
+ });
+
+ describe('minimum guidance (DX-14)', () => {
+ for (const [name, phrases] of Object.entries(MINIMUM_GUIDANCE)) {
+ test(name, () => {
+ const op = operations.find(o => o.name === name)!;
+ for (const phrase of phrases) expect(op.description, `${name}: ${phrase}`).toContain(phrase);
+ });
+ }
+
+ test('every required input of a starter tool is declared in its schema', () => {
+ for (const def of buildToolDefs(operations.filter(o => STARTER_OPS.has(o.name)))) {
+ for (const key of def.inputSchema.required) expect(def.inputSchema.properties, `${def.name}.${key}`).toHaveProperty(key);
+ }
+ });
+ });
diff --cc test/serve-http-mcp-dispatch-context.serial.test.ts
index c91e3b75a3,91616d67d3..1ab661b337
--- a/test/serve-http-mcp-dispatch-context.serial.test.ts
+++ b/test/serve-http-mcp-dispatch-context.serial.test.ts
@@@ -87,7 -87,7 +87,7 @@@ async function rpc(base: string, token
return JSON.parse(dataLine ? dataLine.slice('data:'.length) : text).result;
}
- const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'noticeLedger', 'remote', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
-const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'remote', 'resultRows', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
++const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'noticeLedger', 'remote', 'resultRows', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];
describe('POST /mcp dispatch context', () => {
test('full surface: remote http dispatch with the verified auth and token source scope', async () => {