Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
74.0 KB
Raw Blame

Plan: agent-first operator follow-up wave (one PR, one PATCH)

Base: master at 6622a119 (VERSION 0.60.48.0). Ships as ONE fix-wave PR, one PATCH bump (next free 0.60.x.0 at ship time, auto-allocated past collisions), one CHANGELOG entry. Follow-ups from v0.60.46.0 (#5991); spec docs/designs/AGENT_OPERATOR_WAVE.md (Deferred), contract docs/protocol/AGENT_OPERATOR_v1.md.

Implementation plan

Decision IDs in brackets (CEO-n, T-n) refer to the decision ledger. Approved 2026-10-04: T1–T7 as recommended, T8 (jobs submit enrich|subagent consent) in this wave, UC1 (second-serve proxy) out of scope.

Problem

The agent-first operator wave (v0.60.46.0) gave every error, refusal and notice a machine contract (code, message, why, fix.next, fix.verify). Five gaps remain where an agent operator still sees less than a human at a terminal, or where the contract is not yet universal:

  1. Onboarding coaching never reaches an MCP-only agent. runInitNudge (src/core/onboard/init-nudge.ts:33) and init's first-run decision bundle (src/commands/init-first-run.ts:96, firstRunBundle :123) write only through writeCliNotices (src/core/interop-notices.ts:~283). An agent that talks to gbrain only over MCP never learns its brain has stale chunks, thin link/timeline coverage or zero takes, and never sees the open first-run decisions (writeback, skills). The post-upgrade notice already reaches the first stdio session (src/mcp/dispatch.ts:905, src/core/post-upgrade-notice.ts:53), so the channel exists.
  2. Every stdio wiring path registers a different MCP surface.
    • readiness harness_wiring fix and init's quickstart: --surface verbs (src/core/readiness.ts:397-398, src/commands/init-first-run.ts:144);
    • gbrain bootstrap hooks for Claude Code and Codex: --surface full (src/core/bootstrap/hooks.ts:902,919), opencode: --surface full (src/commands/bootstrap.ts:1270-1271);
    • plugin variants (Claude Code / Codex): --surface starter (generated by scripts/generate-plugin-tree.ts);
    • OpenClaw plugin manifest: bare serve (openclaw.plugin.json:37), resolving to config mcp_surface, else full;
    • docs: docs/protocol/MEMORY_VERBS_v1.md:52-77 say --surface verbs. The same user gets 7, ~30 or ~130 tools depending on which install command an agent ran. Bootstrap pins full because its skills need put_page/get_page/timeline, which verbs lacks (hooks.ts:887-889). Bug found while grounding: the F6 hidden-tool hint (src/mcp/hidden-tool-hint.ts:20) tells every stdio agent "set GBRAIN_SURFACE=full for this machine's gbrain server", but only the plugin launcher (.agents/gbrain-launcher:60) reads GBRAIN_SURFACE; serve resolves flag > config > full (src/mcp/surface.ts:172-180). On a direct registration the advertised fix does nothing.
  3. A losing serve --http exits. stdio serve answers lock contention / missing brain / unreadable config with a status-only server exposing one gbrain_status tool (src/commands/serve-status.ts, src/mcp/status-mode.ts). statusModeEligible excludes --http (serve-status.ts:21-23), so cli.ts:2573-2621 rethrows the pglite_busy connect error and the HTTP daemon exits. A supervisor (launchd/systemd from mcp expose) crash-loops it; every HTTP client sees a dead endpoint instead of the explanation and fix.
  4. 74 suggestion-less OperationError sites in 31 files (scripts/agent-contract-baselines/ suggestionless-operation-error.tsv; list in suggestionless-hits.txt beside this plan). Counting rule used throughout: 6 of the 74 hits are funnel-helper definitions that serve 108 call sites (measured with grep -c including each definition line: shared-skills/adapter.ts fail ×25, shared-skills/membership.ts fail ×21, commands/sources-lifecycle-args.ts invalid ×25, company-brain/receipts.ts fail ×23, commands/takes-mutation.ts invalid ×14, core/embed-facts-options.ts invalid ×6); the other 68 are direct sites. Refusals to fix: 68 + 108 = 176, plus 29 in persistence/administration.ts [CEO-7] and 1 in commands/eval-gate.ts:464 (and its ~7 usage( callers): roughly 210 refusal sites across 33 files. The acceptance bar is the scanner, not the count: zero suggestion-less hits and zero defaulted-suggestion hits. The TODOS entry names src/cli.ts; the baseline instead holds src/mcp/dispatch.ts:854 (the TSV is authoritative).
  5. Consent-gated paid work that is queued carries no consent record, and the approved cap is not enforced. book-mirror gets an Authorization from consentGateOrExit (src/commands/book-mirror.ts:420) and discards it; its N subagent children (:455) run in the worker with no BudgetTracker scope (src/core/minions/worker.ts:1528, src/core/minions/run-child.ts:166 install only submission authority), so the printed derived cap (estimate × 1.5) is never applied. Bug found while grounding: enrich --background on Postgres (src/commands/enrich.ts:950-981) queues paid enrich jobs before its consent gate (:1022) runs, so a non-TTY agent queues paid work with no authorization at all.

Goal

Every MCP-only agent on the owner's stdio pipe gets the onboarding coaching and first-run decisions a terminal user gets, tied to the calls they affect and within the coaching budget and mute rules; every new stdio registration gbrain writes defaults to one surface (OpenClaw manifest excepted, T5); an HTTP serve that cannot open its brain stays up, explains itself and recovers; the suggestion-less OperationError baseline reaches 0 with each refusal naming its own next step; and every consent-gated paid command that queues work stores the authorization on each job and the worker enforces the approved cap.

Item 1 — Onboarding notices over MCP (stdio)

Design.

  • New module src/core/onboard/mcp-onboarding.ts:
    • collectOnboardOpportunities(engine, signal): the six counts runInitNudge runs today, moved out of init-nudge.ts:52-91 into one shared function (init keeps calling it; init output unchanged). Returns { staleChunks, entities, linkCoverage, timelineCoverage, takes, pages, partial }.
    • A cache with a 6 h TTL (in memory, persisted per brain; see DX amendments), first filled in the background right after the stdio engine boots and refreshed in the background when stale (3 s budget with AbortSignal, never on a call's critical path), so a long-lived serve stops nudging after the user fixes a gap. A call that arrives while the cache is still cold gets no onboarding notice; the next affine call does. Test seam __warmOnboardingCacheForTests.
    • onboardOpportunityNotices(counts, cfg): one coaching notice per opportunity class, each with its own registered, muteable code so the ledger's per-code dedupe (notice-ledger.ts, key session|code) cannot drop one class behind another: onboard_stale_chunks, onboard_link_coverage, onboard_timeline_coverage, onboard_no_takes (CLI init keeps onboard_opportunities); these four join NOTICE_CODES as coaching, so mute_notice and gbrain notices mute accept them. Each has its own why (the count and what it limits) and the read-only fix gbrain onboard --check (argv only; run_onboard is mutating and admin-scoped, so it is never offered as the MCP route). On an MCP transport a CLI-only fix renders next: tell_user_to_run by the published deriveNext table (row 3), so the MCP-only agent relays the command with user_message instead of trying to run it; each notice carries that user_message. The stale-chunk class is suppressed when readiness reports embeddings disabled_by_choice or no provider (keyless brains: every chunk is unembedded by design).
    • Call affinity [CEO-5] (A6: "coaching fires only when evidence ties the limitation to the current call"): closed map ONBOARD_CALL_AFFINITY: stale chunks → search, query, recall, context_pack; link coverage → get_backlinks, traverse_graph, entity; timeline coverage → get_timeline, entity, get_page; zero takes → think, takes_list, recall, context_pack. Pinned by test: every name exists in the catalogue, and every class has at least one op on the verbs surface and on the starter surface.
    • features_auto_fix [T4]: the existing featuresAutoFixNotice (src/commands/features.ts:366) is exported from a pure builder fed by the same cached features scan (run in the same background refresh), with the per-user shouldPitch filter (features.ts:108) applied read-only (no offer state is written from MCP). Affinity: get_backlinks, traverse_graph (link gaps) only; the embedding gap is already covered by onboard_stale_chunks, so the two never compete for the 2-per-session budget on one call. Consent stays conditional as today: consent: ['paid'] (→ ask_user) only when a paid fix id is present.
  • First-run decisions: mcpFirstRunNotices(engine) reuses buildInitFirstRunNotices (init-first-run.ts:96) with stdio inputs only: writeback when writebackAskApplies(engine) (writeback-nudge.ts:44, already gated on "shown once ever" and "operator answered") and skillsScaffold from initSkillsScaffold(). search_mode is not offered over MCP (nothing records whether the user confirmed init's default; init and doctor keep it), and harness_wiring is omitted on stdio (readiness says wired_running). Kind ask (never muted, not coaching- budgeted). Delivery rule: once per session (the stdio ledger dedupes per process) while a decision stays open; nothing is persisted on delivery, because delivering an ask is not the user answering it (writeback-nudge.ts keeps the same rule). Answered decisions drop out on their own (writebackAskApplies false once memory.auto_writeback is set; the scaffold decision once the skills exist); a user who dismisses the bundle mutes first_run_decisions with mute_notice (this code joins the muteable set as an explicit exception for ask, since an unanswered ask must stay dismissible).
  • Wiring: src/mcp/dispatch.ts success path, beside :905, stdio and opts.remote !== false only: first-run bundle (once) plus affinity-matched opportunity and features notices, through admitNotices (dispatch.ts:568): per-process dedupe, 2 coaching notices per session (notice-ledger.ts:23), mute (mutedNoticeCodes). One call into mcp-onboarding.ts; dispatch grows ≤3 lines.
  • HTTP [CEO-8]: HTTP gets neither. The counts are brain-wide (they cross source-scoped grants) and every fix runs on the brain host, so a remote client could only relay host maintenance it cannot see. The owner gets the same coaching on stdio, the CLI and doctor. Documented in docs/protocol/AGENT_OPERATOR_v1.md (notices by transport). TODO filed (P3): owner-principal HTTP coaching once HTTP sessions are session-bound.
  • GBRAIN_NO_ONBOARD_NUDGE=1 silences all of it (existing opt-out).
  • DX amendments (Phase 2.5):
    • The first-run bundle attaches to the second successful call of a session, never the first (the user's own request comes first), and its why says "finish the user's current request, then ask".
    • Counts persist in GBRAIN_HOME/onboard-counts-<brainId>.json (6 h TTL, atomic write) so a new per-session serve starts warm; the background refresh still never runs on a call's path.
    • Each opportunity class names its concrete remedy in why/user_message (embedding backfill with its estimate and paid consent, link/timeline extraction, takes), with gbrain onboard --check as the read-only preview fix.
    • Bug fix found in review: mute_notice on stdio stores the mute under principal stdio (ops/notices.ts:31) while dispatch reads mutes with opts.auth?.clientId, which is undefined on stdio (dispatch.ts:571), so a stdio mute never applies. Dispatch reads the same stdio audience. mute_notice joins STARTER_OPS (the one starter change: the dismissal for notices starter now emits). Test: mute in one stdio process, the notice stays suppressed in a fresh process.
    • The first-run decisions' MCP-rendered fixes (writeback config set, skills scaffold) are specified and tested; doctor and gbrain onboard --check list muted-but-open decisions with gbrain notices unmute first_run_decisions.

Tests. New test/mcp-onboarding.test.ts (unit, in-memory PGLite): affinity map names exist and every class reaches verbs and starter; notice on an affine call, none on an unrelated call; two classes both delivered (stale chunks on search, then link coverage on get_backlinks); cold cache delivers nothing; second matching call in the same process deduped; coaching budget caps at 2; muted code suppressed; empty brain emits nothing; keyless brain emits no stale-chunk notice; TTL refresh drops a fixed gap; opt-out env; first-run bundle once per process while open, again in a new process, gone once memory.auto_writeback is set, gone after mute_notice first_run_decisions; HTTP dispatch emits none; a rendered notice on stdio has next: tell_user_to_run and a user_message. Extend test/mcp-notice-channels.test.ts (block format and _meta.gbrain_notices) and test/init-nudge.test.ts (shared collector, init output byte-identical).

Item 2 — One surface for every stdio registration gbrain writes

Design.

  • New src/core/mcp-registration.ts: REGISTRATION_SURFACE = 'starter' [T1] and stdioServeArgv(bin: string, surface: McpSurface = REGISTRATION_SURFACE): string[]. Every path that writes a stdio registration builds from it: readiness stdioRegistration (readiness.ts:397-403, plus its why text :429), registerClaudeMcp/registerCodexMcp (hooks.ts:902,919), opencode (bootstrap.ts:1270-1271, project scope keeps PATH-resolved gbrain), init's quickstart (via readiness), and the plugin generator (scripts/generate-plugin-tree.ts; variants already ship starter, now from the constant).
  • Why starter [T1]: (confirmed or replaced by the eval cell below before ship) it carries the ops bootstrap's registration comment names (put_page, get_page, add_timeline_entry, search, query are in STARTER_OPS, surface.ts:89-106; get_timeline is not), includes the seven verbs, matches the plugin lanes and avoids the ~130-tool full list.
  • OpenClaw manifest [T5]: left as bare serve this wave (config mcp_surface decides). It ships the whole skill catalogue, which has not been checked against starter, and pinning it would narrow every OpenClaw install on update. TODO filed (P2): run the starter-gap check over the OpenClaw skill list, then pin.
  • HTTP registrations are out of this item: bootstrap harness HTTP entries and serve-service.ts:154 are governed by per-client surface rows and the server ceiling (effectiveSurfaceForClient), a different mechanism.
  • GBRAIN_SURFACE honoured by stdio serve: stdio resolution becomes env > flag > config > full, matching the launcher's substitute-or-append semantics (.agents/gbrain-launcher:13-16). An invalid value never stops the server (that would end it before the handshake, where no agent sees it): it is ignored with a stderr line, and the first tool result carries a once-per-process info notice surface_env_invalid naming the three values and the surface actually served. serve --http ignores GBRAIN_SURFACE and prints one stderr line saying so (FOV-6a: an HTTP ceiling never widens without an explicit --surface restart; GBRAIN_MCP_FORCE_SURFACE stays HTTP's narrowing switch).
  • Runtime widening on stdio (CEO dual-voice D1): request_tools (src/core/ops/request-tools.ts, already in STARTER_OPS) gains a stdio branch: on the owner's stdio pipe it widens this process's allowed op set to the requested surface (never past --access read-only, and never on HTTP, where per-client rows and the ceiling stay the mechanism), then sends tools/list_changed (the server already declares listChanged, server.ts:256). Session-scoped: nothing is written; a new session starts at the registered surface. Today it answers "no per-client surface on this transport" (request-tools.ts:171,199).
  • Hidden-tool hint: where request_tools is callable (see DX amendments) the fix becomes fix.mcp: { tool: 'request_tools', arguments: { surface: 'full' } }, consent [], next: run (one call, no restart), with the CLI equivalent kept as argv. Its why names the persistent routes: GBRAIN_SURFACE=full in the harness's server env (or the plugin setting on launcher installs) and that an inherited GBRAIN_SURFACE overrides a pinned --surface.
  • One rule: never narrow an existing install. A new registration gets starter. bootstrap hooks keeps a matching entry untouched (as today, bootstrap.ts:1447-1451); when it replaces an entry on a binary or source mismatch, it carries the existing entry's --surface value over (verifyMcpTargetsWorkspace, :390-419, also returns the parsed surface). OpenClaw's manifest stays unpinned [T5]. No doctor check flags a differing surface.
  • Starter gaps for bootstrap skills: the only STARTER_OPS change this wave is mute_notice (Item 1). Before implementation, the generator's starter-gap check (scripts/generate-plugin-tree.ts) runs over the skills bootstrap installs; each gap gets the generated CLI-equivalent note (the F6 hint covers the runtime). The list is recorded in this plan's task list and the PR body.
  • Eval cell for T1: one gbrain-evals agent-task cell compares verbs / starter / full stdio registrations on bootstrap-skill and memory-loop tasks (current frontier models only, per the eval rules; no tool-output caps), measuring completion, tool-selection errors, tokens and request_tools widenings. The winner sets REGISTRATION_SURFACE; the result is mirrored into gbrain-evals and recorded in the PR.
  • DX amendments (Phase 2.5):
    • The hidden-tool hint is surface- and access-aware: it offers fix.mcp request_tools only when request_tools is callable on this connection (isCallable; it is absent on verbs and under --access read-only because it is mutating); otherwise the fix is the persistent route rendered tell_user_to_run (GBRAIN_SURFACE=full, or a re-registration with --surface full; on read-only it stays read-only).
    • The stdio widen result returns persisted: false, scope: 'session' and the input schemas of the newly allowed ops, and tells the agent to call them by name (clients that ignore tools/list_changed still work); the op and param descriptions become transport-neutral ("per OAuth client on HTTP, this session only on stdio").
    • Surface provenance: serve prints surface=<x> (source: env GBRAIN_SURFACE | --surface | config | default) at startup, and whoami and gbrain_status return surface and surface_source.
    • Escape hatch: bootstrap hooks and init's wiring step take --surface <verbs|starter|full>, passed through stdioServeArgv(bin, surface).
    • Never-narrow preserves the previous effective form exactly: a pinned --surface x stays x, and a bare serve (config/default resolution) stays bare on replacement.
    • Docs: one sentence in MEMORY_VERBS_v1.md on why the default is starter (verbs lacks page writes); a four-row surface-precedence table and the bootstrap starter-gap list (known: get_timeline) in docs/operations/mcp-surface-runbook.md; a copy-paste request_tools transcript.
  • Docs: MEMORY_VERBS_v1.md install blocks, docs/mcp/CODEX.md, docs/operations/mcp-surface-runbook.md, src/cli/help/serve.ts (env line).

Tests. New test/mcp-registration.test.ts: readiness (claude-code, codex, opencode), registerClaudeMcp, registerCodexMcp, opencode user/project and generator output all produce REGISTRATION_SURFACE. test/mcp-surface.test.ts: stdio env > flag > config precedence, bad env is ignored with the stderr line and the surface_env_invalid notice, HTTP ignores env with the warning. New test/hidden-tool-hint.test.ts: the fix is the request_tools call (next: run); new test/request-tools-stdio.test.ts: stdio widen lists the new tools after list_changed, a hidden op becomes callable, --access read-only still caps it, HTTP behaviour unchanged. test/bootstrap-hooks-writers.test.ts: a matching existing full entry is kept; a mismatched entry is replaced with its full surface carried over. Update pinned fixtures (behaviour asserts only) in test/bootstrap-hooks-writers.test.ts, bootstrap-*.serial.test.ts, opencode-json.test.ts, agent-journey*.serial.test.ts, readiness.test.ts.

Item 3 — Status-only serve --http

Design — one status-only entry point and one re-probe loop for both transports.

  • serve-status.ts: statusModeEligible admits --http (still skipped under --fail-fast / GBRAIN_SERVE_FAIL_FAST=1). runStatusModeServe(reason, err, args, connect) stays the single entry point cli.ts calls; it branches on --http internally. Both cli.ts call sites pass the new throw-only connect (Eng amendments); the extraction keeps cli.ts at or under its 3199-line ceiling.
  • Shared re-probe: status-mode.ts gains reprobe(state, connect): probeStatus() (config + peekLock() file reads only), then gatedReconnect when nothing blocks. stdio calls it from inside a tool call (existing rule: at most once per 5 s); HTTP calls the same function from a 5 s background tick [T2] (the daemon has no session, and a shared HTTP server is the topology every fix recommends). Every status-only path (both transports, the initial classification and each re-probe) goes through these two functions. The connect thunk is a throw-only connect (Eng amendments; today both status call sites pass bare connectEngine(), cli.ts:2577,2620, which exits on a vanished config or failed repair), so a config removed between probe and connect cannot kill the status daemon. A later helper that must run on each re-probe (for example engine-identity or migration checks) hooks one place.
  • HTTP status listener src/commands/serve-http-status.ts, started by runStatusModeServe for --http: a bare node:http server on the same --bind/--port with the MCP SDK Server + StreamableHTTPServerTransport in stateless mode (protocol-version negotiation from the SDK) exposing exactly gbrain_status:
    • GET /health → 503 with the HTTP status payload and Retry-After: 5.
    • POST /mcp → initialize (instructions: transport-aware status line), tools/list → [gbrain_status], tools/call gbrain_status → payload, any other tool → one serve_status_only error block.
    • /.well-known/*, /token, /authorize, /register, /admin* → 503 JSON serve_status_only envelope.
    • Unauthenticated by necessity (bearer tokens live in the brain it cannot open). The HTTP payload is built from an explicit allowlist, not by redacting the stdio payload: { status, reason, why, fix, user_message, retry_after_s, contract_version }, with path-free headline and user-message variants per reason (no brain or config path, no PID, no repair_failed detail, no share_http_plan), fixes rendered for transport: 'http' (actor host_admin, next: tell_user_to_run). Every unauthenticated HTTP status response collapses reason to unavailable and the text to "this gbrain server cannot open its brain; its host operator can see why with gbrain doctor" (Funnel publishes a loopback bind, so the bind address cannot decide); the detailed reason stays in the marker file, stderr and doctor.
    • Bind failure: if the port is taken (typically by the HTTP serve that holds the brain), the process exits through the existing listenOrRefuse refusal (serve-http-listen.ts:20: serve_port_in_use envelope with the next-port fix) instead of entering status mode; two daemons on one port is a configuration error.
    • Discoverability: while running, it writes a per-instance marker GBRAIN_HOME/serve-http-status-<port>.json (fields in Eng amendments; removed by its own process on recovery and exit). A marker is live when its PID is alive (readiness config plane: process.kill(pid, 0), no file access beyond the marker) and, in doctor's probed tier, /health answers 503 within 500 ms; a dead marker is deleted by doctor. Readiness harness_wiring and doctor treat a live marker as "a shared HTTP server exists but is in status-only mode" (serve_status_only, transport: http) and give the status reason's fix instead of "start gbrain serve --http" on a taken port.
  • Recovery: when reprobe connects, the full app is built on the same bound listener and its request handler replaces the status handler atomically (Eng amendments); the marker is removed. A lost acquisition race returns to status mode with the new reason; a full-server boot that fails after the engine connected (for example a migration error) disconnects, releases the lock and returns to status mode with reason brain_unopenable and a stderr line, instead of exiting. The 5 s tick is injectable for tests.
  • Transport-aware texts: statusPayload, statusFix, statusInstructionLine, statusModeErrorResult and the recovered payload take the transport; HTTP text never claims tools/list_changed was sent.
  • Stale client lists [X1]: stateless HTTP cannot push tools/list_changed (MCP 2026-07-28 delivers it on a subscriptions/listen stream to subscribed clients), so a client may call gbrain_status on the recovered full server. Only a process that entered status mode keeps the alias: serve-http-mcp.ts checks it before the operation lookup (independent of surfaceAllowedOps, which is undefined on a full surface with no grants, serve-http-mcp.ts:160), requires read scope, never lists it, and answers status: recovered with "re-list tools or restart this MCP connection". A server that never degraded answers unknown_tool as today.
  • Postgres: unchanged. A Postgres connect failure on --http keeps the degraded-engine path (cli.ts:2622-2649); status mode applies only to the reasons preConnectStatusReason/statusReasonForError return (no config, unreadable config, PGLite missing/repair-failed/unopenable/lock held).
  • Observability [X2]: structured stderr lines serve_status_mode_enter / serve_status_mode_recovered (reason, transport, elapsed_ms) on both transports.
  • DX amendments (Phase 2.5):
    • A human stderr banner in HTTP status mode: the reason, the fix, "re-checking every 5 s; Ctrl-C to stop; --fail-fast to exit instead".
    • The thin client surfaces the status: src/core/mcp-client.ts and src/core/remote-mcp-probe.ts read a 503 serve_status_only envelope from OAuth discovery, /token and /mcp and render it (today they discard non-success bodies, remote-mcp-probe.ts:85), instead of a generic discovery failure. Tests with cold credentials, expired credentials and recovery through the real client.
    • After recovery a client that initialized during status mode gets a standard 401 with WWW-Authenticate resource metadata and can complete OAuth; docs/mcp/DEPLOY.md says to reconnect.
    • One name: readiness/doctor reuse serve_status_only with transport: 'http' (no separate reason code).
    • Copy-paste docs: curl -i localhost:<port>/health with the 503 body and Retry-After, --fail-fast, the marker.

Tests. New test/serve-http-status-mode.serial.test.ts (serial: real port, child processes): a stdio serve holds a PGLite brain stored under a path outside the redaction prefixes (e.g. <tmp>/data/brains/x, asserted not to appear) → serve --http starts; /health 503 with only allowlisted keys and no path/PID substrings; initialize + tools/list show only gbrain_status; another tool → serve_status_only; status marker present and doctor harness_wiring reports serve_status_only (transport http); stop the holder → within 10 s /health 200, /mcp requires auth, authenticated gbrain_status → status: recovered, marker gone; --fail-fast exits non-zero; no-config start → gbrain init → recovers; a thin client (gbrain remote against the status URL) renders the serve_status_only envelope with its host-admin fix; a second serve --http on a port held by the owning HTTP serve exits with serve_port_in_use; a stale marker (dead PID) is ignored by readiness and removed by doctor. Unit: test/serve-status-mode.serial.test.ts gains a row proving stdio and HTTP use the same reprobe; a Postgres --http connect failure still takes the degraded path.

Item 4 — Suggestion-less OperationError sites to 0

Design. The B10 pattern at every site: opError(code, message, suggestion, { fix, why? }) with values filled from scope; hostFix for brain-host-only steps (src/core/ops/op-fix.ts); receipt-bearing refusals point at gbrain write-request -- <request_id> only where the principal is the local CLI (book-mirror publication :352, tool-write-identity :21, effect-journal :31); remote-principal rows keep the receipt in the envelope with no CLI fix.

  • Op-handler parameter refusals (evidence-delivery.ts:1125): invalidParam/paramUse so MCP and CLI each see their own syntax. dispatch.ts:854 (registration-trust permission_denied) gets a hostFix naming the agent-facing registration command.
  • CLI argument funnels (sources-lifecycle-args.ts:16, takes-mutation.ts:20, embed-facts-options.ts:15, persistence-admin.ts:110-153, repair.ts, recall.ts, *-delegate.ts): invalid(message, suggestion) with a required suggestion; each call site names its own flag usage or the command's --help.
  • Coded funnels (shared-skills/adapter.ts:53, shared-skills/membership.ts:47, company-brain/receipts.ts:82): fail(code, message, suggestion, opts?); each of the 66 call sites names its own next step.
  • persistence/administration.ts [CEO-7]: invalid() loses its default suggestion; each of its 29 sites passes one.
  • Scanner: scripts/agent-contract-baselines/suggestionless-operation-error.tsv is deleted at 0, so the rule becomes zero-tolerance (check-agent-contract.ts:10). One new rule defaulted-suggestion: a function declaration, function expression or arrow function with a parameter named suggestion that has a default value, whose body calls one of opError, new OperationError, usageError, invalidParam, hostOnlyError, fails. Known hits today: administration.ts:22 and eval-gate.ts:464; both are fixed in this item, so the rule ships with zero hits and no baseline (bad/good fixtures in the guard self-test).
  • New registry codes only if a site needs one (unregistered-code enforces registration).
  • DX amendment (Phase 2.5, both voices): a zero-hit scanner rule generic-suggestion rejects a suggestion whose whole text is a generic denylist phrase ("see --help", "check your input", "try again", "run with --help"), so the backfill cannot pass with boilerplate; a site whose honest next step is the command's help names the exact flag usage instead. Sites pass docs: anchors where a doc section exists. Fixtures in the guard self-test.

Tests. Per module group, behavioural assertions on the envelope a caller sees (code, filled fix.argv or fix.mcp, next) in the module's existing owner test, one row per refusal class: test/repair*.test.ts, test/persistence-admin*.test.ts, test/shared-skills*.test.ts, test/capture*.test.ts, test/recall*.test.ts, test/sources-lifecycle*.test.ts, test/takes*.test.ts, test/company-brain*.test.ts. Scanner: bun run check:guard-self-test with the new rule's fixtures; bun scripts/check-agent-contract.ts passes with the baseline file absent.

Item 5 — Submit-time authorization on queued paid jobs

Producer table. Which basis each paid job gets (paid set: jobs/shared.ts:244 plus the gateway-refresh set):

Producer Job Basis stored Budget the worker enforces
book-mirror (consent-gated CLI) subagent ×N authorized, group {id, of: N} the approved total, shared by the group through durable reservations [T3]
enrich --background (consent-gated CLI, Postgres; one source via maybeBackground, several via the fan-out) enrich ×sources authorized, group {id, of: sources} same shared total, enforced per provider attempt by the invocation guard
pre-upgrade queued rows of the two producers above as above legacy_default (applied by the worker at claim time to a NULL row of these producers; one group per row) job-type cap: enrich data.maxCostUsd else DEFAULT_MAX_COST_USD ($5, enrich.ts:79); subagent the default paid cap ($5, consent.ts:84); cap_source: 'default'
agent run, MCP submit_agent, MCP submit_job / gbrain jobs submit (can queue enrich), doctor --remediate (its own --max-usd), autopilot/dream/cycle (patterns.ts:296, synthesize.ts:954,999), skillopt, import, reindex, sync, ingest_capture, embed backfill various none (NULL), reported as basis unrecorded unchanged: the producer's own budget where one exists (client daily budget for submit_agent, cycle BudgetMeter, configured embed caps, write-path embedding as the configured feature, --max-usd for remediation). `jobs submit enrich

Design.

  • Schema: a new migration (number from bun run new:migration minion_spend_authorization at implementation time), Postgres and PGLite:
    • minion_jobs.spend_authorization JSONB and minion_jobs.spend_claim_token BIGINT (per-acquisition fence, see DX amendments);
    • mcp_spend_reservations.budget_key TEXT and mcp_spend_log.budget_key TEXT (indexed), so the existing reserve-then-settle meter can key a budget by group instead of OAuth client;
    • the queue-protocol trigger (v149's enforce_minion_queue_protocol) also refuses a claim (status → active) of a row with non-NULL spend_authorization unless NEW.spend_claim_token = NEW.claim_generation;
    • no backfill: a new worker treats a claimed row with name subagent/enrich, NULL spend_authorization and an idempotency key starting book-mirror:, enrich: or cli:enrich: (book-mirror.ts:452, multi-source enrich.ts:880, single-source maybeBackground cli-options.ts:471) as legacy_default and writes that record in its claim UPDATE (Eng amendments). This covers pre-upgrade rows and rows an old producer inserts after the upgrade; rows already active at upgrade finish under the rules they started with. Other rows are untouched.
    • src/schema.sql and the PGLite schema get the same objects.
  • Stored shape (src/core/minions/spend-authorization.ts, strict parser): { version: 1, kind: 'authorized' | 'legacy_default', group_id (uuid v7 minted at submit), of?, consented_effects?, cap_usd: number | null, uncapped?: true, cap_source, via?, command, est_usd?, authorized_at }. uncapped: true (--max-usd off, or tokenmax on enrich) stores cap_usd: null; its jobs reserve nothing and spend is still ledgered. Built by jobSpendAuthorization(auth | { uncapped: true, via: 'max_usd' }, { command, est_usd, of }). Set only through a new trusted MinionQueue.add option spendAuthorization (beside allowProtectedSubmit, queue.ts:46); never read from job data (submission-authority.ts:1: payloads are never authority).
  • One approved total per command, shared by its jobs [T3, CEO dual-voice D2]: the user approved a total, not N equal slices. Every job of a group reserves against the group's remaining budget through src/core/minions/budget-meter.ts, generalized with budgetKey: 'group:<group_id>' and a lifetime window (today it is keyed by OAuth client and sums the current UTC day): before each provider attempt the job reserves that attempt's maximum liability through the invocation guard (see Worker enforcement), after it settles actual usage; an overdue hold stays charged until its usage is known, as the meter already does. Concurrent children cannot jointly exceed the cap (pg_advisory_xact_lock on the key on Postgres; on PGLite the reserve's read-then-insert runs in one serialized transaction, so concurrent PGLite workers cannot jointly exceed it either). A crash or reclaim resumes against the same remaining total; nothing per job needs seeding.
  • Unpriced models: under a derived/default cap a call with no price warns (BUDGET_TRACKER_NO_PRICING) and runs unmetered (the "new models must still run" rule); under a user cap it blocks with the no_pricing fix (look up the rate, gbrain pricing set, retry). pricingOverrides load through the same factory.
  • Worker enforcement: one wrapper runWithJobSpend(engine, job, ctx, fn) in spend-authorization.ts, called at both handler seams (worker.ts:1528, run-child.ts:166) in place of the bare handler call, so worker.ts (1764/1764 ceiling) and executeJob grow by at most one line (ceiling bumped with a rationale only if needed). For an authorized/legacy_default row it runs the handler under withAIInvocationGuard (src/core/ai/invocation-guard.ts), the seam withDelegatedSpend already uses (delegated-spend.ts:42-60): every provider attempt that goes through invokeAI (gateway chat/embed/rerank/multimodal, the legacy Anthropic subagent path, subagent.ts:560) reserves its maximum liability (maximumInvocationCents) against group:<group_id> and settles that exact reservation with measured usage; an attempt with unknown usage keeps its maximum charged (usage_unknown_reason), as delegated spend does. The guard nests under any delegated-spend guard (both must admit). BudgetTracker stays synchronous and unchanged; handlers keep their own trackers for their in-process caps. NULL rows run exactly as today.
  • Exhaustion is terminal: runWithJobSpend catches a group reservation refused on settled spend (pressure from live holds is a renewable wait; see amendments) from any handler and rethrows UnrecoverableError (dead, no retry) with derived_cap_exhausted (cap_source: derived) or cost_cap_exceeded (user/default; no_pricing keeps its own code and fix), reporting the group's spent, reserved and remaining amounts and the resume command, so a rerun with a higher --max-usd inserts a fresh group (the idempotency key is released for dead rows, idempotency-coalesce.ts). Under ctx.spend the enrich handler rethrows its caught exhaustion (handlers/enrich.ts:8-12 completes with result.budget_exhausted today).
  • Callers: book-mirror passes auth with of: N; enrich --background moves the consent gate before submission (single- and multi-source, estimate over all sources) and passes of: sources; maybeBackground (cli-options.ts:476) gains a spendAuthorization option it forwards to queue.add. --dry-run queues nothing and needs no consent. --max-usd off is itself the user's explicit authorization (as inline today, enrich.ts:1016) and stores uncapped: true. This consent fix is the PR's first commit (CEO dual-voice D5).
  • Coalesce: a resubmission that coalesces onto a row whose spend_authorization is NULL or legacy_default sets the new authorization with a CAS on the old value (taking effect at that row's next claim if it is active); an authorized row keeps its record, and the command prints one line naming the kept cap and the cancel-and-resubmit commands (gbrain jobs cancel --group <id>, then the same command); jobs get shows the same.
  • Saying so [X5]: one structured job_spend_basis log line per claimed paid job (job_id, name, basis: authorized | legacy_default | unrecorded, cap_usd, cap_source, group spent/remaining); unrecorded says plainly that no submit-time authorization exists and names the producer's own budget where one is known. gbrain jobs get --json gains spend_authorization, spend_basis and a why per basis.
  • DX/outside amendments (Phase 2.5):
    • Per-acquisition fence: the trigger requires NEW.spend_claim_token = NEW.claim_generation on every claim of a spend-authorized row; new workers' claim SQL sets spend_claim_token = claim_generation + 1 in the same UPDATE (queue.ts:~1458). An old worker increments claim_generation without touching the token, so its claim fails even after a new worker claimed the row earlier (a plain protocol column would stay set after a new worker's claim and let a later old-worker reclaim through). Rows already active at upgrade finish under the rules they started with; rows claimed afterwards carry enforcement. Test: new-worker claim → stall → old-worker reclaim is refused.
    • Pressure is not exhaustion: a reservation refused only because of live pending holds (committed + est ≤ cap but committed + pending + est > cap) is a renewable wait (job delayed with backoff, like RateLeaseUnavailableError), not death; only settled spend over the cap is terminal. Overdue holds from crashed attempts stay charged and doctor lists them with the reconciliation step. Test: two children reserve $8 each under a $10 cap, each costs $1, both finish.
    • Typed causes kept: no_pricing exhaustion keeps its code and pricing fix; only cost exhaustion maps to derived_cap_exhausted/cost_cap_exceeded.
    • Honest disclosure: the consent preview, the submit summary and jobs get say when a derived/default cap cannot meter an unpriced model.
    • Group controls: gbrain jobs list --group <id> --json (spent, reserved, remaining, member jobs) and gbrain jobs cancel --group <id>; coalesce and exhaustion messages print these group commands.
    • Rerun semantics: a rerun with a new --max-usd authorizes additional spend for the rows it submits or re-authorizes (a new group for dead and new rows; CAS re-authorization for NULL/legacy rows); reused authorized rows keep their group. The command prints a structured submit summary (reused/new jobs, group ids, caps). Test: a mixed completed/active/dead fan-out rerun.
    • Upgrade notice: the post-upgrade notice adds one line when queued paid jobs will run as legacy_default ("N queued paid jobs now run under a $5 default; re-run the command with --max-usd <x> to re-authorize").
    • The enrich --background exit-3 payload carries the estimate and a ready --yes --max-usd <derived> argv (consent machinery's fix), so a cron owner copies one line.
  • Doctor [X6]: the existing legacy-job-authority check adds an informational count of queued paid jobs by basis and flags spend-authorized rows waiting longer than 10 minutes while workers are running ("an un-upgraded worker may be fenced off; un-upgraded workers stop claiming at a fenced row"), with the read-only fix gbrain jobs list --status waiting --json and the upgrade/restart step. (No worker version registry exists, so doctor does not name workers.)

Tests.

  • New test/minions-spend-authorization.test.ts (unit, PGLite): parser accepts each kind and rejects malformed or data-supplied records; uncapped records reserve nothing; claim-time legacy_default applies only to NULL rows with the three key prefixes (including cli:enrich:); coalesce CAS; jobs get per basis; a legacy_default subagent runs under the $5 default cap and logs job_spend_basis.
  • test/minions/budget-meter.test.ts (the durable meter's suite; test/budget-meter.test.ts is the cycle meter) + new test/e2e/budget-meter-group.test.ts (Postgres E2E lane, picked up by run-e2e.sh): group key with lifetime window; two concurrent reservations cannot exceed the cap (controlled pause between the two reserves, both completion orders); overdue holds stay charged; existing client/day behaviour unchanged.
  • New test/minions-spend-authorization.serial.test.ts (worker in-process, fake chat gateway): with a $10 group of two children costing $8 and $1, both complete (headroom is shared); a child that would push the group past its cap dies with the exhaustion code, the group's remaining amount and the resume command; unpriced model under derived/default warns and runs, under user blocks; a stalled-then-reclaimed child resumes against the same remaining total; an enrich job's provider attempts reserve through the group guard.
  • Trigger: an old-protocol claim of a spend-authorized row is refused; a NULL row is still claimable (Postgres E2E + PGLite).
  • test/book-mirror.test.ts: every child row carries the authorization and the same group_id.
  • New test/enrich-background-consent.test.ts: non-TTY enrich --background without --yes exits 3 and queues nothing (single- and multi-source); with --yes each job carries the group record; an authorized enrich job that exhausts its group dies (not completes) and a rerun with a higher cap inserts a fresh group.
  • Migration tests per CONTRIBUTING (test/migrate.test.ts, goldens).

Eng amendments (Phase 3)

These change the items above where they conflict; the review record lists the findings they answer.

Item 1.

  • Affinity is evidence-gated, not name-gated: each class has a result predicate on the call it attaches to (timeline: a get_page result of an entity type with no timeline entries; stale chunks: a search/query whose vector arm ran and the brain's stale ratio passes runInitNudge's threshold; links: a link op on a brain under the init link-coverage threshold; takes: a takes op on a brain with zero takes). Thresholds are runInitNudge's, shared through collectOnboardOpportunities.
  • PGLite has one connection: the background refresh starts only while no dispatch is in flight and yields between counts; the cold-start count runs once per 6 h per brain (persisted cache). Measured on a 100k-chunk PGLite brain (first search latency with and without a refresh running), reported in the PR.
  • In-session preview: an onboard_* notice's fix is fix.mcp get_health (read-only, same connection) where that op is on the session's surface; the CLI remedy (and gbrain onboard --check) is named in why with "run after this session ends or through the running server", because a CLI command contends for the PGLite lock the stdio serve holds. Test: a file-backed PGLite journey with the notice-emitting serve alive.
  • first_run_decisions mute: NoticeLedger.admit honours mutes for ask notices listed in MUTEABLE_ASK_CODES (only first_run_decisions); docs/protocol/AGENT_OPERATOR_v1.md states the one exception to "ask always shows". The stdio mute fix changes only the lookup to mutedNoticeCodes('stdio') (which unions global mutes).
  • gbrain notices unmute <code> clears the code for every owner audience (global and stdio), so the advertised recovery works after an MCP mute. Test: MCP mute → CLI unmute → fresh stdio process shows the notice.
  • Under --access read-only notice text does not offer mute_notice (it is write-scoped); it names the CLI mute.

Item 2.

  • One mutable allow-set per stdio session, shared by the tools/list handler and dispatch; test that a widen is visible to both.
  • Widening can be turned off: config mcp.allow_session_widen (default true, the default-on rule); when off, the hint renders the persistent route. Every widen writes a stderr audit line (surface_widened, from, to, op).
  • The hint's persistent route names the harness's per-server env block (claude mcp add -e GBRAIN_SURFACE=full, Codex server env), never a shell profile, so one machine-wide variable does not override deliberate pins.

Item 3.

  • Throw-only connect: extract connectEngineForServe() from cli.ts's connectEngine into src/core/engine-connect.ts: it throws classified errors instead of exiting (vanished config, failed repair) and disconnects a partially started engine on failure. Both status call sites pass it; connectEngine keeps the exit behaviour at the CLI boundary by wrapping it. Net cli.ts lines ≤ 0.
  • One listener, one lifecycle owner: the status listener is a node:http server whose request handler is a mutable reference. Recovery builds the full app with buildServeHttpApp (serve-http.ts:605, already separate from listening) while the status handler keeps answering, then swaps the handler; runServeHttp takes an adoptServer option that listenOrRefuse returns as-is instead of binding (ceiling bump for serve-http.ts, +≤3 lines, with rationale). No close-and-rebind, so no port race. A failed build disconnects the engine, releases the lock and keeps the status handler (reason brain_unopenable).
  • Single-flight tick: the HTTP re-probe is a chained setTimeout (next tick scheduled after the current reprobe settles) plus an in-flight flag; shutdown (SIGTERM/SIGINT) during a recovery waits for it, then closes once. Sockets accepted before the swap are tracked by the same lifecycle.
  • Per-instance marker: GBRAIN_HOME/serve-http-status-<port>.json { pid, instance_nonce, brain_id, bind, port, reason, since }; /health returns instance (the nonce) so doctor matches marker and responder; a process removes only its own marker. Readiness treats a marker as live only when its PID is alive and since is after the last boot.
  • Probes: docs/mcp/DEPLOY.md says /health answers 503 in status mode (container health checks will restart the container; use --fail-fast there). gbrain mcp expose verification reports "status-only" with the reason instead of "failed".

Item 4.

  • The defaulted-suggestion rule also flags an optional or nullish-coalesced suggestion parameter (any name ending suggestion/hint) on a function whose body calls the listed constructors.
  • Each funnel gets one table-driven test that collects every call site's suggestion (via the scanner's site list) and asserts it is non-empty and not on the generic denylist; a reviewer reads a sample per file in the PR.

Item 5.

  • Seam: the invocation guard replaces tracker hooks (see Worker enforcement). It covers every provider attempt routed through invokeAI, retries included, with a per-attempt reservation handle. Unpriced models: under a derived/default cap the guard reserves 0 with estimateKnown: false and logs BUDGET_TRACKER_NO_PRICING (runs, disclosed as unmetered); under a user cap it refuses with no_pricing and the pricing fix.
  • Bounded pressure: only live (non-overdue) holds count as pressure. Overdue holds count as committed spend, so a group whose committed spend plus overdue holds leaves no room dies with cost_cap_exceeded/derived_cap_exhausted and a reconcile line naming the overdue holds. A renewable wait is capped at 6 renewals (one reservation TTL); after that the job dies with the same envelope.
  • Typed errors end to end: group refusals are must-abort in worker-pool.ts (stop claiming items, keep the checkpoint); the child codec (job-isolation.ts) carries code, fix and the group amounts; the worker maps pressure to delayed and exhaustion/no_pricing to dead; jobs get shows the persisted envelope.
  • Mixed versions: child readiness (child-readiness.ts) gains a required spend-enforcement-v1 feature (CHILD_READINESS_FEATURES, child-readiness.ts:17) for spend-authorized rows; a parent never hands such a row to an executor without it (the row is released, not failed). Test: new parent, pre-change child binary.
  • Schema: mcp_spend_reservations.client_id and mcp_spend_log.client_id become nullable with a CHECK that exactly one of client_id/budget_key is set; admin spend views and spend-log.ts per-client reads filter to client_id IS NOT NULL; an expression index on minion_jobs ((spend_authorization->>'group_id')) serves jobs list/cancel --group.
  • jobs submit route [T8, provisional]: CLI gbrain jobs submit enrich|subagent runs the same consent gate (--yes, --max-usd) and stores an authorized record; the enrich --background exit-3 payload no longer has an unconsented alternative. agent run consent stays a P2 TODO.

Cross-cutting.

  • T1 sequencing: build → eval cell → keep or flip the constant; an inconclusive eval keeps starter.

Eng tests added (beyond each item's list).

  • test/minions-spend-authorization.serial.test.ts: two concurrent attempts in one enrich job ($8 then $1, settled in reverse order) settle their own holds; a crashed child's overdue hold does not livelock a sibling (dies with the reconcile line); a legacy Anthropic subagent path is metered; a group refusal inside an enrich worker pool stops the pool and dies with the typed envelope through the child codec; a final call that overshoots is charged and the next reservation is refused.
  • Trigger E2E: a fenced row ahead of a NULL row against an old-protocol claim (old worker stalls, documented); new parent + old child executor releases the row.
  • test/e2e/budget-meter-group.test.ts: admin spend excludes group rows; CHECK rejects rows with both keys.
  • test/serve-http-status-mode.serial.test.ts: loopback request (as Funnel delivers it) gets the collapsed reason; a slow connect stub across three ticks connects once; SIGTERM during recovery shuts down once and removes only this instance's marker; two status daemons on two ports keep separate markers; a failed full-app build keeps the status handler answering on the same socket.
  • test/mcp-onboarding.test.ts: a note page get_page gets no timeline notice; an entity page without timeline does; read-only access omits mute_notice from text.
  • test/request-tools-stdio.test.ts: widen visible to tools/list and dispatch; mcp.allow_session_widen=false refuses with the persistent route; audit line written.
  • test/cli-jobs-submit-consent.test.ts: non-TTY jobs submit enrich without --yes exits 3 and queues nothing.

Cross-cutting

  • Registry: reuse serve_status_only, derived_cap_exhausted, cost_cap_exceeded; register any new code a site needs; regenerate docs/guides/error-codes.md (bun run build:error-codes).
  • Docs (declarative, current state): docs/protocol/AGENT_OPERATOR_v1.md (notices by transport, HTTP status-only mode, queued paid jobs), docs/operations/spend-controls.md (queued paid work rows), docs/mcp/DEPLOY.md and docs/guides/remote-mcp.md (HTTP status mode, --fail-fast), MEMORY_VERBS_v1.md, docs/mcp/CODEX.md, KEY_FILES entries for every touched file (agent-contract.md, mcp.md, agent-bootstrap.md, core-minions-1.md, core-minions-2.md, commands-1.md; budget-meter.ts entry), the Deferred list in docs/designs/AGENT_OPERATOR_WAVE.md, llms.txt/llms-full.txt regenerated.
  • TODOS.md: close the five items and the P3 module-local fail-helpers item; file: agent run consent for paid job names (P2; plus jobs submit if T8 is declined), OpenClaw starter pin after a gap check (P2, if T5 stands), owner-principal HTTP onboarding coaching (P3).
  • CHANGELOG: one entry with "Behavior changes for scripts and agents" rows: HTTP status-only mode (and --fail-fast), GBRAIN_SURFACE honoured by stdio serve, new registrations use starter, enrich --background asks for consent, queued consent-gated jobs (including pre-upgrade book-mirror/enrich rows, $5 default) enforce their cap and die on exhaustion with a resume command.
  • Size ceilings: src/cli.ts (3199/3199) changes only by the connect extraction (net ≤ 0 lines); worker.ts (1764/1764) and executeJob grow ≤1 line each via the wrapper (ceiling bumped with rationale only if needed); new logic lives in new modules.
  • Timed journeys (DX): rerun Lane I's fresh_install_to_wired_recall (CLI + stdio) and add one existing-HTTP- brain journey (connect a harness to a shared serve --http, including a status-mode interval), reporting machine time, user round-trips and time to find the right recovery doc (reported, not gating).
  • Measured evidence (CEO dual-voice D7): besides the T1 cell, one agent-task row checks whether an agent shown an onboard_* notice relays it (or acts on it) and whether a request_tools widen completes a task that needed a non-starter op; both reported in the PR and mirrored into gbrain-evals (reported, not gating).
  • Rollback note (CHANGELOG): rolling the binary back leaves queued rows with spend_authorization fenced from older workers; cancel them (gbrain jobs cancel <id>) or clear the column on queued rows before downgrading.
  • Verification: bun run verify (scanner, guard self-test, size ratchets), bun run test, serial lane, bun run test:e2e lifecycle, then bun run ci:ubicloud before ready.
  • Size: 47 source files, ~25 test files, ~12 docs. Item 4 is the largest (210 refusal sites in 33 files).

Coordination

  • GBRA-50 (capy/engine-graduation, not merged) changes the same status-only paths: a serve respawned during graduation exits with graduation_in_progress, and a status-only or degraded serve re-reads config and exits on an engine-identity change or a graduation tombstone, through one helper called from the status-only paths. This plan does not depend on that branch; it keeps one status-only entry point (runStatusModeServe) and one re-probe function (reprobe) for stdio and HTTP, so GBRA-50's helper needs no second call site. Whichever lands second rebases onto the other and puts the helper call inside reprobe/the entry point.
  • Open PRs touching the same files: #6002 (src/commands/recall.ts, item 4 edits :841-860), #6010 claims v0.60.49.0 (this wave takes the next free PATCH at ship time).

Risks

  • Item 2 narrows new bootstrap registrations from full to starter: a bootstrap skill calling a non-starter op hits the F6 hint (now with a working fix). Mitigation: the gap list is enumerated and noted before ship.
  • Item 3 serves an unauthenticated status endpoint on a possibly public bind. Mitigation: allowlisted payload with path-free texts, reason collapsed on every unauthenticated response (Funnel publishes a loopback bind), no brain data, tested with a non-standard path and a loopback request.
  • Item 3 and GBRA-50 both change serve-status.ts/status-mode.ts; merge conflict risk is limited to the entry point and reprobe, by design.
  • Item 5 generalizes budget-meter.ts (today OAuth-client/day only) with a group key and lifetime window; the existing client budget behaviour must stay byte-identical (pinned by its existing tests).
  • Item 5 makes pre-upgrade book-mirror chapters (claimed as legacy_default, $5 per child) and authorized groups terminal on exhaustion; an expensive-model chapter that finished before the upgrade can now die. Mitigation: the resume command, completed chapters skipped on rerun; stated in the CHANGELOG behaviour row.
  • Item 5 fences old workers off spend-authorized rows (trigger): an un-upgraded worker stops claiming at the first fenced row in its queue order (the claim selects one row, then the trigger refuses it; v149 precedent), so it processes nothing until it restarts on the new binary. Doctor flags long-waiting authorized rows; the CHANGELOG says "restart workers after upgrading". A new parent worker refuses to hand authorized rows to a child executor that lacks the spend-enforcement capability.
  • Item 4 touches 33 files that other threads may edit; coordinate landing order (cross-thread rule).

NOT in scope

  • Tool-call proxy for a second serve (P2, IPC forwarding).
  • consent.preapprove.paid.max_usd_per_day (P2); this wave's group/lifetime meter key is reusable groundwork.
  • Contract v2 / legacy-shape removal; exit 3 for mcp expose / google.
  • Connectors two-step OAuth.
  • HTTP registration surfaces (per-client rows, server ceiling).
  • Consent for agent run and caps for other producers that already have their own budgets.
  • Raising a live group's cap in place (a rerun authorizes additional spend instead).
  • The other scanner baselines, except where a touched file shrinks them as a side effect.
  • Item 1: on stdio only, onboarding notices use one registered, muteable coaching code per class (onboard_stale_chunks, onboard_link_coverage, onboard_timeline_coverage, onboard_no_takes), attach only to calls in the closed ONBOARD_CALL_AFFINITY map (every name exists; every class reachable on verbs and starter), and pass admitNotices (per-process dedupe, 2/session coaching budget, mute); counts cached per process (warmed after engine boot, 6 h TTL, 3 s budget, never on the call path; cold-cache calls get none); stale-chunk class suppressed on keyless/disabled-by-choice brains; empty brain and GBRAIN_NO_ONBOARD_NUDGE=1 emit nothing; fix is argv-only gbrain onboard --check, rendered next: tell_user_to_run with a user_message over MCP; HTTP emits none (documented); tests in test/mcp-onboarding.test.ts, mcp-notice-channels, init-nudge (init output unchanged).
  • Item 1: first_run_decisions (writeback, skills scaffold; no search_mode, no harness_wiring) reaches stdio once per session while a decision is open, nothing persisted on delivery; answered decisions drop out; first_run_decisions is muteable as the one ask exception; tested.
  • Item 1 (taste T4, provisional): features_auto_fix rides the affinity channel on link ops only, shouldPitch applied read-only, consent paid only when a paid fix id is present.
  • Item 2: stdioServeArgv(bin, surface = REGISTRATION_SURFACE) used by readiness, bootstrap hooks (Claude, Codex), opencode, init quickstart and the plugin generator; REGISTRATION_SURFACE = 'starter' (taste T1, provisional) is confirmed or replaced by one gbrain-evals cell (verbs/starter/full on bootstrap-skill and memory-loop tasks, current frontier models, mirrored to gbrain-evals) before ship; OpenClaw manifest unchanged (taste T5, provisional); HTTP registrations out of scope; builder test.
  • Item 2: request_tools on stdio widens this session's allowed ops to the requested surface (never past --access read-only, never on HTTP) and sends tools/list_changed; nothing persisted; the hidden-tool hint fix is fix.mcp request_tools {surface:'full'}, next: run, with the persistent routes (GBRAIN_SURFACE, plugin setting) and the inherited-env warning in why; tests in test/request-tools-stdio.test.ts and test/hidden-tool-hint.test.ts.
  • Item 2: stdio serve resolves GBRAIN_SURFACE > --surface > config > full; an invalid value is ignored with a stderr line and a once-per-process surface_env_invalid info notice; serve --http ignores the env with a stderr line; tested.
  • Item 2: never narrow an existing install: bootstrap hooks keeps a matching entry untouched and carries the existing --surface over when it replaces a mismatched entry; no doctor surface check; bootstrap skill starter gaps enumerated before implementation and noted (no STARTER_OPS change).
  • Item 3: one entry point runStatusModeServe and one reprobe(state, connect) for stdio and HTTP (stdio inside tool calls, ≤1/5 s; HTTP 5 s background tick, taste T2 provisional), with the guarded no-config reconnect; --http eligible unless --fail-fast/GBRAIN_SERVE_FAIL_FAST=1; cli.ts call sites unchanged; Postgres connect failures keep the degraded path.
  • Item 3: HTTP status listener (node:http + SDK stateless StreamableHTTP, one tool): /health 503 + Retry-After, /mcp with only gbrain_status, 503 envelope on OAuth/admin routes; allowlisted path-free payload, http-rendered fixes; on non-loopback binds reason collapses to unavailable; exits via listenOrRefuse (serve_port_in_use) on a taken port; marker GBRAIN_HOME/serve-http-status.json, live by PID (+ /health 503 within 500 ms in doctor, which deletes dead markers), read by readiness/doctor (http_serve_status_only); recovery boots the full server on the same port, and a failed boot returns to status mode (brain_unopenable) instead of exiting; injectable tick; transport-aware status texts.
  • Item 3 (X1/X2): a recovered HTTP server that was in status mode answers authenticated gbrain_status (read scope, checked before the op lookup, never listed) with status: recovered; serve_status_mode_enter/_recovered log lines.
  • Item 3 tests: test/serve-http-status-mode.serial.test.ts (non-prefix path, non-loopback reason collapse, tools list, marker + doctor, recovery with auth, recovered alias, --fail-fast, serve_port_in_use, stale marker, no-config recovery, thin client) plus shared-reprobe and Postgres-degraded unit rows.
  • Item 4: every baselined site gets opError with a filled suggestion and, wherever a next step exists, a filled fix (B10; receipt fixes only for CLI principals); op-handler parameter refusals via invalidParam/paramUse; CLI-argument funnels invalid(message, suggestion); coded funnels fail(code, message, suggestion, opts?); administration.ts and eval-gate.ts:464 lose their defaults; dispatch.ts:854 gets a hostFix; baseline file deleted; zero-hit defaulted-suggestion rule (function/arrow declarations calling opError, new OperationError, usageError, invalidParam, hostOnlyError) with fixtures; acceptance bar is zero scanner hits (~210 sites in 33 files); one envelope test per refusal class with a filled fix.
  • Item 5: producer table governs basis: book-mirror and enrich --background store authorized with one group_id; their pre-upgrade queued rows (statuses waiting, delayed, paused, waiting-children, active; key prefixes book-mirror:, enrich:, cli:enrich:) are stamped legacy_default under the job-type cap else $5 default; every other producer stays NULL, reported as basis unrecorded.
  • Item 5 (taste T3 revised, CEO dual-voice D2): a group's jobs share the approved total through budget-meter.ts generalized with a group:<id> key and lifetime window (reserve each call's estimate, settle actual; overdue holds stay charged; concurrent children cannot exceed the cap); unpriced models warn and run under derived/default caps and block under user caps; runWithJobSpend at both seams installs one tracker with async reserve/settle hooks; enrich receives the wrapper's tracker; exhaustion or a refused reservation is terminal (dead) with derived_cap_exhausted/cost_cap_exceeded, group spent/reserved/remaining and the resume command.
  • Item 5: migration adds spend_authorization, claim_protocol, meter budget_key columns and a trigger refusing old-protocol claims of spend-authorized rows (CEO dual-voice D4); strict parser; trusted MinionQueue.add option only; uncapped records reserve nothing.
  • Item 5: enrich --background gates consent before queueing (first commit of the PR; exit 3, nothing queued without authorization; --dry-run exempt; --max-usd off stores uncapped); maybeBackground forwards spendAuthorization; coalesce CAS onto NULL/legacy rows (active rows at next claim), authorized rows keep their record with a printed line; job_spend_basis log line and jobs get fields; doctor counts queued paid jobs by basis and names fenced old workers.
  • Evidence (D7): T1 eval cell plus one agent-task row on onboarding-notice relay and request_tools widening, reported in the PR and mirrored to gbrain-evals (not gating); CHANGELOG rollback note for fenced rows.
  • Coordination: GBRA-50 hooks the shared entry point/reprobe; no dependency on its branch; #6002 landing order for recall.ts.
  • Cross-cutting: registry/docs/KEY_FILES/TODOS/CHANGELOG as listed; cli.ts not edited, worker.ts/executeJob ≤1 line; PATCH auto-allocated; verify + unit + serial + E2E + ci:ubicloud before ready.
  • Replacements of CEO obligations: the worker fence is the per-acquisition spend_claim_token = claim_generation check (not claim_protocol); readiness/doctor use serve_status_only with transport: 'http' (not http_serve_status_only); mute_notice joins STARTER_OPS (the one starter change).
  • Item 1: first-run bundle attaches to the second successful call with "finish the user's current request, then ask"; counts persist in GBRAIN_HOME/onboard-counts-<brainId>.json (6 h TTL); each class names its concrete remedy (cost/consent where paid) with onboard --check as preview; stdio mute bug fixed (dispatch reads the stdio audience) and tested across a fresh process; first-run MCP-rendered fixes tested; doctor/onboard --check list muted open decisions with the unmute command.
  • Item 2: hint is surface/access-aware (request_tools only when callable, else persistent route tell_user_to_run); stdio widen returns persisted:false, scope:'session' and the new ops' schemas, transport-neutral descriptions; surface provenance on startup, whoami, gbrain_status; --surface on bootstrap hooks and init wiring; never-narrow keeps pinned or bare form exactly; docs: why-starter sentence, precedence table, starter-gap list (get_timeline), request_tools transcript; tests for read-only, verbs, list_changed-ignoring client (call by name), bare registration.
  • Item 3: human status banner; mcp-client.ts/remote-mcp-probe.ts render 503 serve_status_only envelopes from discovery/token/mcp (tests: cold creds, expired creds, recovery); post-recovery 401 + WWW-Authenticate re-auth tested and documented; curl -i /health transcript.
  • Item 4: zero-hit generic-suggestion denylist rule with fixtures; docs: anchors where a section exists.
  • Item 5: renewable wait on reservation pressure (test: $8+$8 reservations under $10 cap, $1 actual each, both finish); terminal only on settled exhaustion; overdue holds listed by doctor; no_pricing keeps its code and fix; unmetered-unpriced disclosure in preview, submit summary and jobs get; gbrain jobs list --group and jobs cancel --group; rerun semantics + structured submit summary (test: mixed completed/active/dead fan-out); post-upgrade line for legacy_default rows; enrich exit-3 payload carries the estimate and a --yes --max-usd fix; per-acquisition fence test (new claim → stall → old reclaim refused).
  • Cross-cutting: timed journeys (install CLI+stdio; existing HTTP brain with a status interval; doc findability), reported not gating; NOT in scope adds raising a live group's cap.
  • Replacements of CEO/DX obligations: group spend is enforced through withAIInvocationGuard per provider attempt (max-liability hold on group:<id>, exact settle) instead of async BudgetTracker hooks or passing the wrapper's tracker to enrich; legacy_default is applied by the worker at claim time to NULL rows with the three key prefixes (no migration backfill; rows already active at upgrade finish as started); every unauthenticated HTTP status response collapses reason (not only non-loopback binds); recovery swaps the request handler on one bound listener (no close-and-rebind); the status marker is per port and per instance; doctor flags long-waiting authorized rows instead of naming workers; cli.ts changes only by the throw-only connect extraction (net ≤ 0 lines).
  • Item 1: affinity gated by per-class result predicates with runInitNudge thresholds; PGLite refresh idle-gated, latency measured on a 100k-chunk brain; in-session preview fix.mcp get_health, CLI remedy timing stated; MUTEABLE_ASK_CODES exception for first_run_decisions documented in AGENT_OPERATOR_v1; stdio mute uses mutedNoticeCodes('stdio'); gbrain notices unmute clears every owner audience (test MCP mute → CLI unmute → fresh process); read-only text omits mute_notice.
  • Item 2: one mutable per-session allow-set shared by tools/list and dispatch (tested); mcp.allow_session_widen (default true) with surface_widened audit line; hint's persistent route names the per-server env block.
  • Item 3: connectEngineForServe throw-only connect in src/core/engine-connect.ts with partial-start cleanup, used by both status call sites; runServeHttp({ adoptServer }) + handler swap after buildServeHttpApp, failed build keeps the status handler and releases the lock; single-flight chained 5 s tick, shutdown serialized with recovery; marker serve-http-status-<port>.json with instance nonce returned by /health; DEPLOY note on 503 health probes; mcp expose reports status-only; tests: loopback collapse, slow-connect single open, SIGTERM during recovery, two-port markers, failed build.
  • Item 4: scanner flags optional/nullish suggestion parameters; per-funnel table-driven tests over every call site (non-empty, not denylisted).
  • Item 5: overdue holds are committed spend, only live holds are pressure, renewable wait capped at 6 renewals; typed errors carried through worker-pool must-abort, child codec and worker disposition; spend-enforcement-v1 child readiness feature (new parent + old child test); nullable client_id with one-key CHECK, admin/spend reads filtered, group_id expression index; Postgres group test in test/e2e/budget-meter-group.test.ts and test/minions/budget-meter.test.ts extended; tests: reversed in-job settle, overdue-hold sibling, legacy Anthropic path metered, pool refusal through child codec, final-call overshoot, fenced row ahead of NULL row; unpriced under derived/default reserves 0 and runs disclosed, under user cap refuses no_pricing.
  • Item 5 (taste T8, provisional): CLI gbrain jobs submit enrich|subagent runs the consent gate and stores an authorized record (test test/cli-jobs-submit-consent.test.ts).
  • Cross-cutting: T1 sequencing build → eval → keep/flip, inconclusive keeps starter; meter docs correct the PGLite serialization reasoning; test plan artifact user-master-eng-review-test-plan-20261004-184202.md.

Coordination addendum (GBRA-50, 2026-10-04)

GBRA-50 graduation touches the same serve paths (origin/capy/graduation-g3-cli @ 18c4506f7, to be integrated into capy/engine-graduation):

  • src/cli.ts connectCliOnlyEngine: exits 75 graduation_in_progress during a graduation run; the degraded-serve reconnect checks for an engine-identity change.
  • serve-status.ts: preConnectStatusReason + the runStatusModeServe reconnect.
  • status-mode.ts: StatusReason gains engine_graduated; probeStatus/statusHeadline/statusFix handle it.
  • serve.ts: installGraduationHandoff + an onShutdownReady hook in installStdioLifecycle (function-size baseline 315 -> 316).
  • new src/core/persistence/graduation-serve-guard.ts (file reads only). Whichever lands second merges master and re-attaches the other's calls; Item 3's engine-connect extraction must keep the graduation identity check on the reconnect path.