Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/agent-operator-wave

garrytan0b0f7eaa40b5
diff --cc .claude-plugin/plugin.json
index 4b0544508a,4b0544508a..794cf0e51b
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain",
-- "version": "0.60.40.0",
++ "version": "0.60.41.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 0f0bd0e47e,0f0bd0e47e..36933d128d
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "gbrain",
-- "version": "0.60.40.0",
++ "version": "0.60.41.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 f535977d84,a25adbbf42..77f66c397d
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@@ -1,4 -1,4 +1,4 @@@
--<!-- gbrain-runbook-stamp: 0.60.40.0 -->
++<!-- gbrain-runbook-stamp: 0.60.41.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 6236c7f687,e1d7b3b937..0d129f86e8
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -10,176 -10,104 +10,274 @@@ 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.40.0] - 2026-10-04
++## [0.60.41.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.40.0
++## To take advantage of v0.60.41.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.
+
+#### 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.
+
+#### 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.40.0] - 2026-10-04
+
+ **When a page repair fails, gbrain now says exactly what stopped it, and pages whose file only gained new lines can be repaired in a few commands instead of by hand.**
+
+ Each page lives twice in a managed brain: as a markdown file and as a database row. When something edits the file directly, gbrain stops saving new facts to that page so it never overwrites one copy with the other. The repair tool for that (`gbrain sources reconcile`) could fail with `Publication failed (P0001). Inspect owner diagnostics.`, and the diagnostics said nothing. P0001 comes from a safety check inside the database, and gbrain threw away its reason. Now the failure names the table, the kind of write, which safety rule fired and the gbrain build that ran the job, so the next report pins the cause.
+
+ Repairs got easier too. A new read-only classification sorts drifted pages by how they drifted. A new opt-in preview mode fills in the decisions for changes that only add things: contacts appended to a list, a "last used" date that moved forward. Lines added to the body or timeline are shown as suggestions you accept explicitly, because an added line can still contradict an older one. Anything that changed or removed existing text, or touched privacy, titles, tags or other policy fields, still waits for a person.
+
+ ### How to use it
+
+ ```bash
+ # 1. See how a source's drifted pages drifted (read-only, no page text in the output)
+ gbrain sources reconcile <source> --brain host --audit --classify --limit 25 --json
+
+ # 2. Preview one page with the additive rules, read the inserted lines in the private file
+ gbrain sources reconcile <source> <slug> --brain host --preview --auto-additive --out ~/.gbrain/repair/p.json --json
+
+ # 3. Accept the inserted lines once you (or the user) have read them, then apply
+ gbrain sources reconcile <source> <slug> --brain host --preview --auto-additive --accept-suggested --out ~/.gbrain/repair/p2.json --json
+ gbrain sources reconcile <source> <slug> --brain host --apply ~/.gbrain/repair/p2.json --request-id "$(bun -e 'console.log(crypto.randomUUID())')" --json
+
+ # 4. Retry the write that was blocked, with a new request id
+ ```
+
+ ### What you'd see
+
+ | Drift on the page | Classification | What the preview does |
+ | --- | --- | --- |
+ | Contacts appended after every stored entry, repeats kept | `structurally_additive` | Decides it |
+ | `updated` or `phone_last_used` moved forward | `structurally_additive` | Decides it |
+ | New lines in the body or timeline, nothing removed | `additive_with_suggestions` | Suggests it; needs `--accept-suggested` |
+ | A stored sentence edited or deleted | `review_required` | Leaves it for a person |
+ | `visibility`, `access`, title, tags or an `expires_at` changed | `review_required` | Leaves it for a person |
+
+ A refused write now reads like this in the receipt (`write_error_detail`), with no page text and no source names:
+
+ | Field | Example |
+ | --- | --- |
+ | `write_error` | `writer_coordinator_required` |
+ | `table` / `op` | `pages` / `INSERT` |
+ | `branch` / `relationship` | `allowlist` / `different_source` |
+ | `stage` | `publication` or `after_file_publication` |
+
+ `gbrain sources writer status --probe --json` adds `recent_failures`, which also carries the source ids and the gbrain build and host that ran the failed attempt. Those stay owner-only because a source name can itself be private.
+
+ ### Two new doctor checks
+
+ - `managed_guard_schema_drift` warns when a guarded table (pages, tags, timeline entries, takes, facts, aliases, sources) carries a column gbrain never created, and calls out a `source_id` on tags, timeline entries or takes, the #5983 cause.
+ - `publication_refusals` counts writes the database refused in the last 7 days, split by the managed-writer guard, another trigger, and older unclassified P0001 failures, and says what to run next.
+
+ ### Things to watch
+
+ - Restart every long-running gbrain process that shares the database (serve, autopilot, sync jobs) after upgrading. A refusal is most often one older process doing a write the current guard refuses, and the new record names that process's build.
+ - "Structurally additive" checks structure, not truth. The rules never decide prose for you.
+ - Preview files with automatic decisions use artifact format 2. An older gbrain refuses them as malformed rather than guessing.
+
+ ### What we caught and fixed before merging
+
+ The plan went through CEO, engineering and outside-voice review. The reviewers caught that an appended line can contradict an old one, so prose became a suggestion instead of an automatic decision. They caught that the first draft of the diagnostic would have shown source names to remote callers, so names moved behind the owner-only status command. They also caught that the failure record would have been erased by receipt compaction and lost across crash recovery, so it now survives both. We could not reproduce the reporter's P0001 on a clean schema: 14 page and brain states committed on v0.60.35.0 and v0.60.37.0 against real Postgres. The cause turned out to be a schema change on the reporter's brain (a `source_id` column on tags, timeline and take tables that gbrain never creates), fixed in v0.60.38.0 (#5983). With this release, that failure would have reported `relationship: missing_source` on `tags`, and the new doctor check names the stray column directly.
+
+ ## To take advantage of v0.60.40.0
+
+ `gbrain upgrade` applies schema migration v198 (a nullable `error_detail` column on write receipts and a re-installed managed-writer guard). If it did not, or `gbrain doctor` warns about a partial migration:
+
+ 1. **Run the orchestrator:**
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install
+ ```
+ 2. **Restart every gbrain process that shares this database** so all of them run the same build.
+ 3. **Verify:**
+ ```bash
+ gbrain sources writer status --probe --json # recent_failures is present (often empty)
+ gbrain sources reconcile <source> --brain host --audit --classify --limit 5 --json
+ ```
+ 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.
+
+ ### Itemized changes
+
+ #### Diagnostics (#5974)
+ - `gbrain_require_managed_writer()` raises with `TABLE`, `SCHEMA`, `CONSTRAINT = managed_writer_guard:<checkpoint|topology|allowlist>` and a JSON `DETAIL` (`op`, `relationship`, source ids). Migration v198 re-installs it and adds `persistence_requests.error_detail jsonb`.
+ - New `src/core/persistence/publication-failure.ts`: `databaseRefusal` maps a guard P0001 to `writer_coordinator_required` (`origin: database_guard`) and any other P0001 to `storage_error` naming the raising function from the error's `where`. Raw messages, SQL and row values are never kept. `withAttempt` stamps stage, build and host; `publicFailureDetail` strips source ids, build and host for receipts.
+ - `requestError`, `finishUnpublishedFailure`, `markRecovering`, `recoverPublication` and `completeWrite` carry the detail; compaction keeps it. The consumer logs publication failures that used to return without a log line.
+ - Receipts gain `write_error_detail`; refusals carry an agent-facing suggestion (`DATABASE_REFUSAL_HINT`). `sources writer status` gains `recent_failures`. New row in `docs/guides/write-refusals.md`.
+
+ #### Additive drift resolution (#5974)
+ - New `src/core/persistence/reconcile-additive.ts`: `classifyDrift` over the complete file/database delta; `additiveDecisions`; `assertAutoDecisions` rechecks rule, rule version and evidence digest at apply and owner preparation.
+ - `sources reconcile --preview --auto-additive [--accept-suggested]`; preview returns `classification`, `drift_paths`, `auto_decided_paths` and `next_action`. Artifact `format_version: 2` adds `auto_decisions`.
+ - `sources reconcile --audit --classify` adds per-page `classification`, `drift_paths` and `file_modified_after_database`, plus `classified` counts.
+ - Docs: `docs/guides/concurrent-writes.md` (classify and additive section), `RECONCILE_HELP`.
+
+ #### Doctor (#5983, #5974)
+ - New `src/commands/doctor/checks/managed-guard.ts`: `managed_guard_schema_drift` (columns on `GUARDED_TABLES` outside `GUARDED_TABLE_COLUMNS`, pinned to the catalog goldens by `test/doctor-managed-guard.test.ts`) and `publication_refusals` (7-day count by origin). Both link `docs/guides/write-refusals.md#managed-guard-page-children`. `PAGE_CHILD_TABLES` and `GUARDED_TABLES` are now exported from `writer-guard-schema.ts`.
+ - Migration v198 replaces only the guard function (`MANAGED_WRITER_GUARD_FUNCTION_SQL`, no table lock) on top of v197's page-child source resolution.
+
+ #### Tests
+ - `test/persistence-publication-refusal-5974.test.ts` (PGLite and Postgres): cross-source write inside publication, refusal after file replacement with exact restoration, redaction, compaction survival, other P0001 raisers.
+ - `test/persistence-reconcile-additive-5974.test.ts` (PGLite and Postgres): classifier truth table; the reporter's page shape through audit, preview, apply, `remember` and MCP readback; a replaced page staying blocked; tampered evidence and a concurrent file change refusing apply. Both files join the PostgreSQL persistence-validation workflow.
+
## [0.60.39.0] - 2026-10-03
**`gbrain repair failed-writes` replays the `put_page`, `add_timeline_entry` and `remember` calls the managed writer guard refused before v0.60.38.0 (#5983), from the content their failed receipts still hold. Each write is replayed once, and never over a later write of the same page.**
diff --cc TODOS.md
index c9e1598cb0,46d29b9812..f422490824
--- 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.40.0)
++## Agent-first operator wave follow-ups (filed 2026-10-03, follow-up from v0.60.41.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 a35e988522,a35e988522..1889bf9064
--- a/VERSION
+++ b/VERSION
@@@ -1,1 -1,1 +1,1 @@@
--0.60.40.0
++0.60.41.0
diff --cc docs/operations/spend-controls.md
index 3c656c76f5,c933b78540..2e7de850aa
--- 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.40.0 every command that spends money asks for authorization the
++Since v0.60.41.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 openclaw.plugin.json
index 58fe8d87ac,58fe8d87ac..0cc22502e6
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@@ -1,7 -1,7 +1,7 @@@
{
"id": "gbrain-context-engine",
"name": "gbrain",
-- "version": "0.60.40.0",
++ "version": "0.60.41.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --cc package.json
index de5089987f,f180deec1e..0e41982238
--- a/package.json
+++ b/package.json
@@@ -212,7 -207,7 +212,7 @@@
"bun": ">=1.4.0"
},
"license": "MIT",
-- "version": "0.60.40.0",
++ "version": "0.60.41.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 6f36b0fb78,6f36b0fb78..9bbe51034a
--- 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.40.0",
++ "version": "0.60.41.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 f981caee89,f981caee89..13606a70e8
--- 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.40.0",
++ "version": "0.60.41.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 867a487551,867a487551..fe84a490c6
--- 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.40.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.41.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 194ab739ba,194ab739ba..371f5601a1
--- 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.40.0",
++ "version": "0.60.41.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 920b3f41ed,920b3f41ed..05cee2749f
--- 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.40.0",
++ "version": "0.60.41.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 ea751d525c,ea751d525c..6787ab62ad
--- 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.40.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.41.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 a1562e496d,a1562e496d..3f011cce54
--- a/plugin/README.md
+++ b/plugin/README.md
@@@ -1,4 -1,4 +1,4 @@@
--<!-- gbrain-plugin-tree-stamp: 0.60.40.0 -->
++<!-- gbrain-plugin-tree-stamp: 0.60.41.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/agent-contract-baselines/legacy-advice-key.tsv
index 4173f7d430,0000000000..d573c2cad8
mode 100644,000000..100644
--- a/scripts/agent-contract-baselines/legacy-advice-key.tsv
+++ b/scripts/agent-contract-baselines/legacy-advice-key.tsv
@@@ -1,81 -1,0 +1,82 @@@
+# shrink-only baseline for scripts/check-agent-contract.ts rule legacy-advice-key: path<TAB>count
+src/cli/cli-error.ts 1
+src/commands/autopilot/jobs.ts 2
+src/commands/claw-test.ts 11
+src/commands/code-callees.ts 1
+src/commands/code-callers.ts 1
+src/commands/code-def.ts 2
+src/commands/code-refs.ts 2
+src/commands/code-scope.ts 5
+src/commands/company-brain-connect.ts 2
+src/commands/creds.ts 1
+src/commands/doctor/checks/data-integrity.ts 1
+src/commands/doctor/checks/sync-failures.ts 1
+src/commands/engine-status.ts 1
+src/commands/friction.ts 1
+src/commands/google-attachments.ts 1
+src/commands/google-setup-tail.ts 1
+src/commands/google.ts 5
+src/commands/harness-connect.ts 1
+src/commands/hook.ts 2
+src/commands/loops.ts 1
+src/commands/mcp-admin.ts 2
+src/commands/mcp.ts 2
+src/commands/serve-http-clients.ts 1
+src/commands/serve-http-grants.ts 2
+src/commands/serve-http-oauth.ts 1
+src/commands/serve-http-registration.ts 1
+src/commands/serve-http-webhooks.ts 4
+src/commands/skillpack.ts 1
+src/commands/sources-retry-held.ts 3
+src/commands/upgrade.ts 7
+src/core/agent-install/entry.ts 1
+src/core/agent-install/shared-skills.ts 7
+src/core/ai/recipes/llama-server.ts 2
+src/core/ai/recipes/lmstudio.ts 2
+src/core/backup/coverage.ts 11
+src/core/backup/repository.ts 1
+src/core/brainstorm/error-classify.ts 1
+src/core/connectors/sync.ts 8
+src/core/context/hook-heartbeat.ts 2
+src/core/cycle.ts 1
+src/core/cycle/patterns.ts 1
+src/core/cycle/synthesize.ts 1
+src/core/error-catalogue.ts 2
+src/core/error-docs.ts 1
+src/core/friction.ts 1
+src/core/harness/capabilities.ts 1
+src/core/harness/install.ts 4
+src/core/harness/shared-skills.ts 3
+src/core/harness/status.ts 2
+src/core/harness/verify.ts 1
+src/core/ops/code-intel.ts 2
+src/core/ops/facts.ts 2
+src/core/ops/search.ts 1
+src/core/output/post-write.ts 1
- src/core/persistence/diagnostics.ts 2
++src/core/persistence/diagnostics.ts 3
+src/core/persistence/effect-retry.ts 7
+src/core/persistence/health.ts 1
+src/core/persistence/memory-prepare.ts 1
+src/core/persistence/onboarding.ts 1
+src/core/persistence/page-advisories.ts 1
+src/core/persistence/params.ts 1
++src/core/persistence/reconcile.ts 1
+src/core/persistence/types.ts 1
+src/core/pg-access-classify.ts 18
+src/core/schema-pack/lint-rules.ts 16
+src/core/search/projection-readiness.ts 2
+src/core/shared-skills/adapter.ts 1
+src/core/shared-skills/migration-members.ts 1
+src/core/skillopt/benchmark.ts 20
+src/core/skillopt/bootstrap-benchmark.ts 5
+src/core/skillopt/bundled-skill-gate.ts 1
+src/core/skillopt/checkpoint.ts 1
+src/core/skillopt/cycle-phase.ts 2
+src/core/skillopt/lock.ts 1
+src/core/skillopt/models-plan.ts 1
+src/core/skillopt/orchestrator.ts 6
+src/core/skillpack/preconditions.ts 9
+src/core/skillpack/shared-brain-bridge.ts 7
+src/core/sync-cost-gate.ts 3
+src/core/verbs.ts 1
+src/mcp/capabilities.ts 1
diff --cc skills/migrations/v0.60.11.0.md
index 9e83264da3,f56399e9cf..d5de7de5c2
--- 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.40.0 and later bind repair approval to the previewed plan).
++ (gbrain v0.60.41.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 0d03503601,5e84bca7de..1454f36c3f
--- 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": "ea40e8d06b92f4c9b15bf9a794f3a8f9021a2379382d884d88319065dd2be011",
- "migrations/v0.60.11.0.md": "ad3086df4eceff272f08bf16d674be404b97963292729b280f44268c583f77c5",
++ "migrations/v0.60.11.0.md": "6da03fdcf2b3d3d960e3379ccb949dce06247687f965a0398f6085055326aa87",
"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/source-reconcile.ts
index 045289c346,2bcdb6fb70..0e1f0c075a
--- a/src/commands/source-reconcile.ts
+++ b/src/commands/source-reconcile.ts
@@@ -103,39 -102,35 +113,50 @@@ export function parseReconcileArgs(args
}
const applying = flags.has('--apply');
if (applying && ['--preview', '--from', '--decisions', '--out', '--audit', '--backups', '--remove-backup'].some(flag => flags.has(flag))) {
- throw new OperationError('invalid_params', 'Apply cannot be combined with preview, decisions, output, or audit options.');
+ throw opError('invalid_params', 'Apply cannot be combined with preview, decisions, output, or audit options.',
+ 'Run apply on its own: the resolved preview file after --apply, --request-id and --brain only. Make or resolve previews in a separate command first.');
}
- if (!applying && flags.has('--request-id')) throw new OperationError('invalid_params', '--request-id is only valid with --apply.');
- if (applying && !isWriteRequestId(flags.get('--request-id'))) throw new OperationError('invalid_params', 'Apply requires an explicit UUID --request-id.');
- if (flags.has('--decisions') && !flags.has('--from')) throw new OperationError('invalid_params', '--decisions requires --from.');
- if (!audit && !flags.has('--backups') && (flags.has('--limit') || flags.has('--after'))) throw new OperationError('invalid_params', '--limit and --after are only valid with --audit or --backups.');
- if (audit && ['--preview', '--out', '--from', '--decisions', '--auto-additive', '--accept-suggested'].some(flag => flags.has(flag))) throw new OperationError('invalid_params', 'Audit cannot create or resolve a page preview.');
- if (flags.has('--classify') && !audit) throw new OperationError('invalid_params', '--classify is only valid with --audit.');
- if ((applying || backups) && (flags.has('--auto-additive') || flags.has('--accept-suggested'))) throw new OperationError('invalid_params', '--auto-additive and --accept-suggested only shape a preview.');
- if (flags.has('--accept-suggested') && !flags.has('--auto-additive')) throw new OperationError('invalid_params', '--accept-suggested requires --auto-additive.');
- if (flags.has('--auto-additive') && flags.has('--decisions')) throw new OperationError('invalid_params', '--auto-additive computes its own decisions; omit --decisions.');
+ if (!applying && flags.has('--request-id')) throw opError('invalid_params', '--request-id is only valid with --apply.',
+ 'Drop --request-id: previews, audits and backup listings change nothing and take no request ID.');
+ if (applying && !isWriteRequestId(flags.get('--request-id'))) throw opError('invalid_params', 'Apply requires an explicit UUID --request-id.',
+ 'Add --request-id with a new UUID for a first apply. After a lost response or a pending receipt, reuse the same request_id with the same arguments instead of a new one.');
+ if (flags.has('--decisions') && !flags.has('--from')) throw opError('invalid_params', '--decisions requires --from.',
+ 'Add --from with the preview file the decisions resolve, and --out with a new file for the resolved preview.');
+ if (!audit && !flags.has('--backups') && (flags.has('--limit') || flags.has('--after'))) throw opError('invalid_params', '--limit and --after are only valid with --audit or --backups.',
+ 'Drop --limit and --after, or use them with --audit (source only) or --backups (one page).');
- if (audit && ['--preview', '--out', '--from', '--decisions'].some(flag => flags.has(flag))) throw opError('invalid_params', 'Audit cannot create or resolve a page preview.',
- 'Run the audit without --preview, --out, --from or --decisions, then preview a page it lists in a separate command.');
++ if (audit && ['--preview', '--out', '--from', '--decisions', '--auto-additive', '--accept-suggested'].some(flag => flags.has(flag))) throw opError('invalid_params', 'Audit cannot create or resolve a page preview.',
++ 'Run the audit without --preview, --out, --from, --decisions, --auto-additive or --accept-suggested, then preview a page it lists in a separate command.');
++ if (flags.has('--classify') && !audit) throw opError('invalid_params', '--classify is only valid with --audit.',
++ 'Add --audit (with --source), or drop --classify.');
++ if ((applying || backups) && (flags.has('--auto-additive') || flags.has('--accept-suggested'))) throw opError('invalid_params', '--auto-additive and --accept-suggested only shape a preview.',
++ 'Use --auto-additive (and --accept-suggested) with --preview, then apply the written preview with --from.');
++ if (flags.has('--accept-suggested') && !flags.has('--auto-additive')) throw opError('invalid_params', '--accept-suggested requires --auto-additive.',
++ 'Add --auto-additive, or drop --accept-suggested.');
++ if (flags.has('--auto-additive') && flags.has('--decisions')) throw opError('invalid_params', '--auto-additive computes its own decisions; omit --decisions.',
++ 'Drop --decisions, or drop --auto-additive and resolve the preview with --decisions.');
if (backups && ['--preview', '--out', '--from', '--decisions', '--apply', '--audit'].some(flag => flags.has(flag)) || flags.has('--backups') && flags.has('--remove-backup')) {
- throw new OperationError('invalid_params', 'Backup administration cannot be combined with preview, apply, audit, or another backup action.');
+ throw opError('invalid_params', 'Backup administration cannot be combined with preview, apply, audit, or another backup action.',
+ 'Run --backups (list) or --remove-backup (delete one reference) on its own, with only --brain, --limit, --after and --json.');
}
const brain = flags.get('--brain') as string | undefined;
- if (brain !== undefined && !isValidSourceId(brain)) throw new OperationError('invalid_params', 'Invalid brain ID.');
+ if (brain !== undefined && !isValidSourceId(brain)) throw opError('invalid_params', 'Invalid brain ID.',
+ 'Pass --brain host for the local brain, or the ID of a mounted brain; the command in fix lists mounted brain IDs.',
+ { fix: readFix('Lists the mounted brains and their IDs.', { argv: ['gbrain', 'mounts', 'list', '--json'] }) });
const params: Record<string, unknown> = { source_id: source, ...(slug ? { slug } : {}) };
if (backups) {
params.action = flags.has('--backups') ? 'list' : 'remove';
if (flags.has('--remove-backup')) params.backup_reference = flags.get('--remove-backup');
- if (flags.has('--after') && !isWriteRequestId(flags.get('--after'))) throw new OperationError('invalid_params', 'Backup pagination requires a request UUID cursor.');
+ if (flags.has('--after') && !isWriteRequestId(flags.get('--after'))) throw opError('invalid_params', 'Backup pagination requires a request UUID cursor.',
+ 'Pass --after exactly as the previous backup listing returned its cursor (a request UUID), or omit it to start from the newest backup.');
}
if (applying) params.request_id = flags.get('--request-id');
+ if (flags.has('--auto-additive')) params.auto_additive = true;
+ if (flags.has('--accept-suggested')) params.accept_suggested = true;
+ if (flags.has('--classify')) params.classify = true;
if (flags.has('--limit')) {
const limit = Number(flags.get('--limit'));
- if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new OperationError('invalid_params', 'Audit limit must be an integer from 1 to 100.');
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw opError('invalid_params', 'Audit limit must be an integer from 1 to 100.',
+ 'Pass --limit as a whole number from 1 to 100, or omit it for the default page size.');
params.limit = limit;
}
if (flags.has('--after')) params.after = flags.get('--after');
diff --cc src/core/cli-flag-registry.generated.ts
index 22d1256552,a84bd94360..e63ffb78c1
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@@ -94,31 -91,31 +94,31 @@@ export const CLI_FLAG_REGISTRY: Record<
'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', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--fact', '--federated-read', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--no-accept-pending', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--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', '--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'],
'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', '--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', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--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'],
+ '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'],
- 'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
+ 'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--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'],
- 'serve': ['--access', '--apply-rewrites', '--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--oauth-request', '--operations', '--port', '--prefer-postgres', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--url', '--yes'],
+ 'serve': ['--access', '--apply-rewrites', '--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--fail-fast', '--help', '--http', '--json', '--log-full-params', '--oauth-request', '--operations', '--port', '--prefer-postgres', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--tools-json', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
- 'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],
+ 'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--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', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--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'],
+ 'sources': ['--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'],
'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'],
diff --cc src/core/persistence/coordinator.ts
index a61e007270,157358d331..43f8e313f2
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@@ -321,11 -289,9 +325,11 @@@ export async function publishMutation(e
}
export async function recoverPublication(engine: BrainEngine, id: string, hostId = localHostId(), alreadyLocked = false,
- terminalError?: { code: string; message: string }, capacityAlreadyHeld = false, hooks: PublicationHooks = {}): Promise<WriteRequest> {
+ terminalError?: PublicationFailure, capacityAlreadyHeld = false, hooks: PublicationHooks = {}): Promise<WriteRequest> {
let row = await getWriteRequestById(engine, id);
- if (!row) throw new OperationError('not_found', 'Write request not found.');
+ if (!row) throw opError('not_found', 'Write request not found.',
+ 'The write request is no longer in the journal (it was compacted or never existed), so there is nothing to recover. Inspect the canonical owners for requests that still need recovery.',
+ { fix: ownerStatusFix() });
if (!row.recovery) return row;
assertMutationProtocol(row);
const binding = await getWorktreeBinding(engine, row.source_id, hostId);
diff --cc src/core/persistence/journal.ts
index f14cc96276,5952f4b0c0..321d4b59cc
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@@ -327,16 -306,12 +328,16 @@@ export async function completeWrite(tx
const keys = ['brain', principalKey(requestPrincipal(row)), ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])];
await lockCounters(tx, keys);
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
- if (!current) throw new OperationError('not_found', 'Write request not found.');
+ if (!current) throw opError('not_found', 'Write request not found.',
+ `The journal row of request ${row.request_id} in source ${row.source_id} disappeared before its completion was recorded, so no outcome was saved. Inspect the source's requests with the command in fix before submitting anything again.`,
+ { fix: ownerStatusFix(row.source_id) });
if (isTerminal(current)) return current;
- if (row.execution_token !== current.execution_token) throw new OperationError('write_claim_lost', 'Write claim changed before completion.');
+ if (row.execution_token !== current.execution_token) throw opError('write_claim_lost', 'Write claim changed before completion.',
+ `Another owner pass claimed request ${row.request_id} in source ${row.source_id} before this pass recorded its outcome, so this pass's completion was discarded; the current claim records the final outcome. Inspect the request with the command in fix instead of resubmitting it.`,
+ { fix: requestInspectFix(row) });
const [effects] = await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytes
FROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);
- if (jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + Number(effects.bytes) > Number(current.terminal_reservation)) throw capacityError('terminal result and effects exceed their reserved bounded encoding');
+ if (jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + (error?.detail ? jsonBytes(error.detail) : 0) + Number(effects.bytes) > Number(current.terminal_reservation)) throw capacityError('terminal result and effects exceed their reserved bounded encoding');
// Only publication stamps the consumer; failures, cancellations and conflicts leave it unset.
const stamp = writerStamp();
const [done] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,
diff --cc src/core/persistence/reconcile-audit.ts
index 18e3a68d42,2aeba2ff22..d1fdd27821
--- a/src/core/persistence/reconcile-audit.ts
+++ b/src/core/persistence/reconcile-audit.ts
@@@ -11,7 -11,9 +11,10 @@@ import { submissionAuthority } from './
import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter, verifyLocalWriter } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
import { prepareFileTarget } from './page-prepare.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+ import { readReconcileState } from './reconcile-state.ts';
+ import { reconcileCanonical } from './reconcile-merge.ts';
+ import { classifyDrift } from './reconcile-additive.ts';
export interface ReconcileAuditReport extends Record<string, unknown> {
source_id: string;
@@@ -25,20 -29,14 +30,20 @@@
}
export async function auditCanonicalSource(engine: BrainEngine, sourceId: string,
- options: { limit?: number; after?: string } = {}): Promise<ReconcileAuditReport> {
+ options: { limit?: number; after?: string; classify?: boolean } = {}): Promise<ReconcileAuditReport> {
const limit = options.limit ?? 25;
if (!isValidSourceId(sourceId) || !Number.isInteger(limit) || limit < 1 || limit > 100) {
- throw new OperationError('invalid_params', 'Audit requires an explicit source and a limit from 1 to 100.');
+ throw opError('invalid_params', 'Audit requires an explicit source and a limit from 1 to 100.',
+ 'Pass one registered source ID and a limit from 1 to 100 (default 25); the command in fix lists source IDs.',
+ { fix: readFix('Lists the registered sources and their IDs.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
}
if (options.after !== undefined) {
- if (typeof options.after !== 'string') throw new OperationError('invalid_params', 'The audit cursor must be a page slug.');
- try { validateSlug(options.after); } catch { throw new OperationError('invalid_params', 'The audit cursor must be a valid page slug.'); }
+ if (typeof options.after !== 'string') throw opError('invalid_params', 'The audit cursor must be a page slug.',
+ "Pass --after exactly as the previous audit's next_after slug, or omit it to start from the first page.");
+ try { validateSlug(options.after); } catch {
+ throw opError('invalid_params', 'The audit cursor must be a valid page slug.',
+ "Pass --after exactly as the previous audit's next_after slug, or omit it to start from the first page.");
+ }
}
const hostId = existingLocalHostId();
const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;
@@@ -91,27 -85,43 +99,48 @@@
return report;
}
+ /** #5974: read-only structural classification of one drifted page; reports paths and rule outcomes, never values. */
+ async function classifyFinding(engine: BrainEngine, sourceId: string, slug: string, counts: Record<string, number>) {
+ try {
+ const state = await readReconcileState(engine, sourceId, slug);
+ const classification = classifyDrift(state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags));
+ const verdict = classification.verdict === 'no_drift' ? 'formatting_only' : classification.verdict;
+ counts[verdict]++;
+ const updated = Date.parse(String(state.snapshot.page.updated_at ?? ''));
+ const suggestion = verdict === 'formatting_only' ? `Only formatting differs. Preview with gbrain sources reconcile ${sourceId} ${slug} --brain <brain> --preview; the result is the database content.`
+ : verdict === 'review_required' ? `Not structurally additive. Preview gbrain sources reconcile ${sourceId} ${slug} --brain <brain> --preview --out <new file> and ask the user before deciding the review paths.`
+ : `Preview gbrain sources reconcile ${sourceId} ${slug} --brain <brain> --preview --auto-additive --out <new file>${verdict === 'additive_with_suggestions' ? ', read the inserted lines, then add --accept-suggested' : ''}; apply it with a new request ID.`;
+ return { classification: verdict, suggestion, drift_paths: classification.paths.map(({ path, class: kind, reason }) => ({ path, class: kind, reason })),
+ ...(Number.isFinite(updated) ? { file_modified_after_database: statSync(state.path).mtimeMs > updated } : {}) };
+ } catch {
+ counts.error++;
+ return { classification: 'error' };
+ }
+ }
+
export async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown>): Promise<ReconcileAuditReport> {
- if (Object.keys(params).some(key => !['source_id', 'limit', 'after'].includes(key)) || !isValidSourceId(params.source_id)) {
- throw opError('invalid_params', 'Audit accepts only source_id, limit, and after.',
- 'Pass a registered source_id, and optionally limit (1 to 100) and after (the previous next_after slug), with no other fields.');
+ if (Object.keys(params).some(key => !['source_id', 'limit', 'after', 'classify'].includes(key)) || !isValidSourceId(params.source_id)
+ || params.classify !== undefined && typeof params.classify !== 'boolean') {
- throw new OperationError('invalid_params', 'Audit accepts only source_id, limit, after, and classify.');
++ throw opError('invalid_params', 'Audit accepts only source_id, limit, after, and classify.',
++ 'Pass a registered source_id, and optionally limit (1 to 100), after (the previous next_after slug) and classify (true or false), with no other fields.');
}
const writer = currentVerifiedLocalWriter() ?? await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));
if (writer.remote || writer.principal.kind !== 'local_cli' || writer.grant.slugPrefixes !== null) {
- throw new OperationError('permission_denied', 'A whole-source audit requires the existing trusted CLI grant without a slug-prefix restriction.');
+ throw trustedCliRequired('A whole-source audit requires the existing trusted CLI grant without a slug-prefix restriction.');
}
if (!writer.grant.sourceIds.includes('*') && !writer.grant.sourceIds.includes(params.source_id)) {
- throw new OperationError('permission_denied', 'The current CLI grant excludes this source.');
+ throw opError('permission_denied', 'The current CLI grant excludes this source.',
+ `The CLI writer registration does not cover source '${params.source_id}'. Review its grant with the command in fix; widening it is the user's decision.`,
+ { fix: readFix('Shows the CLI writer registration and the sources it grants.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });
}
const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 AND NOT archived', [params.source_id]);
- if (!source) throw new OperationError('source_changed', 'The selected source is unavailable.');
+ if (!source) throw opError('source_changed', 'The selected source is unavailable.',
+ `Source '${params.source_id}' is missing or archived. Check it with the command in fix, and restore an archived source before auditing it.`,
+ { fix: readFix('Lists registered sources, archived ones included.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,
'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');
- const report = await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined });
+ const report = await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined,
+ classify: params.classify === true });
await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,
'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');
return report;
diff --cc src/core/persistence/reconcile-prepare.ts
index 0c572dd422,89e4267697..5a48444a1d
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@@ -22,21 -20,14 +22,22 @@@ import { mergeReconcile, reconcileCanon
import { stabilizeSafetyAssessments } from './reconcile-safety.ts';
import { assertReconcilePins, readReconcileState, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { verifyReconcileBackup } from './reconcile-backup.ts';
+ import { assertAutoDecisions } from './reconcile-additive.ts';
+const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as stored now, with its revision, read-only.`,
+ { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
+const receiptFix = (row: WriteRequest): Action => readFix('Reads the reconcile request\'s durable receipt: its state, outcome and recorded error, read-only.',
+ { argv: ['gbrain', 'write-request', '--', row.request_id] });
+const freshPreview = (sourceId: string, slug: string) => `Generate a fresh preview with gbrain sources reconcile ${sourceId} ${slug} --preview (with the same --brain), review it and apply that file; nothing from this attempt was written.`;
+
function preservePrivateFacts(incoming: string, stored: string): string {
const next = parseFactsFence(incoming), prior = parseFactsFence(stored);
- if (next.warnings.length || prior.warnings.length) throw new OperationError('invalid_params', 'Fact fences must parse losslessly before reconciliation.');
+ if (next.warnings.length || prior.warnings.length) throw opError('invalid_params', 'Fact fences must parse losslessly before reconciliation.',
+ 'The ## Facts table of the file or of the stored page has rows that do not parse cleanly, so reconciliation cannot prove its private facts are kept; nothing was written. Repair the malformed rows in the file, then generate a fresh preview and apply it.');
for (const fact of prior.facts.filter(f => f.visibility !== 'world')) {
if (next.facts.some(f => f.claim === fact.claim && (f.visibility !== fact.visibility || f.rowNum === fact.rowNum && digest(f) !== digest(fact)))) {
- throw new OperationError('permission_denied', 'Reconciliation cannot modify protected private facts; use the scoped fact workflow.');
+ throw opError('permission_denied', 'Reconciliation cannot modify protected private facts; use the scoped fact workflow.',
+ 'The reconciled page would edit, renumber or change the visibility of a private fact, which reconcile never does; nothing was written. Keep those fact rows as stored, generate a fresh preview, and change private facts through the fact tools (remember, forget) instead.');
}
}
const merged = restoreHiddenFactRows(next, prior);
diff --cc src/core/persistence/reconcile-state.ts
index c3cafd5542,578d0ae996..8fa27ebd95
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@@ -157,7 -144,20 +160,22 @@@ export function assertReconcilePins(exp
}
export function validateReconcileArtifact(value: unknown): ReconcileArtifact {
validateReconcileJson(value);
- strictReconcileKeys(value, ['format_version', 'preview_id', 'preconditions', 'preimages', 'decisions', 'conflicts', 'result', 'result_digest', 'status']);
+ const v2 = (value as Record<string, unknown> | null)?.format_version === 2;
+ strictReconcileKeys(value, ['format_version', 'preview_id', 'preconditions', 'preimages', 'decisions', 'conflicts', 'result', 'result_digest', 'status',
+ ...(v2 ? ['auto_decisions'] : [])], ['format_version', 'preview_id', 'preconditions', 'preimages', 'decisions', 'conflicts', 'result', 'result_digest', 'status',
+ ...(v2 ? ['auto_decisions'] : [])]);
+ if (v2) {
- if (!Array.isArray(value.auto_decisions) || !value.auto_decisions.length || value.auto_decisions.length > 1000) throw new OperationError('invalid_params', 'Malformed automatic reconciliation decisions.');
++ if (!Array.isArray(value.auto_decisions) || !value.auto_decisions.length || value.auto_decisions.length > 1000) throw opError('invalid_params', 'Malformed automatic reconciliation decisions.',
++ 'Re-run the same reconcile preview with --auto-additive to recreate the file instead of editing it by hand.');
+ for (const entry of value.auto_decisions as unknown[]) {
+ strictReconcileKeys(entry, ['path', 'rule', 'rule_version', 'evidence_digest']);
+ if (typeof entry.path !== 'string' || typeof entry.rule !== 'string' || !Number.isSafeInteger(entry.rule_version)
+ || typeof entry.evidence_digest !== 'string' || !/^[a-f0-9]{64}$/.test(entry.evidence_digest)) {
- throw new OperationError('invalid_params', 'Malformed automatic reconciliation decisions.');
++ throw opError('invalid_params', 'Malformed automatic reconciliation decisions.',
++ 'Re-run the same reconcile preview with --auto-additive to recreate the file instead of editing it by hand.');
+ }
+ }
+ }
strictReconcileKeys(value.preconditions, ['brain_id', 'source_id', 'source_incarnation', 'slug', 'page_id', 'worktree_id', 'binding_digest',
'owner_epoch', 'revision', 'raw_file_hash', 'relative_path', 'policy_digest', 'withdrawals_digest', 'assessment_at']);
strictReconcileKeys(value.preimages, ['file_base64', 'database', 'stored_page']);
diff --cc src/core/persistence/reconcile.ts
index edfd47679f,34eebe735f..6d972a2e48
--- a/src/core/persistence/reconcile.ts
+++ b/src/core/persistence/reconcile.ts
@@@ -64,28 -64,43 +75,48 @@@ async function config(engine: BrainEngi
return await loadConfigWithEngine(engine, loadConfig()) ?? { engine: engine.kind } as GBrainConfig;
}
export async function runReconcilePreview(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown> & { preview: ReconcileArtifact }> {
- strictReconcileKeys(params, ['source_id', 'slug', 'from', 'decisions', 'output_path'], ['source_id', 'slug']);
+ strictReconcileKeys(params, ['source_id', 'slug', 'from', 'decisions', 'output_path', 'auto_additive', 'accept_suggested'], ['source_id', 'slug']);
+ const auto = params.auto_additive === true;
+ if (params.auto_additive !== undefined && typeof params.auto_additive !== 'boolean'
+ || params.accept_suggested !== undefined && (typeof params.accept_suggested !== 'boolean' || !auto)) {
- throw new OperationError('invalid_params', 'accept_suggested requires auto_additive; both are booleans.');
++ throw opError('invalid_params', 'accept_suggested requires auto_additive; both are booleans.',
++ 'Pass auto_additive: true with accept_suggested: true, or drop accept_suggested.');
+ }
- if (auto && params.decisions !== undefined) throw new OperationError('invalid_params', 'auto_additive computes its own decisions; omit decisions, or resolve manually without auto_additive.');
++ if (auto && params.decisions !== undefined) throw opError('invalid_params', 'auto_additive computes its own decisions; omit decisions, or resolve manually without auto_additive.',
++ 'Drop decisions, or drop auto_additive and resolve the preview with decisions.');
const { sourceId, slug } = await authorize(engine, params.source_id, params.slug);
if (params.output_path !== undefined) {
- if (typeof params.output_path !== 'string') throw new OperationError('invalid_params', 'output_path must be an absolute private file path.');
+ if (typeof params.output_path !== 'string') throw opError('invalid_params', 'output_path must be an absolute private file path.',
+ 'Pass output_path (CLI: --out) as an absolute path to a new file outside every source checkout.');
await assertReconcileOutputPath(engine, sourceId, params.output_path);
}
const from = params.from === undefined ? undefined : validateReconcileArtifact(params.from);
- if (params.decisions !== undefined && !from) throw new OperationError('invalid_params', 'Decisions require the previous private preview artifact.');
- if (from && (from.preconditions.source_id !== sourceId || from.preconditions.slug !== slug)) throw new OperationError('invalid_params', 'The previous preview names a different page.');
+ if (params.decisions !== undefined && !from) throw opError('invalid_params', 'Decisions require the previous private preview artifact.',
+ 'Pass the preview being resolved along with the decisions (CLI: --from with the preview file written by --out).');
+ if (from && (from.preconditions.source_id !== sourceId || from.preconditions.slug !== slug)) throw opError('invalid_params', 'The previous preview names a different page.',
+ `Use the preview made for ${slug} in '${sourceId}', or run the command with the source and slug that preview file names.`);
const state = await readReconcileState(engine, sourceId, slug, from?.preconditions.assessment_at);
if (from) assertPreimages(from, state);
- const decisions = reconcileDecisions(params.decisions ?? from?.decisions ?? []);
+ const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);
+ const classification = auto ? classifyDrift(state.file, database) : undefined;
+ let decisions = reconcileDecisions(params.decisions ?? from?.decisions ?? []);
+ let autoDecisions: AutoDecision[] = params.decisions === undefined ? from?.auto_decisions ?? [] : [];
+ if (classification) {
+ const chosen = additiveDecisions(classification, mergeReconcile(state.file, database, []).conflicts, state.file, database, params.accept_suggested === true);
+ decisions = reconcileDecisions(chosen.decisions);
+ autoDecisions = chosen.auto;
+ }
+ if (autoDecisions.length) assertAutoDecisions(autoDecisions, state.file, database, decisions);
const prepared = await prepareReconcileResult(engine, state, decisions);
- const preview: ReconcileArtifact = { format_version: 1, preview_id: from?.preview_id ?? randomUUID(), preconditions: state.pins,
+ const reviewRequired = classification?.verdict === 'review_required';
+ const preview: ReconcileArtifact = { format_version: autoDecisions.length ? 2 : 1, preview_id: from?.preview_id ?? randomUUID(), preconditions: state.pins,
preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),
decisions, conflicts: prepared.conflicts, result: prepared.result, result_digest: digest(prepared.result),
- status: prepared.conflicts.length ? 'needs_resolution' : 'ready' };
+ status: prepared.conflicts.length || reviewRequired ? 'needs_resolution' : 'ready', ...(autoDecisions.length ? { auto_decisions: autoDecisions } : {}) };
await assertReconcileSize(engine, preview);
return { source_id: sourceId, slug, preview_id: preview.preview_id, status: preview.status,
+ ...(classification ? { classification: classification.verdict, drift_paths: classification.paths,
+ auto_decided_paths: autoDecisions.map(d => d.path), next_action: additiveNextAction(classification, preview.status) } : {}),
conflict_paths: prepared.conflicts.map(c => c.path), protected_paths: prepared.protectedPaths,
migrated_scan_paths: prepared.scanPaths, relative_path: state.pins.relative_path,
line_endings: state.raw.includes(Buffer.from('\r\n')) ? 'crlf' : 'lf',
diff --cc templates/bootstrap/template-repo/README.md
index e310ad5da0,e310ad5da0..25c0c89f98
--- 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.40.0 -->
++<!-- gbrain-template-stamp: 0.60.41.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same