Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master (v0.60.59.0) into capy/aow-followup; re-stamp to v0.60.60.0
garrytan586f7aabf425
diff --cc .claude-plugin/plugin.jsonindex 1e0a30ca35,1e0a30ca35..c7f9252be3--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain",-- "version": "0.60.59.0",++ "version": "0.60.60.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.jsonindex 474042701e,474042701e..af362d6a53--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@@ -1,6 -1,6 +1,6 @@@{"name": "gbrain",-- "version": "0.60.59.0",++ "version": "0.60.60.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.mdindex 2046e04357,2046e04357..a69acb9563--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@@ -1,4 -1,4 +1,4 @@@--<!-- gbrain-runbook-stamp: 0.60.59.0 -->++<!-- gbrain-runbook-stamp: 0.60.60.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --cc CHANGELOG.mdindex 0d4c799a5d,f0073266d1..88a6199256--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,127 -10,103 +10,224 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).- ## [0.60.59.0] - 2026-10-05++## [0.60.60.0] - 2026-10-05++**Background paid jobs ask before they spend and stay inside the amount the user approved, an agent on MCP gets the same setup tips a person at the terminal gets, every install gives the agent the same tool set, and a shared HTTP server that can't open its brain explains why instead of dying.**++Paid background work had a hole. `gbrain enrich --background` put paid jobs in the queue before it asked anyone, and the dollar cap you approved for `book-mirror` was never enforced on the jobs it queued. Now both ask first, store the approval on every job they queue, and the worker stops a command's jobs at the total the user agreed to. An agent talking to gbrain over MCP never saw tips like "your search data is stale"; now they arrive next to the tool call they affect, at most two per session. Depending on how gbrain was installed, the agent got 7, about 30 or about 130 tools; every install path now registers the same middle set, and the agent can widen it in one call. And every refusal gbrain returns now names its own next step.++### The numbers that matter++| What we measured | Before | Now |+| --- | --- | --- |+| `enrich --background` queueing paid jobs before consent | always | never: exit 3 with the consent payload, nothing queued |+| Queued `book-mirror` chapters held to the approved cap | 0 (cap never enforced) | every chapter, one shared total per command |+| Refusal sites with no next step (scanner baseline) | 74 rows; about 210 sites counting funnel call sites | 0, zero-tolerance |+| Tool sets registered by different install paths | 3 (verbs, full, bare) | 1 (`starter`) |+| Agent tasks solved, `starter` surface (Opus 5.5, GPT-6.1 Sol, Sonnet 5.5, Fable 5.1; 10 tasks each) | n/a | 40/40, 7.9M tokens |+| Same tasks on `full` | n/a | 40/40, 12.3M tokens (+55%) |+| Same tasks on `verbs` | n/a | 37/40 |+| A losing `serve --http` when another process holds the brain | exits | stays up on its port, recovers within 5 s of the brain opening |++The surface eval is a ceiling result: every model scored 100% on both `starter` and `full`, so it shows `starter` loses nothing on these tasks while costing a third fewer tokens.++### How to use it++```bash+gbrain enrich --background --max-usd 5 # approve the spend up front+gbrain jobs list --group <spend-group> --json # every job one command queued+gbrain jobs cancel --group <spend-group> # stop them together+gbrain doctor --only legacy_job_authority --json # queued paid jobs and old workers+curl -i http://127.0.0.1:<port>/health # 503 + Retry-After while status-only+gbrain config set mcp.allow_session_widen false # forbid request_tools session widening+```++### Things to watch++- Restart every worker after upgrading. Only upgraded workers claim jobs that carry a spend approval; an older worker stops at the first one in its queue.+- `book-mirror` and `enrich` jobs queued before the upgrade run under a $5 cap. A chapter on an expensive model can stop; rerunning the command skips completed chapters.+- New stdio registrations use `starter`. A skill that needs a tool outside it gets the `unknown_tool` hint whose fix is one `request_tools` call. Existing registrations keep their surface; OpenClaw's manifest is not pinned yet.+- Container health checks that relied on `serve --http` exiting when its brain is unavailable need `--fail-fast` or `GBRAIN_SERVE_FAIL_FAST=1`.+- ## To take advantage of v0.60.59.0++## To take advantage of v0.60.60.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:++1. **Run the orchestrator manually:**+ ```bash+ gbrain apply-migrations --yes+ ```- 2. **Your agent reads `skills/migrations/v0.60.59.0.md` the next time you interact with it.** Migration v205 adds the spend-approval columns to the job queue. Restart every worker, `gbrain serve` and autopilot so queued paid jobs are claimed under the new rules.++2. **Your agent reads `skills/migrations/v0.60.60.0.md` the next time you interact with it.** Migration v205 adds the spend-approval columns to the job queue. Restart every worker, `gbrain serve` and autopilot so queued paid jobs are claimed under the new rules.+3. **Verify the outcome:**+ ```bash+ gbrain doctor --only legacy_job_authority,harness_wiring --json+ ```+4. **If any step fails or the numbers look wrong,** please file an issue:+ https://github.com/garrytan/gbrain/issues with:+ - output of `gbrain doctor`+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists+ - which step broke++ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.++### Behavior changes for scripts and agents++| Area | Before | Now | What to change |+| --- | --- | --- | --- |+| `gbrain enrich --background` | queued jobs, then each job asked or ran | asks before queueing; without `--yes`, `--max-usd`, a preapproval or `spend.posture=tokenmax`, exit 3 with the consent payload and nothing queued; `--dry-run` needs none | relay the estimate, run `fix.argv` after the user agrees |+| `gbrain jobs submit enrich\|subagent` | queued with no consent | same consent gate (exit 3 without authorization); the approval is stored on the job | as above |+| Jobs queued by `book-mirror` and `enrich --background` | no stored approval; cap not enforced on queued jobs | every job carries the approval; all of a command's jobs share one approved total, enforced on every provider attempt | none |+| A queued job whose group total is spent | ran on | dies with `derived_cap_exhausted` or `cost_cap_exceeded`; `result.spend_refusal` carries the group amounts and a rerun fix with twice the cap; when sibling jobs fill the group, it is delayed (no attempt burned) up to 6 times | read `result.spend_refusal`, ask the user before rerunning with a higher cap |+| An unpriced model in a queued paid job | not checked | warns and runs under a derived or default cap; stops with `no_pricing` under a user cap | register the rate, or ask the user |+| `book-mirror`/`enrich` jobs queued before this release | ran under the configured budget | run as `legacy_default` under $5 (enrich: its own `--max-usd` when set) | rerun the command if a chapter stops; completed chapters are skipped |+| Workers older than this release | claimed every job | cannot claim spend-authorized jobs and stop at the first one in their queue | restart every worker after upgrading |+| `gbrain jobs` | no group view | `jobs list --group <id>`, `jobs cancel --group <id>`; `jobs get --json` adds `spend_basis`, `spend_why`, `spend_group` | none |+| `gbrain serve --http` whose brain is locked, missing, damaged or unconfigured | exited | stays up status-only: `/health` 503 with `Retry-After: 5`, `/mcp` lists only `gbrain_status`, OAuth/admin routes 503 `serve_status_only`, `reason` always `unavailable` over HTTP; opens the brain on the same port within 5 s of the fix | `--fail-fast` or `GBRAIN_SERVE_FAIL_FAST=1` keeps the exit |+| An HTTP client after status-only recovery | n/a | no `tools/list_changed` over HTTP; a client that connected during status mode gets 401 with `WWW-Authenticate` | re-list tools or reconnect; sign in again on 401 |+| `gbrain serve --http` with a configured PGLite brain whose data dir is missing | created the brain | answers status-only `missing_brain` | run `gbrain init` or fix the config |+| Doctor `harness_wiring` while a status-only HTTP server runs | "start `gbrain serve --http`" | `serve_status_only` (`transport: http`) with the reason's fix; stale `serve-http-status-<port>.json` markers are removed | follow `fix` |+| Thin clients against a status-only host | generic error | code `serve_status_only` with the host-admin fix, from OAuth discovery or `/token` | relay the fix to the brain host's operator |+| New stdio registrations (readiness fix, init quickstart, `bootstrap hooks` for Claude Code, Codex and opencode, plugins) | `verbs`, `full` or bare `serve` depending on the command | `--surface starter`; `bootstrap hooks` keeps a matching entry and a replaced entry keeps its pinned surface; `--surface` on `bootstrap hooks` and `init` picks another | none |+| Stdio `serve` and `GBRAIN_SURFACE` | ignored on direct registrations | honoured (env > `--surface` > config > full); an invalid value is ignored with a stderr line and one `surface_env_invalid` notice; `serve --http` ignores it and says so; whoami, capabilities and `gbrain_status` report `surface` and `surface_source` | none |+| `request_tools {surface}` on stdio | listed tools only | widens the current session (`tools/list_changed`, returns the new schemas, writes nothing); `mcp.allow_session_widen=false` turns it off; the `unknown_tool` hint's fix is that call (`next: run`) | call `fix.mcp` |+| Stdio MCP sessions | no onboarding notices | onboarding coaching notices on calls whose results show the gap (`onboard_stale_chunks`, `onboard_link_coverage`, `onboard_timeline_coverage`, `onboard_no_takes`) and the first-run decisions bundle on the second successful call; HTTP gets neither | relay or mute them |+| `mute_notice` over stdio | stored, never applied | applies; `first_run_decisions` can be muted; `gbrain notices unmute` clears owner and stdio mutes; `mute_notice` is on the starter surface and its `code` parameter lists no enum | none |+| Refusals from source and writer administration, owner-delegated embed/extract/reindex/sync, repair, takes, capture, forget, shared skills, company-brain receipts, queued-job authorization, `book-mirror` publication and the write path | some carried only a message | a site-specific `suggestion` and, where a next step exists, a filled `fix`; `code` values are unchanged | follow `fix` |+| `gbrain errors` | 14 codes returned on the wire were unregistered | `cache_quota_exceeded`, `catalog_capacity_exceeded`, `follow_approval_required`, `invalid_acknowledgment`, `invalid_receipt`, `invalid_receipt_transition`, `membership_inactive`, `membership_not_found`, `receipt_conflict`, `receipt_fence_changed`, `receipt_fence_required`, `receipt_identity_mismatch`, `skill_unavailable`, `stale_unavailable` are in the registry | none |++Rolling the binary back leaves queued spend-authorized jobs unclaimable; cancel them first with `gbrain jobs cancel --group <id>`.++### Itemized changes++#### Spend approval on queued paid jobs++- `enrich --background` runs the consent gate before it queues anything, single- and multi-source, with the estimate over all sources; the exit-3 fix carries `--yes --max-usd <derived>` (`src/commands/enrich.ts`, `test/enrich-background-consent.test.ts`).+- Migration v205 adds the spend columns and group index to `minion_jobs`. `src/core/minions/spend-record.ts` holds the stored record (effects, cap, cap source, producer argv) with a strict parser; `src/core/minions/spend-authorization.ts` (`runWithJobSpend`) runs both handler seams (worker and child executor) inside `withAIInvocationGuard`, nested in delegated spend.+- `src/core/minions/budget-meter.ts` gains `reserveGroup`: a `group:<id>` key with a lifetime window, a typed `GroupBudgetRefusal` (exhausted or pressure), reservations capped at remaining headroom, and holds past their deadline counted as spent. The OAuth-client daily path is unchanged.+- Claims stamp the fence token and `legacy_default` on pre-upgrade `book-mirror`/`enrich` rows; a trigger fences spend-authorized rows from older workers; children advertise `spend-enforcement-v1` and a parent never hands an authorized row to a child without it.+- `book-mirror` queues one group per run; `jobs submit enrich|subagent` asks for consent; each producer prints a submit summary. Doctor `legacy_job_authority` reports the queued-spend census and warns on long-waiting authorized rows while a registered worker is alive.++#### MCP onboarding and one registration surface++- `src/core/onboard/mcp-onboarding.ts` emits onboarding coaching on stdio calls whose results show the gap, under the coaching budget and mute rules, and stays silent on an empty brain; the first-run decisions bundle arrives on the second successful call. Init's nudge counting is shared and byte-identical.+- `src/core/mcp-registration.ts` builds every stdio registration gbrain writes with `REGISTRATION_SURFACE = starter`; readiness, init, `bootstrap hooks` and the plugin generator use it. Stdio `serve` resolves its surface from `GBRAIN_SURFACE`, `--surface`, config, then full, and reports the source. `request_tools {surface}` widens a stdio session; `hidden-tool-hint.ts` points at it.+- Stdio `mute_notice` reads its own store in dispatch, so mutes apply. New notice codes: `onboard_stale_chunks`, `onboard_link_coverage`, `onboard_timeline_coverage`, `onboard_no_takes`, `first_run_decisions_muted`, `surface_env_invalid`. New config key `mcp.allow_session_widen` (default true).+- The starter surface eval cell (Cat 40 loop, 10 tasks x 4 models x 3 surfaces) is preregistered and recorded in gbrain-evals.++#### Status-only `serve --http`++- `src/commands/serve-http-status.ts` serves the status-only app on the normal listener; `runStatusModeServe` and `reprobe` are shared with stdio, the re-probe is single-flight every 5 s, and recovery swaps the request handler on the same socket. A per-port marker (`src/core/serve-http-status-marker.ts`) feeds doctor, readiness and `mcp expose`.+- `src/core/engine-connect.ts` (`connectEngineForServe`) is the throw-only host connect, including the graduation connect gate; `src/cli.ts` wraps it with the CLI exits and shrinks by 25 lines.+- `src/core/mcp-client.ts` and `src/core/remote-mcp-probe.ts` render the 503 `serve_status_only` envelopes.++#### Refusals name their next step++- Every `opError`/`OperationError`/funnel site carries a site-specific suggestion; `invalid`, `fail`, `deny`, `usage` and `conflict` funnels require one per call site. `scripts/agent-contract-baselines/suggestionless-operation-error.tsv` is deleted, so `suggestionless-operation-error` is zero-tolerance.+- `scripts/check-agent-contract.ts` adds `defaulted-suggestion` (a defaulted or optional suggestion parameter on a function that builds an error) and `generic-suggestion` (whole-text boilerplate such as "see --help"), both with zero hits and guard self-test fixtures.++### For contributors++- The plan and review record live in `docs/designs/AGENT_OPERATOR_FOLLOWUP_WAVE.md`.+- `test/mcp-schema-budget.test.ts` caps the starter `tools/list` JSON at 26,450 characters (`mute_notice` joined starter; `get_page` gained `content_only`; `traverse_graph` gained temporal filters); the model-visible list stays under 25,000.+- Size ceilings moved with rationale in `scripts/module-size-limits.tsv`: `src/cli.ts` down to 3,184; `worker.ts`, `jobs.ts`, `queue.ts`, `init.ts`, `config.ts`, `serve-http.ts` up by the lines this release adds.++ ## [0.60.59.0] - 2026-10-05++ **Every test CI claims to run now proves it ran, by name; red nightly runs open an issue instead of going unseen; PR CI goes green about 30% sooner on about 20% less compute; and `gbrain eval run-all` stops reporting success for work it skipped.**++ This is a test, eval and CI fix wave. For you it makes two eval commands honest. For anyone changing gbrain, CI stops crying wolf: flaky tests are fixed at the root, red nightly runs open an issue instead of going unseen, coverage that never executed now executes, and pull-request CI is faster.++ ### What changes for you++ - **`gbrain eval run-all` tells the truth.** A bare run runs only the suites it can run (BrainBench). Naming a suite it does not run (`--suites longmemeval,replay`) exits 1 with `eval_suite_unwired` and the per-suite commands as the fix, and a failed suite exits 1 instead of 0.+ - **`gbrain eval takes-quality` prices every model the canonical pricing table knows.** The private six-model allowlist is gone. An unpriced model warns and runs; under a `--budget-usd` cap it refuses with `no_pricing` and the `gbrain pricing set` command to register its rate.+++ ### What changes for contributors++ | Pull-request CI (`test.yml` + `e2e.yml`) | Before | Now |+ | --- | --- | --- |+ | Time to green | 1010-1067 s | 696-874 s (median 743 s) |+ | Ubicloud vCPU-minutes per run | 899-940 | 739-755 |+ | Critical path | Selected E2E | a unit shard (Test) |+ | Selected E2E shard max / mean | 904 / 721 s (4 workers) | 365-451 / 323-345 s (8 workers) |+ | Unit shard max / mean | 762 / 542 s | 614-732 / 544-567 s |+ | Tests that ran in no lane | 55 PostgreSQL arms and 12 dead opt-in gates (the compile smoke among them) | 0 (one allowlisted arm with a TODO) |++ Before: the three baseline runs of the master tree on 2026-10-04. Now: the three acceptance runs of this branch on the re-mined weights. Both sets of run ids are in `docs/test-audit/2026-10-04/baseline.md`, and every run executes the baseline's test identities or declares the change in `expected-deltas.tsv`.++ ### Things to watch++ | Change | What to do |+ | --- | --- |+ | Test opt-ins under the old names stop the run with the rename command | `GBRAIN_BASH32_REQUIRE` → `GBRAIN_TEST_BASH32_REQUIRE`, `GBRAIN_PERF_BUDGET_MULTIPLIER` → `GBRAIN_TEST_PERF_BUDGET_MULTIPLIER`, `GBRAIN_SKIP_SUBPROCESS_TESTS` → `GBRAIN_TEST_SKIP_SUBPROCESS`, `GBRAIN_REQUIRE_LAUNCHD` → `GBRAIN_TEST_REQUIRE_LAUNCHD`, `GBRAIN_SKIP_LAUNCHD_E2E` → `GBRAIN_TEST_SKIP_LAUNCHD`, `GBRAIN_ENFORCE_E5_BUDGET` → `GBRAIN_TEST_ENFORCE_E5_BUDGET`, `GBRAIN_REQUIRE_COMPILE` → `GBRAIN_TEST_REQUIRE_COMPILE`. Under the old names the test preload deleted them, so they never worked. |+ | A new `*.serial.test.ts` file needs a row in `scripts/serial-files.tsv` | run `bash scripts/check-test-isolation.sh --as-parallel <file>` first; if it passes and the file touches no process-wide state, name it `*.test.ts` instead |+ | A test file with a `DATABASE_URL`-gated arm needs a Postgres lane | `bun run check:postgres-lanes` names the file and the workflow list to add it to |+ | A stale generated artifact fails `verify` | `bun run regen:all` regenerates everything and lists what changed |+ | `docs/TESTING.md` has a 120 KB cap that only goes down | move subsystem detail next to its code instead of growing the file |+ | E2E narrowing is retired | doc-only changes skip E2E; every other change runs the whole E2E corpus |+ | Removed modules | `src/core/chunkers/semantic.ts`, `src/core/chunkers/llm.ts`, `src/core/search/keyword.ts` and `src/core/search/vector.ts` had no importer (use `src/core/search/hybrid.ts`); the forward-reference bootstrap facade (import `src/core/engine-sql/bootstrap.ts`); `scripts/check-exports-count.sh` (`test/public-exports.test.ts` owns the contract); the skillopt judge and reflect evals |+ | The eval ledger `.gbrain-evals/eval-results.jsonl` is local | it is gitignored; `--record` modes keep appending to your local copy |++ ## To take advantage of v0.60.59.0++ `gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:++ 1. **Run the orchestrator manually:**+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ ```+ 2. **Nothing else to migrate.** There is no schema change.+ 3. **Verify:**+ ```bash+ gbrain doctor --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++ #### Fixes++ - `gbrain eval run-all`: bare runs run wired suites only; `eval_suite_unwired` (exit 1, with `gbrain errors eval_suite_unwired`); a failed suite exits 1.+ - `gbrain eval takes-quality`: canonical pricing for every model, registered overrides first; unpriced models warn and run; `no_pricing` under a user cap.+ - Scale harness: the `find_orphans` known answer reads the op's maximum page and compares with `total_orphans`.++ #### Flakes fixed at the root++ - `test/physical-root-walk.test.ts` pins the `sources add` walk against a subdirectory vanishing mid-walk, with a two-brain `.git` reservation case (B1); a leaked `check-update --refresh-cache` child in the self-upgrade breadcrumb test; facts-queue tests wait on queue counters instead of fixed sleeps; the child-readiness test requires the confirmed timeout message (tini contract documented); a `persistence-deactivate` race where an `await` inside a `.rejects` matcher let Postgres reject before the handler attached and leaked env into later files; the gateway baseline is restored after `gateway-chat.test.ts`, folded from community PR #5907, contributed by @nezovskii. Thank you.+ - `waitFor` deadlines scale with `GBRAIN_TEST_WAIT_MULTIPLIER` (1 to 4; coverage lanes set 2), capped at 50 s.+ - Verify's fallback watchdog (hosts without `timeout`) no longer leaves orphaned `sleep` processes holding the caller's pipes.++ #### Every claimed test now runs++ - Executed-test receipts: every Bun invocation in CI writes a receipt and a JUnit report; `scripts/ci-executed-counts.ts` compares runs by (lane, file, test, backend arm) and fails on an undeclared drop or an incomplete run. Verify records each check as pass, fail, timeout or skip (`GBRAIN_CHECK_SKIPPED:`) and keeps its logs on failure. A red job's step summary lists the failing tests with a reproduce command.+ - 55 unit-file PostgreSQL arms that ran in no lane run in persistence-validation's `unit-postgres-arms` job, one Bun process per file; `check:postgres-lanes` keeps it that way.+ - 12 dead opt-in gates renamed under `GBRAIN_TEST_*`; the compiled self-update smoke runs unconditionally; `check:test-env-opt-ins` fails on a test gated on a name the preload strips.+ - The agent-voice recipe's unit suite runs in CI (`bun run test:agent-voice`); `check:jsonb-params` and `check:image-decoders` run in `verify`; scripts/ is typechecked; guard self-test fixtures cover seven more guards; the privacy guard scans `evals/` and `docs/test-audit/`; `test/docs-repo-paths.test.ts` fails on a doc naming a missing repo path; the skill-refs allowlist fails on stale rows.+ - Blind source pins in six suites (each passed with its behavior broken) are replaced by behavioral owners; probes are in `docs/test-audit/2026-10-04/implementation/lane-c.md`.++ #### Red nightlies become issues++ - `nightly-watch.yml` opens, updates, reopens and closes one `Nightly red: <workflow>` issue per scheduled workflow, with the failing jobs, the last green commit and the next step; `.github/nightly-known-red.tsv` holds at most three known-red or known-skipped rows, each owned by a TODO.+ - A weekly `ci-health.yml` report lists first-attempt pass rates and the most-failing test files.+ - Heavy Tests: the Docker image copies `patches/`; `postinstall.ts` exits 0 without `src/`; every heavy script runs and prints a rerun command per failure; the Claude door runs even when the Codex door fails.+ - Missing provider secrets are a visible warning (Hermes, real-agent doors, publish-template, key-gated E2E), never a silent green.+ - The scale tier runs under an out-of-process phase watchdog that names the stalled phase; the vectors phase prints one line per batch.++ #### Faster and cheaper pull-request CI++ - E2E selection is one rule: doc-only changes select nothing, everything else selects the whole corpus, read from the pull request files API on a shallow checkout and failing closed on a truncated list. Up to eight Selected E2E workers on 2 vCPU; the E2E backend matrix moves to its own two 4 vCPU shards and stops running a second time in Selected E2E; serial tests on 4 vCPU; the longmemeval slow file joins the unit shards; unit shards stay on 4 vCPU (2 vCPU raised the shard mean from 542 s to 608 s).+ - 92 serial files that pass the isolation lint and touch no process-wide state rejoin the parallel lane; `scripts/serial-files.tsv` lists the remaining serial files with a class and reason.+ - Shorter test waits through production-default seams (connector fixture, maintenance publish wait, effect renewal interval), and `test/helpers/brain-template.ts` clones initialized disk brains instead of replaying migrations.+ - Shard weights re-mined from this branch's green run; `check:weight-coverage` fails on stale entries and warns on unweighted shares.+ - `merge_group` triggers (inert until the merge queue is enabled) use the PR profile; a version-only `package.json` diff no longer widens the native test scope; dependency audit blocks only when dependencies change or on master, schedules and dispatches; Semgrep uploads SARIF weekly.++ #### Docs and tooling++ - `bun run regen:all` regenerates every generated artifact; `check:regen-all` in verify.+ - `docs/TESTING.md` opens with a quick start, drops the test inventories and moves subsystem detail beside its code (120 KB ratchet cap).+ - Removed: unreferenced chunkers and search modules, the forward-reference facade, dead test seams, finished one-off scripts, a broken benchmark, the skillopt judge and reflect evals, a fixture naming a real person, and the exports-count and pagetype-exhaustive guards.+## [0.60.58.0] - 2026-10-04**A managed Postgres brain far from its database catches up a sync backlog about 2.7 times faster again, and every write to it costs fewer round trips (#5984).**diff --cc TODOS.mdindex 3dfe08c64a,9454312b0b..90b48506e9--- a/TODOS.md+++ b/TODOS.md@@@ -43,20 -80,24 +80,20 @@@ Spec: `docs/designs/AGENT_OPERATOR_WAVE- [ ] **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.- - [x] **P2 — Status-only mode for `serve --http` lock contention.** **Completed: v0.60.59.0** — a `serve --http` that cannot open its brain stays up in status-only mode on the same port (`/health` 503 + `Retry-After: 5`, `/mcp` with only `gbrain_status`), re-probes every 5 s through the shared `runStatusModeServe`/`reprobe` path and swaps in the full app on the same listener. Pinned by `test/serve-http-status-mode.serial.test.ts`.-- [ ] **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.++- [x] **P2 — Status-only mode for `serve --http` lock contention.** **Completed: v0.60.60.0** — a `serve --http` that cannot open its brain stays up in status-only mode on the same port (`/health` 503 + `Retry-After: 5`, `/mcp` with only `gbrain_status`), re-probes every 5 s through the shared `runStatusModeServe`/`reprobe` path and swaps in the full app on the same listener. Pinned by `test/serve-http-status-mode.serial.test.ts`.- [ ] **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.- - [x] **P2 — Submit-time job authorization and pre-upgrade queued jobs.** **Completed: v0.60.59.0** — `book-mirror`, `enrich --background` and `jobs submit enrich|subagent` store the approval on every queued job (migration v205); the worker holds a command's jobs to one approved total, and pre-upgrade rows run as `legacy_default` under $5. Pinned by `test/minions-spend-authorization*.test.ts`, `test/enrich-background-consent.test.ts`, `test/cli-jobs-submit-consent.test.ts`.-- [ ] **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.++- [x] **P2 — Submit-time job authorization and pre-upgrade queued jobs.** **Completed: v0.60.60.0** — `book-mirror`, `enrich --background` and `jobs submit enrich|subagent` store the approval on every queued job (migration v205); the worker holds a command's jobs to one approved total, and pre-upgrade rows run as `legacy_default` under $5. Pinned by `test/minions-spend-authorization*.test.ts`, `test/enrich-background-consent.test.ts`, `test/cli-jobs-submit-consent.test.ts`.- [ ] **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.- - [x] **P2 — Onboarding notices over MCP.** **Completed: v0.60.59.0** — stdio MCP sessions get the onboarding coaching notices on calls whose results show the gap, plus the first-run decisions bundle; stdio `mute_notice` applies. Pinned by `test/mcp-onboarding.test.ts`.-- [ ] **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.++- [x] **P2 — Onboarding notices over MCP.** **Completed: v0.60.60.0** — stdio MCP sessions get the onboarding coaching notices on calls whose results show the gap, plus the first-run decisions bundle; stdio `mute_notice` applies. Pinned by `test/mcp-onboarding.test.ts`.- [ ] **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.- - [x] **P2 — Unify MCP surfaces across wiring paths.** **Completed: v0.60.59.0** — every stdio registration gbrain writes pins `--surface starter` (`src/core/mcp-registration.ts`), stdio `serve` honours `GBRAIN_SURFACE`, and `request_tools {surface}` widens a stdio session. Pinned by `test/mcp-registration.test.ts`, `test/request-tools-stdio.test.ts`.-- [ ] **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.++- [x] **P2 — Unify MCP surfaces across wiring paths.** **Completed: v0.60.60.0** — every stdio registration gbrain writes pins `--surface starter` (`src/core/mcp-registration.ts`), stdio `serve` honours `GBRAIN_SURFACE`, and `request_tools {surface}` widens a stdio session. Pinned by `test/mcp-registration.test.ts`, `test/request-tools-stdio.test.ts`.- [ ] **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`.**@@@ -64,16 -105,10 +101,16 @@@- [ ] **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.- - [x] **P2 — Backfill the last 74 suggestion-less `OperationError` sites (31 files).** **Completed: v0.60.59.0** — every refusal site carries a site-specific suggestion (about 210 sites in 33 files, including funnel call sites); the baseline file is deleted and the `defaulted-suggestion` and `generic-suggestion` scanner rules are zero-tolerance.- - [x] **P3 — Module-local `fail(code, message)` helpers carry a generic next step.** **Completed: v0.60.59.0** — `shared-skills` `fail`, `persistence/administration` `invalid` and the other funnels require a suggestion per call site.-- [ ] **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.++- [x] **P2 — Backfill the last 74 suggestion-less `OperationError` sites (31 files).** **Completed: v0.60.60.0** — every refusal site carries a site-specific suggestion (about 210 sites in 33 files, including funnel call sites); the baseline file is deleted and the `defaulted-suggestion` and `generic-suggestion` scanner rules are zero-tolerance.++- [x] **P3 — Module-local `fail(code, message)` helpers carry a generic next step.** **Completed: v0.60.60.0** — `shared-skills` `fail`, `persistence/administration` `invalid` and the other funnels require a suggestion per call site.+- [ ] **P2 — `gbrain agent run` asks for consent for paid job names.**+ **What:** `book-mirror`, `enrich --background` and `jobs submit enrich|subagent` ask before queueing paid work; `gbrain agent run` with a paid job name does not. **Fix:** the same consent gate and stored spend record. **Effort:** S. **Priority:** P2.+- [ ] **P2 — Pin the OpenClaw plugin manifest to `starter`.**+ **What:** every other stdio registration pins `--surface starter`; OpenClaw's manifest stays a bare `serve`. **Fix:** run the starter-gap check over the OpenClaw skill list, then pin it. **Effort:** S. **Priority:** P2.+- [ ] **P3 — Onboarding coaching for owner-principal HTTP sessions.**+ **What:** stdio sessions get onboarding notices; HTTP gets none. **Fix:** emit them once HTTP sessions are session-bound. **Effort:** S. **Priority:** P3.+- [ ] **P3 — `book-mirror`'s default model has no provider prefix.**+ **What:** the default `--model claude-opus-4-7` is rejected by `queue.add` as an unknown provider. **Fix:** default to `anthropic:claude-opus-4-7` (or the configured chat model). **Effort:** XS. **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.**diff --cc VERSIONindex ae212c0527,ae212c0527..9de3247158--- a/VERSION+++ b/VERSION@@@ -1,1 -1,1 +1,1 @@@--0.60.59.0++0.60.60.0diff --cc docs/architecture/key-files/agent-contract.mdindex eb5db7406e,d9982a5cda..071f85ec10--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@@ -9,21 -9,20 +9,21 @@@ Spec: `docs/designs/AGENT_OPERATOR_WAVE- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).-- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.+- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute).- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).- - `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.serial.test.ts`.- - `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated.serial.test.ts`.+ - `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.test.ts`.+ - `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.- `src/cli/flag-values.ts` — strict numeric values for CLI-only flags (D4): `intFlagValue` / `numberFlagValue` (digits only, safe integer, `[min, max]`) and `flagValueError` raise `invalid_params` usage errors (exit 2) naming the flag, what it accepts and an example. Used by jobs submit, extract-conversation-facts, eval run-all, sync `--interval`, connectors sync, book-mirror (the absorbed community fixes #5936 #5934 #5933 #5931 #5930 #5909). Tests: each command's `*-numeric-flags`/`*-flags` test.- `src/cli/op-param-values.ts` — `opParamValue`: typed values for shared ops from `ParamDef` inside `parseOpArgs` (number → finite, string enum → declared values), `invalid_params` with an example otherwise; mirrors MCP `validateParams`. `parseOpArgs` also honours a bare `--` (D6). Test: `test/cli-op-typed-args.test.ts`.- - `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `writeback`, `harness_wiring`, `skills_scaffold`); the stdio onboarding cache reuses it with writeback and skills only. `firstRunBundle`/`harnessRegistrationCommand` take `gbrain init --surface`. Tests: `test/cli-json-guard.serial.test.ts`.-- `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `harness_wiring` today). Tests: `test/cli-json-guard.test.ts`.++- `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `writeback`, `harness_wiring`, `skills_scaffold`); the stdio onboarding cache reuses it with writeback and skills only. `firstRunBundle`/`harnessRegistrationCommand` take `gbrain init --surface`. Tests: `test/cli-json-guard.test.ts`.+- `src/core/onboard/mcp-onboarding.ts` — onboarding coaching for the owner's stdio pipe. `collectOnboardOpportunities(engine, signal, between?)` is the one home of init's six counts (parallel for `runInitNudge`, sequential with yields for the background refresh); a failed count is `null` and never reads as a gap, and `onboardGaps` applies init's thresholds (link < 0.7, timeline < 0.9; an empty brain has none). The per-brain cache (6 h TTL, `GBRAIN_HOME/onboard-counts-<brain>.json`, atomic write, partial runs not persisted) is loaded by `startOnboardingRefresher` and refreshed in the background only while the idle gate reports no request in flight (3 s budget); it also holds the pitchable `gbrain features` recommendations (`pitchableFeatures`, offer state read-only) and the stale-chunk backfill estimate. `mcpOnboardingNotices` is dispatch's one producer on the stdio success path: `first_run_decisions` (writeback + skills via `mcpFirstRunNotices`, from the second successful call, nothing persisted) and one coaching notice per class (`onboard_stale_chunks`, `onboard_link_coverage`, `onboard_timeline_coverage`, `onboard_no_takes`) when `ONBOARD_CALL_AFFINITY` names the call and the class's result predicate holds, plus `features_auto_fix` on `get_backlinks`/`traverse_graph`; fixes are the read-only `get_health` / `gbrain onboard --check` preview, the dismissal line names `mute_notice` only where it is callable. `mutedFirstRunDecisionsNotice` feeds doctor (`memory_writeback`) and `gbrain onboard --check`. HTTP never calls it. Test seams `__warmOnboardingCacheForTests`, `__awaitOnboardingRefreshForTests`, `__resetMcpOnboardingForTests`. Tests: `test/mcp-onboarding.test.ts`, `test/init-nudge.test.ts`, `test/mcp-notice-channels.test.ts`.- - `test/cli-contract.serial.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.- - `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.serial.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.serial.test.ts`) has one row per declaration, `<command> <sub>` included.+ - `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.+ - `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.-- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.+- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; none on a brain keyless by choice). `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.-- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` — F4 status-only stdio serve. cli.ts hands over a `serve` (stdio, host brain, not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, or a PGLite lock held by a live holder; `runStatusModeServe` builds a gated lazy engine (`createDegradedEngine` with the configured `kind`; its method set aligns with the live engine on recovery) marked with `StatusModeState`. `probeStatus` reads config + `peekLock` only; `gatedReconnect` refuses while blocked (no lock attempt) and otherwise connects (≤1 attempt / 5 s, inside tool calls only, `resetReadinessMemo()` first). `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. Test: `test/serve-status-mode.serial.test.ts` (recover in place → recall; shared `serve --http` with tokens minted before it starts → both harnesses recall; no brain → init → recall; `--fail-fast`).+- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.-- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`) and `GBRAIN_SURFACE=full`; HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills.+- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`.- `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.diff --cc docs/architecture/key-files/commands-4.mdindex 5cb26f5eb4,cd768c7dd0..64a8ba6bc6--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@@ -15,7 -15,7 +15,7 @@@ Current behavior and load-bearing invar- `src/commands/integrity.ts` — `gbrain integrity check|auto|review|extract`: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip). `scanIntegrity()` is the shared library function called from `gbrain doctor` (sampled at limit=500) and `cmdCheck` (full scan). Batch-load fast path on Postgres uses a single SQL query (avoids the PgBouncer per-row round-trip timeout), gated by `engine.kind === 'postgres'` at the call site so PGLite never enters batch; fallback `catch` logs at `GBRAIN_DEBUG=1`. Batch projection is `SELECT ... ORDER BY source_id, slug` (NOT `SELECT DISTINCT ON (slug)`, which would collapse same-slug-different-source pages into one scan) so multi-source brains scan each `(source, slug)` row independently. Sequential and auto-repair loops use `listAllPageRefs()` to enumerate `(slug, source_id)` pairs and thread `sourceId` to `getPage`; batch + sequential paths report the same page count on multi-source brains.- - `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite). `jobs submit enrich|subagent` runs the paid consent gate and stores an `authorized` spend record on the row; `jobs get --json` adds `spend_basis`, `spend_why` and `spend_group`; `jobs list --group <id>` and `jobs cancel --group <id>` act on one spend group.-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite).++- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `jobs-readiness.ts` orchestrates bounded driver-lane and selected-child readiness before worker schema/recovery, handler registration or claims. After `ensureSchema`, `maybeRunWorkerStartupRecovery(queue, process.env, true)` runs for both bare and supervised workers; the final worker `ready` event publishes readiness, and a worker handed an owner status channel (`GBRAIN_WORKER_STATUS_PATH` or `GBRAIN_WORKER_STATUS_TOKEN`, even partially) refuses admission if its status cannot be published, while a legacy supervised worker (`GBRAIN_SUPERVISED=1` from a pre-0.59.1 owner, no channel) publishes nothing and proceeds; typed faults report `configuration_blocked` and exit `WORKER_EXIT_CONFIGURATION`, while transient readiness failures admit no jobs and remain retryable. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the `JOBS_SUBCOMMANDS` dispatch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `jobs work` (`src/commands/jobs/work.ts`) wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status --json` adds `processing_ready`, lowercase `processing_state` (`starting`/`ready`/`configuration_blocked`, or `unknown`/`stopped` without current state), `reason_code`, `blocked_since` and worker/child identities without changing `running` or crash counters. A live local pidfile keeps this diagnostic engine-free; a missing pidfile retains the DB-lock fallback. It consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `jobs work` resolves the actual selected child and validates its bounded protocol/capability handshake and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `jobs run-child` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes. `jobs work` registers the shell handler always; the startup line names the flag first (`--allow-shell-jobs` / `GBRAIN_ALLOW_SHELL_JOBS=1`); `jobs start` computes `allowShellJobs` as `--allow-shell-jobs || GBRAIN_ALLOW_SHELL_JOBS === '1'` — the same literal `handlers/shell.ts` and `buildChildArgs` check. `extract-atoms-drain` accepts a trusted `retryRequestId` in submitted params; a new job ID distinguishes a newly approved malformed-output provider attempt from provider-free publication replay. PGLite `jobs --follow` still requires exclusive owner access. D2: `jobs supervisor start --detach` writes its payload (`event`, `status:'started'`, `supervisor_pid`, `pid_file`, `detached`, `stderr_log`) through `writeStdoutFinal`; the `jobs` record declares no `json` because work/watch/foreground supervisor stream. Start refusals add an envelope under `--json` (`invalid_params` exit 2 for an unknown subcommand or bad `--health-interval`, `config_error` for PGLite). `jobs submit enrich|subagent` runs the paid consent gate and stores an `authorized` spend record on the row; `jobs get --json` adds `spend_basis`, `spend_why` and `spend_group`; `jobs list --group <id>` and `jobs cancel --group <id>` act on one spend group.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `runJobs` resolves help and the thin-client refusal, builds the queue, then dispatches through `JOBS_SUBCOMMANDS` (Object.hasOwn lookup, same unknown-subcommand error) to one module per subcommand in `src/commands/jobs/<sub>.ts` (`runJobs<Sub>(ctx)`; parsers, formatters and `JobsCommandContext` in `jobs/shared.ts`; `maybeRunWorkerStartupRecovery` in `jobs/work.ts`), all re-exported from `jobs.ts`. Subcommands that register handlers import `registerBuiltinHandlers` lazily from `jobs.ts`. `registerBuiltinHandlers` is the ordered registration table (worker.register vs gateway-refreshing registerBuiltinJob stay here); handler bodies live in `src/core/minions/handlers/` (see core-minions-1). Registration names and order are pinned by `test/jobs-handler-registry-golden.test.ts`, which also drives the supervisor's `deriveHandlerNames` probe.- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker defers it (`JobDeferredError`, 30 min, no attempt counted) so the backlog runs once a key exists. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.diff --cc openclaw.plugin.jsonindex a72d6fae10,a72d6fae10..fd40c92f71--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@@ -1,7 -1,7 +1,7 @@@{"id": "gbrain-context-engine","name": "gbrain",-- "version": "0.60.59.0",++ "version": "0.60.60.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --cc package.jsonindex 2c9b75fa42,4f3778e60d..174875d294--- a/package.json+++ b/package.json@@@ -212,7 -218,7 +218,7 @@@"bun": ">=1.4.0"},"license": "MIT",-- "version": "0.60.59.0",++ "version": "0.60.60.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --cc plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 687283823e,687283823e..d1c953c0ed--- 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.59.0",++ "version": "0.60.60.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.jsonindex 06e6fb6a5c,06e6fb6a5c..49ffc220b2--- 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.59.0",++ "version": "0.60.60.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.mdindex 3faa255e3f,3faa255e3f..5a8afad3e3--- 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.59.0 -->++<!-- gbrain-plugin-tree-stamp: 0.60.60.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.jsonindex 5d4d60283b,5d4d60283b..44057234f2--- 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.59.0",++ "version": "0.60.60.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.jsonindex a8a00f9f2a,a8a00f9f2a..57658ab0b8--- 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.59.0",++ "version": "0.60.60.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.mdindex 0c99a92bb2,0c99a92bb2..7f0a523f89--- 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.59.0 -->++<!-- gbrain-plugin-tree-stamp: 0.60.60.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.mdindex d76196632f,df9b1f1cc1..3d911606dc--- a/plugin/README.md+++ b/plugin/README.md@@@ -1,4 -1,4 +1,4 @@@--<!-- gbrain-plugin-tree-stamp: 0.60.59.0 -->++<!-- gbrain-plugin-tree-stamp: 0.60.60.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --cc skills/migrations/v0.60.60.0.mdindex 91239bd7f6,0000000000..790fbc9cdemode 100644,000000..100644--- a/skills/migrations/v0.60.60.0.md+++ b/skills/migrations/v0.60.60.0.md@@@ -1,55 -1,0 +1,55 @@@- # Upgrade to v0.60.59.0: paid queued jobs carry the user's approval, one MCP tool surface, HTTP status mode++# Upgrade to v0.60.60.0: paid queued jobs carry the user's approval, one MCP tool surface, HTTP status mode++Four behavior changes reach existing brains. Paid commands that queue work+(`book-mirror`, `enrich --background`, `jobs submit enrich|subagent`) ask for+consent before queueing and the worker holds them to the approved total. New+stdio registrations use the `starter` tool surface. A `gbrain serve --http`+that cannot open its brain stays up in status-only mode. Stdio MCP sessions+receive onboarding coaching notices.++1. **Finish the upgrade.** `gbrain upgrade` runs it. To be sure, on the brain+ host:+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ ```+ Migration v205 adds the spend-authorization columns to the job queue.++2. **Restart every worker, `gbrain serve` and autopilot.** Only upgraded+ workers claim jobs that carry a spend authorization; an older worker stops+ claiming at the first such job in its queue. Check:+ ```bash+ gbrain doctor --only legacy_job_authority --json+ ```++3. **Tell the user about queued paid jobs from before the upgrade.** A+ `book-mirror` or `enrich` job queued before this release runs as+ `legacy_default` under a $5 cap (enrich: its own `--max-usd` when set). A+ chapter on an expensive model can stop with `derived_cap_exhausted`;+ rerunning the command skips completed chapters. List them:+ ```bash+ gbrain jobs list --json+ ```+ Cancel a group only with the user's agreement:+ `gbrain jobs cancel --group <id>`.++4. **Expect consent prompts on background paid work.** `gbrain enrich+ --background` and `gbrain jobs submit enrich|subagent` exit 3 with the+ consent payload unless the user authorized the spend (`--yes`,+ `--max-usd <usd>`, a preapproval or `spend.posture=tokenmax`). Relay the+ estimate to the user and rerun `fix.argv` after they agree.++5. **Know the tool surface.** New stdio registrations (readiness fix, init,+ `bootstrap hooks`, plugins) pin `--surface starter`. Existing registrations+ keep their surface. A stdio session that needs a hidden tool calls+ `request_tools` with `{ "surface": "full" }`; `mcp.allow_session_widen=false`+ turns that off. Stdio `serve` honours `GBRAIN_SURFACE`.++6. **Shared HTTP brains.** A `gbrain serve --http` whose brain is locked,+ missing or unconfigured answers `/health` with 503 and `Retry-After: 5`+ and recovers on the same port once the brain opens. Container health+ checks that need the old exit use `--fail-fast` or+ `GBRAIN_SERVE_FAIL_FAST=1`. After recovery, clients re-list tools or+ reconnect.++Rolling the binary back leaves queued spend-authorized jobs unclaimable;+cancel them first with `gbrain jobs cancel --group <id>`.diff --cc skills/skills.lock.jsonindex c1c520ed44,5cdcbedbe6..52ef448150--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@@ -167,8 -167,7 +167,8 @@@"migrations/v0.60.52.0.md": "ae49b2f51ba6288e4883d8bfda9f494f821e160e227164aa065a645d4e9ae87b","migrations/v0.60.53.0.md": "0c43dffb7926703d024b4dbe6ed84a87b630b587c84b42c84f931f13f9c089cf","migrations/v0.60.57.0.md": "b97afe1df069b14446a31b41bfd1f24fc76877c13bd2bf55bf6f6371a87e579c",- "migrations/v0.60.59.0.md": "3dd231e1446746493ec012466bfcb92f1ec946baf5af5369ac8a8de7219d3e78","migrations/v0.60.6.0.md": "1cbfca2c899e1348acbd61f0baa4c8e723b5283ff868c710c74e116c0cb6726e",++ "migrations/v0.60.60.0.md": "18b4e0dfe00053d8d7182f91d30ca99a99fa50fb07f0a43f379420d3c2aec882","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a","migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a","migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",diff --cc src/core/minions/child-readiness.tsindex c85ba4820f,929d77086a..80be1174f3--- a/src/core/minions/child-readiness.ts+++ b/src/core/minions/child-readiness.ts@@@ -44,10 -42,22 +44,22 @@@ export function parseChildReadiness(raw}if (r.status === 'transient_error') throw new Error('Selected job child readiness failed transiently; no jobs were admitted.');if (r.status !== 'ready') throw childConfigurationError('child_protocol_incompatible');- return { version: r.version, versionSkew: r.version !== VERSION };+ return { version: r.version, versionSkew: r.version !== VERSION, features: r.features as string[] };}+ /**+ * Runs the selected child's readiness handshake under a deadline.+ *+ * Timeout contract: at `timeoutMs - min(250, timeoutMs / 10)` the selected+ * process is SIGKILLed. Beneath tini that means every process group tini+ * started (the selected grandchild), and tini then reaps the grandchild and+ * exits. The confirmed failure ("timed out; no jobs were admitted") settles+ * only from the wrapper's `close`, so the selected process has already exited+ * and been reaped (or is a zombie awaiting its new parent). If `close` does not+ * arrive by `timeoutMs`, the call settles with "cleanup unconfirmed" and makes+ * no claim about the process.+ */-export async function checkChildReadiness(options: ChildReadinessOptions): Promise<{ version: string; versionSkew: boolean }> {+export async function checkChildReadiness(options: ChildReadinessOptions): Promise<{ version: string; versionSkew: boolean; features: string[] }> {const timeoutMs = options.timeoutMs ?? CHILD_READINESS_TIMEOUT_MS;if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000) throw new Error('Invalid child readiness deadline.');if (options.signal?.aborted) throw new Error('Selected job child readiness was interrupted.');diff --cc templates/bootstrap/template-repo/README.mdindex ef0860fb41,ef0860fb41..4a1519b218--- 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.59.0 -->++<!-- gbrain-template-stamp: 0.60.60.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same