Garry's Opinionated OpenClaw/Hermes Agent Brain
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:
- 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 throughwriteCliNotices(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. - Every stdio wiring path registers a different MCP surface.
- readiness
harness_wiringfix and init's quickstart:--surface verbs(src/core/readiness.ts:397-398,src/commands/init-first-run.ts:144); gbrain bootstrap hooksfor 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 byscripts/generate-plugin-tree.ts); - OpenClaw plugin manifest: bare
serve(openclaw.plugin.json:37), resolving to configmcp_surface, elsefull; - docs:
docs/protocol/MEMORY_VERBS_v1.md:52-77say--surface verbs. The same user gets 7, ~30 or ~130 tools depending on which install command an agent ran. Bootstrap pinsfullbecause its skills needput_page/get_page/timeline, whichverbslacks (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) readsGBRAIN_SURFACE;serveresolves flag > config > full (src/mcp/surface.ts:172-180). On a direct registration the advertised fix does nothing.
- readiness
- A losing
serve --httpexits. stdio serve answers lock contention / missing brain / unreadable config with a status-only server exposing onegbrain_statustool (src/commands/serve-status.ts,src/mcp/status-mode.ts).statusModeEligibleexcludes--http(serve-status.ts:21-23), socli.ts:2573-2621rethrows thepglite_busyconnect error and the HTTP daemon exits. A supervisor (launchd/systemd frommcp expose) crash-loops it; every HTTP client sees a dead endpoint instead of the explanation and fix. - 74 suggestion-less
OperationErrorsites in 31 files (scripts/agent-contract-baselines/ suggestionless-operation-error.tsv; list insuggestionless-hits.txtbeside this plan). Counting rule used throughout: 6 of the 74 hits are funnel-helper definitions that serve 108 call sites (measured withgrep -cincluding each definition line:shared-skills/adapter.tsfail×25,shared-skills/membership.tsfail×21,commands/sources-lifecycle-args.tsinvalid×25,company-brain/receipts.tsfail×23,commands/takes-mutation.tsinvalid×14,core/embed-facts-options.tsinvalid×6); the other 68 are direct sites. Refusals to fix: 68 + 108 = 176, plus 29 inpersistence/administration.ts[CEO-7] and 1 incommands/eval-gate.ts:464(and its ~7usage(callers): roughly 210 refusal sites across 33 files. The acceptance bar is the scanner, not the count: zero suggestion-less hits and zerodefaulted-suggestionhits. The TODOS entry namessrc/cli.ts; the baseline instead holdssrc/mcp/dispatch.ts:854(the TSV is authoritative). - Consent-gated paid work that is queued carries no consent record, and the approved cap is not enforced.
book-mirrorgets anAuthorizationfromconsentGateOrExit(src/commands/book-mirror.ts:420) and discards it; its Nsubagentchildren (:455) run in the worker with noBudgetTrackerscope (src/core/minions/worker.ts:1528,src/core/minions/run-child.ts:166install only submission authority), so the printed derived cap (estimate × 1.5) is never applied. Bug found while grounding:enrich --backgroundon Postgres (src/commands/enrich.ts:950-981) queues paidenrichjobs 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 countsrunInitNudgeruns today, moved out ofinit-nudge.ts:52-91into 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, keysession|code) cannot drop one class behind another:onboard_stale_chunks,onboard_link_coverage,onboard_timeline_coverage,onboard_no_takes(CLI init keepsonboard_opportunities); these four joinNOTICE_CODESascoaching, somute_noticeandgbrain notices muteaccept them. Each has its ownwhy(the count and what it limits) and the read-only fixgbrain onboard --check(argv only;run_onboardis mutating and admin-scoped, so it is never offered as the MCP route). On an MCP transport a CLI-only fix rendersnext: tell_user_to_runby the publishedderiveNexttable (row 3), so the MCP-only agent relays the command withuser_messageinstead of trying to run it; each notice carries thatuser_message. The stale-chunk class is suppressed when readiness reports embeddingsdisabled_by_choiceor 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 theverbssurface and on thestartersurface. features_auto_fix[T4]: the existingfeaturesAutoFixNotice(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-usershouldPitchfilter (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 byonboard_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)reusesbuildInitFirstRunNotices(init-first-run.ts:96) with stdio inputs only:writebackwhenwritebackAskApplies(engine)(writeback-nudge.ts:44, already gated on "shown once ever" and "operator answered") andskillsScaffoldfrominitSkillsScaffold().search_modeis not offered over MCP (nothing records whether the user confirmed init's default; init anddoctorkeep it), andharness_wiringis omitted on stdio (readiness sayswired_running). Kindask(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.tskeeps the same rule). Answered decisions drop out on their own (writebackAskAppliesfalse oncememory.auto_writebackis set; the scaffold decision once the skills exist); a user who dismisses the bundle mutesfirst_run_decisionswithmute_notice(this code joins the muteable set as an explicit exception forask, since an unanswered ask must stay dismissible). - Wiring:
src/mcp/dispatch.tssuccess path, beside:905, stdio andopts.remote !== falseonly: first-run bundle (once) plus affinity-matched opportunity and features notices, throughadmitNotices(dispatch.ts:568): per-process dedupe, 2 coaching notices per session (notice-ledger.ts:23), mute (mutedNoticeCodes). One call intomcp-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=1silences 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
whysays "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 andpaidconsent, link/timeline extraction, takes), withgbrain onboard --checkas the read-only preview fix. - Bug fix found in review:
mute_noticeon stdio stores the mute under principalstdio(ops/notices.ts:31) while dispatch reads mutes withopts.auth?.clientId, which is undefined on stdio (dispatch.ts:571), so a stdio mute never applies. Dispatch reads the samestdioaudience.mute_noticejoinsSTARTER_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 andgbrain onboard --checklist muted-but-open decisions withgbrain notices unmute first_run_decisions.
- 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
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] andstdioServeArgv(bin: string, surface: McpSurface = REGISTRATION_SURFACE): string[]. Every path that writes a stdio registration builds from it: readinessstdioRegistration(readiness.ts:397-403, plus itswhytext:429),registerClaudeMcp/registerCodexMcp(hooks.ts:902,919), opencode (bootstrap.ts:1270-1271, project scope keeps PATH-resolvedgbrain), init's quickstart (via readiness), and the plugin generator (scripts/generate-plugin-tree.ts; variants already shipstarter, 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,queryare inSTARTER_OPS,surface.ts:89-106;get_timelineis not), includes the seven verbs, matches the plugin lanes and avoids the ~130-toolfulllist. - OpenClaw manifest [T5]: left as bare
servethis wave (configmcp_surfacedecides). It ships the whole skill catalogue, which has not been checked againststarter, 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 harnessHTTP entries andserve-service.ts:154are governed by per-client surface rows and the server ceiling (effectiveSurfaceForClient), a different mechanism. GBRAIN_SURFACEhonoured by stdioserve: 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-processinfonoticesurface_env_invalidnaming the three values and the surface actually served.serve --httpignoresGBRAIN_SURFACEand prints one stderr line saying so (FOV-6a: an HTTP ceiling never widens without an explicit--surfacerestart;GBRAIN_MCP_FORCE_SURFACEstays HTTP's narrowing switch).- Runtime widening on stdio (CEO dual-voice D1):
request_tools(src/core/ops/request-tools.ts, already inSTARTER_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 sendstools/list_changed(the server already declareslistChanged,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_toolsis callable (see DX amendments) the fix becomesfix.mcp: { tool: 'request_tools', arguments: { surface: 'full' } }, consent[],next: run(one call, no restart), with the CLI equivalent kept asargv. Itswhynames the persistent routes:GBRAIN_SURFACE=fullin the harness's server env (or the plugin setting on launcher installs) and that an inheritedGBRAIN_SURFACEoverrides a pinned--surface. - One rule: never narrow an existing install. A new registration gets
starter.bootstrap hookskeeps 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--surfacevalue 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_OPSchange this wave ismute_notice(Item 1). Before implementation, the generator's starter-gap check (scripts/generate-plugin-tree.ts) runs over the skillsbootstrapinstalls; 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/fullstdio 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 andrequest_toolswidenings. The winner setsREGISTRATION_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_toolsonly whenrequest_toolsis callable on this connection (isCallable; it is absent onverbsand under--access read-onlybecause it is mutating); otherwise the fix is the persistent route renderedtell_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 ignoretools/list_changedstill work); the op and param descriptions become transport-neutral ("per OAuth client on HTTP, this session only on stdio"). - Surface provenance:
serveprintssurface=<x> (source: env GBRAIN_SURFACE | --surface | config | default)at startup, andwhoamiandgbrain_statusreturnsurfaceandsurface_source. - Escape hatch:
bootstrap hooksand init's wiring step take--surface <verbs|starter|full>, passed throughstdioServeArgv(bin, surface). - Never-narrow preserves the previous effective form exactly: a pinned
--surface xstaysx, and a bareserve(config/default resolution) stays bare on replacement. - Docs: one sentence in
MEMORY_VERBS_v1.mdon why the default isstarter(verbs lacks page writes); a four-row surface-precedence table and the bootstrap starter-gap list (known:get_timeline) indocs/operations/mcp-surface-runbook.md; a copy-pasterequest_toolstranscript.
- The hidden-tool hint is surface- and access-aware: it offers
- Docs:
MEMORY_VERBS_v1.mdinstall 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:statusModeEligibleadmits--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--httpinternally. Both cli.ts call sites pass the new throw-only connect (Eng amendments); the extraction keepscli.tsat or under its 3199-line ceiling.- Shared re-probe:
status-mode.tsgainsreprobe(state, connect):probeStatus()(config +peekLock()file reads only), thengatedReconnectwhen 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. Theconnectthunk is a throw-only connect (Eng amendments; today both status call sites pass bareconnectEngine(),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 byrunStatusModeServefor--http: a barenode:httpserver on the same--bind/--portwith the MCP SDKServer+StreamableHTTPServerTransportin stateless mode (protocol-version negotiation from the SDK) exposing exactlygbrain_status:GET /health→ 503 with the HTTP status payload andRetry-After: 5.POST /mcp→initialize(instructions: transport-aware status line),tools/list→[gbrain_status],tools/call gbrain_status→ payload, any other tool → oneserve_status_onlyerror block./.well-known/*,/token,/authorize,/register,/admin*→ 503 JSONserve_status_onlyenvelope.- 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, norepair_faileddetail, noshare_http_plan), fixes rendered fortransport: 'http'(actorhost_admin,next: tell_user_to_run). Every unauthenticated HTTP status response collapsesreasontounavailableand the text to "this gbrain server cannot open its brain; its host operator can see why withgbrain 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
listenOrRefuserefusal (serve-http-listen.ts:20:serve_port_in_useenvelope 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,/healthanswers 503 within 500 ms; a dead marker is deleted by doctor. Readinessharness_wiringand 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 "startgbrain serve --http" on a taken port.
- Recovery: when
reprobeconnects, 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 reasonbrain_unopenableand a stderr line, instead of exiting. The 5 s tick is injectable for tests. - Transport-aware texts:
statusPayload,statusFix,statusInstructionLine,statusModeErrorResultand the recovered payload take the transport; HTTP text never claimstools/list_changedwas sent. - Stale client lists [X1]: stateless HTTP cannot push
tools/list_changed(MCP 2026-07-28 delivers it on asubscriptions/listenstream to subscribed clients), so a client may callgbrain_statuson the recovered full server. Only a process that entered status mode keeps the alias:serve-http-mcp.tschecks it before the operation lookup (independent ofsurfaceAllowedOps, which isundefinedon a full surface with no grants,serve-http-mcp.ts:160), requiresreadscope, never lists it, and answersstatus: recoveredwith "re-list tools or restart this MCP connection". A server that never degraded answersunknown_toolas today. - Postgres: unchanged. A Postgres connect failure on
--httpkeeps the degraded-engine path (cli.ts:2622-2649); status mode applies only to the reasonspreConnectStatusReason/statusReasonForErrorreturn (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-fastto exit instead". - The thin client surfaces the status:
src/core/mcp-client.tsandsrc/core/remote-mcp-probe.tsread a 503serve_status_onlyenvelope from OAuth discovery,/tokenand/mcpand 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-Authenticateresource metadata and can complete OAuth;docs/mcp/DEPLOY.mdsays to reconnect. - One name: readiness/doctor reuse
serve_status_onlywithtransport: 'http'(no separate reason code). - Copy-paste docs:
curl -i localhost:<port>/healthwith the 503 body andRetry-After,--fail-fast, the marker.
- A human stderr banner in HTTP status mode: the reason, the fix, "re-checking every 5 s; Ctrl-C to stop;
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/paramUseso MCP and CLI each see their own syntax.dispatch.ts:854(registration-trustpermission_denied) gets ahostFixnaming 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.tsvis deleted at 0, so the rule becomes zero-tolerance (check-agent-contract.ts:10). One new ruledefaulted-suggestion: a function declaration, function expression or arrow function with a parameter namedsuggestionthat has a default value, whose body calls one ofopError,new OperationError,usageError,invalidParam,hostOnlyError, fails. Known hits today:administration.ts:22andeval-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-codeenforces registration). - DX amendment (Phase 2.5, both voices): a zero-hit scanner rule
generic-suggestionrejects 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 passdocs: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_authorizationat implementation time), Postgres and PGLite:minion_jobs.spend_authorization JSONBandminion_jobs.spend_claim_token BIGINT(per-acquisition fence, see DX amendments);mcp_spend_reservations.budget_key TEXTandmcp_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-NULLspend_authorizationunlessNEW.spend_claim_token = NEW.claim_generation; - no backfill: a new worker treats a claimed row with name
subagent/enrich, NULLspend_authorizationand an idempotency key startingbook-mirror:,enrich:orcli:enrich:(book-mirror.ts:452, multi-sourceenrich.ts:880, single-sourcemaybeBackgroundcli-options.ts:471) aslegacy_defaultand writes that record in its claim UPDATE (Eng amendments). This covers pre-upgrade rows and rows an old producer inserts after the upgrade; rows alreadyactiveat upgrade finish under the rules they started with. Other rows are untouched. src/schema.sqland 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 onenrich) storescap_usd: null; its jobs reserve nothing and spend is still ledgered. Built byjobSpendAuthorization(auth | { uncapped: true, via: 'max_usd' }, { command, est_usd, of }). Set only through a new trustedMinionQueue.addoptionspendAuthorization(besideallowProtectedSubmit,queue.ts:46); never read from jobdata(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 withbudgetKey: 'group:<group_id>'and alifetimewindow (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_lockon 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/defaultcap a call with no price warns (BUDGET_TRACKER_NO_PRICING) and runs unmetered (the "new models must still run" rule); under ausercap it blocks with theno_pricingfix (look up the rate,gbrain pricing set, retry).pricingOverridesload through the same factory. - Worker enforcement: one wrapper
runWithJobSpend(engine, job, ctx, fn)inspend-authorization.ts, called at both handler seams (worker.ts:1528,run-child.ts:166) in place of the bare handler call, soworker.ts(1764/1764 ceiling) andexecuteJobgrow by at most one line (ceiling bumped with a rationale only if needed). For anauthorized/legacy_defaultrow it runs the handler underwithAIInvocationGuard(src/core/ai/invocation-guard.ts), the seamwithDelegatedSpendalready uses (delegated-spend.ts:42-60): every provider attempt that goes throughinvokeAI(gateway chat/embed/rerank/multimodal, the legacy Anthropic subagent path,subagent.ts:560) reserves its maximum liability (maximumInvocationCents) againstgroup:<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).BudgetTrackerstays synchronous and unchanged; handlers keep their own trackers for their in-process caps. NULL rows run exactly as today. - Exhaustion is terminal:
runWithJobSpendcatches a group reservation refused on settled spend (pressure from live holds is a renewable wait; see amendments) from any handler and rethrowsUnrecoverableError(dead, no retry) withderived_cap_exhausted(cap_source: derived) orcost_cap_exceeded(user/default;no_pricingkeeps 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-usdinserts a fresh group (the idempotency key is released fordeadrows,idempotency-coalesce.ts). Underctx.spendthe enrich handler rethrows its caught exhaustion (handlers/enrich.ts:8-12completes withresult.budget_exhaustedtoday). - Callers:
book-mirrorpassesauthwithof: N;enrich --backgroundmoves the consent gate before submission (single- and multi-source, estimate over all sources) and passesof: sources;maybeBackground(cli-options.ts:476) gains aspendAuthorizationoption it forwards toqueue.add.--dry-runqueues nothing and needs no consent.--max-usd offis itself the user's explicit authorization (as inline today,enrich.ts:1016) and storesuncapped: true. This consent fix is the PR's first commit (CEO dual-voice D5). - Coalesce: a resubmission that coalesces onto a row whose
spend_authorizationis NULL orlegacy_defaultsets the new authorization with a CAS on the old value (taking effect at that row's next claim if it isactive); anauthorizedrow 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 getshows the same. - Saying so [X5]: one structured
job_spend_basislog line per claimed paid job (job_id,name,basis:authorized | legacy_default | unrecorded,cap_usd,cap_source, group spent/remaining);unrecordedsays plainly that no submit-time authorization exists and names the producer's own budget where one is known.gbrain jobs get --jsongainsspend_authorization,spend_basisand awhyper basis. - DX/outside amendments (Phase 2.5):
- Per-acquisition fence: the trigger requires
NEW.spend_claim_token = NEW.claim_generationon every claim of a spend-authorized row; new workers' claim SQL setsspend_claim_token = claim_generation + 1in the same UPDATE (queue.ts:~1458). An old worker incrementsclaim_generationwithout 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 alreadyactiveat 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 ≤ capbutcommitted + pending + est > cap) is a renewable wait (job delayed with backoff, likeRateLeaseUnavailableError), 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_pricingexhaustion keeps its code and pricing fix; only cost exhaustion maps toderived_cap_exhausted/cost_cap_exceeded. - Honest disclosure: the consent preview, the submit summary and
jobs getsay when a derived/default cap cannot meter an unpriced model. - Group controls:
gbrain jobs list --group <id> --json(spent, reserved, remaining, member jobs) andgbrain jobs cancel --group <id>; coalesce and exhaustion messages print these group commands. - Rerun semantics: a rerun with a new
--max-usdauthorizes 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 --backgroundexit-3 payload carries the estimate and a ready--yes --max-usd <derived>argv (consent machinery'sfix), so a cron owner copies one line.
- Per-acquisition fence: the trigger requires
- Doctor [X6]: the existing
legacy-job-authoritycheck 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 fixgbrain jobs list --status waiting --jsonand 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-timelegacy_defaultapplies only to NULL rows with the three key prefixes (includingcli:enrich:); coalesce CAS;jobs getper basis; alegacy_defaultsubagent runs under the $5defaultcap and logsjob_spend_basis. test/minions/budget-meter.test.ts(the durable meter's suite;test/budget-meter.test.tsis the cycle meter) + newtest/e2e/budget-meter-group.test.ts(Postgres E2E lane, picked up byrun-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 underderived/defaultwarns and runs, underuserblocks; 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 samegroup_id.- New
test/enrich-background-consent.test.ts: non-TTYenrich --backgroundwithout--yesexits 3 and queues nothing (single- and multi-source); with--yeseach 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_pageresult of an entity type with no timeline entries; stale chunks: asearch/querywhose vector arm ran and the brain's stale ratio passesrunInitNudge'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 arerunInitNudge's, shared throughcollectOnboardOpportunities. - 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
searchlatency with and without a refresh running), reported in the PR. - In-session preview: an
onboard_*notice's fix isfix.mcp get_health(read-only, same connection) where that op is on the session's surface; the CLI remedy (andgbrain onboard --check) is named inwhywith "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_decisionsmute:NoticeLedger.admithonours mutes forasknotices listed inMUTEABLE_ASK_CODES(onlyfirst_run_decisions);docs/protocol/AGENT_OPERATOR_v1.mdstates the one exception to "ask always shows". The stdio mute fix changes only the lookup tomutedNoticeCodes('stdio')(which unions global mutes).gbrain notices unmute <code>clears the code for every owner audience (global andstdio), so the advertised recovery works after an MCP mute. Test: MCP mute → CLI unmute → fresh stdio process shows the notice.- Under
--access read-onlynotice text does not offermute_notice(it is write-scoped); it names the CLI mute.
Item 2.
- One mutable allow-set per stdio session, shared by the
tools/listhandler and dispatch; test that a widen is visible to both. - Widening can be turned off: config
mcp.allow_session_widen(defaulttrue, 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 serverenv), never a shell profile, so one machine-wide variable does not override deliberate pins.
Item 3.
- Throw-only connect: extract
connectEngineForServe()fromcli.ts'sconnectEngineintosrc/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;connectEnginekeeps 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:httpserver whose request handler is a mutable reference. Recovery builds the full app withbuildServeHttpApp(serve-http.ts:605, already separate from listening) while the status handler keeps answering, then swaps the handler;runServeHttptakes anadoptServeroption thatlistenOrRefusereturns as-is instead of binding (ceiling bump forserve-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 (reasonbrain_unopenable). - Single-flight tick: the HTTP re-probe is a chained
setTimeout(next tick scheduled after the currentreprobesettles) 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 };/healthreturnsinstance(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 andsinceis after the last boot. - Probes:
docs/mcp/DEPLOY.mdsays/healthanswers 503 in status mode (container health checks will restart the container; use--fail-fastthere).gbrain mcp exposeverification reports "status-only" with the reason instead of "failed".
Item 4.
- The
defaulted-suggestionrule also flags an optional or nullish-coalesced suggestion parameter (any name endingsuggestion/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 aderived/defaultcap the guard reserves 0 withestimateKnown: falseand logsBUDGET_TRACKER_NO_PRICING(runs, disclosed as unmetered); under ausercap it refuses withno_pricingand 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_exhaustedand 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) carriescode,fixand the group amounts; the worker maps pressure to delayed and exhaustion/no_pricingto dead;jobs getshows the persisted envelope. - Mixed versions: child readiness (
child-readiness.ts) gains a requiredspend-enforcement-v1feature (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_idandmcp_spend_log.client_idbecome nullable with a CHECK that exactly one ofclient_id/budget_keyis set; admin spend views andspend-log.tsper-client reads filter toclient_id IS NOT NULL; an expression index onminion_jobs ((spend_authorization->>'group_id'))servesjobs list/cancel --group. jobs submitroute [T8, provisional]: CLIgbrain jobs submit enrich|subagentruns the same consent gate (--yes,--max-usd) and stores anauthorizedrecord; theenrich --backgroundexit-3 payload no longer has an unconsented alternative.agent runconsent 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 slowconnectstub 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 pageget_pagegets no timeline notice; an entity page without timeline does; read-only access omitsmute_noticefrom text.test/request-tools-stdio.test.ts: widen visible totools/listand dispatch;mcp.allow_session_widen=falserefuses with the persistent route; audit line written.test/cli-jobs-submit-consent.test.ts: non-TTYjobs submit enrichwithout--yesexits 3 and queues nothing.
Cross-cutting
- Registry: reuse
serve_status_only,derived_cap_exhausted,cost_cap_exceeded; register any new code a site needs; regeneratedocs/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.mdanddocs/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.tsentry), the Deferred list indocs/designs/AGENT_OPERATOR_WAVE.md,llms.txt/llms-full.txtregenerated. - TODOS.md: close the five items and the P3 module-local fail-helpers item; file:
agent runconsent for paid job names (P2; plusjobs submitif 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_SURFACEhonoured by stdioserve, new registrations usestarter,enrich --backgroundasks for consent, queued consent-gated jobs (including pre-upgradebook-mirror/enrichrows, $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) andexecuteJobgrow ≤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 sharedserve --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 arequest_toolswiden 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_authorizationfenced 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:e2elifecycle, thenbun run ci:ubicloudbefore 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 withgraduation_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 insidereprobe/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
fulltostarter: 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 andreprobe, 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-mirrorchapters (claimed aslegacy_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 runand 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 closedONBOARD_CALL_AFFINITYmap (every name exists; every class reachable onverbsandstarter), and passadmitNotices(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 andGBRAIN_NO_ONBOARD_NUDGE=1emit nothing; fix is argv-onlygbrain onboard --check, renderednext: tell_user_to_runwith auser_messageover MCP; HTTP emits none (documented); tests intest/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_decisionsis muteable as the oneaskexception; tested. - Item 1 (taste T4, provisional):
features_auto_fixrides the affinity channel on link ops only,shouldPitchapplied read-only, consentpaidonly 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_toolson stdio widens this session's allowed ops to the requested surface (never past--access read-only, never on HTTP) and sendstools/list_changed; nothing persisted; the hidden-tool hint fix isfix.mcp request_tools {surface:'full'},next: run, with the persistent routes (GBRAIN_SURFACE, plugin setting) and the inherited-env warning inwhy; tests intest/request-tools-stdio.test.tsandtest/hidden-tool-hint.test.ts. - Item 2: stdio
serveresolvesGBRAIN_SURFACE>--surface> config >full; an invalid value is ignored with a stderr line and a once-per-processsurface_env_invalidinfo notice;serve --httpignores the env with a stderr line; tested. - Item 2: never narrow an existing install:
bootstrap hookskeeps a matching entry untouched and carries the existing--surfaceover when it replaces a mismatched entry; no doctor surface check; bootstrap skill starter gaps enumerated before implementation and noted (noSTARTER_OPSchange). - Item 3: one entry point
runStatusModeServeand onereprobe(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;--httpeligible 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):
/health503 + Retry-After,/mcpwith onlygbrain_status, 503 envelope on OAuth/admin routes; allowlisted path-free payload, http-rendered fixes; on non-loopback bindsreasoncollapses tounavailable; exits vialistenOrRefuse(serve_port_in_use) on a taken port; markerGBRAIN_HOME/serve-http-status.json, live by PID (+/health503 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) withstatus: recovered;serve_status_mode_enter/_recoveredlog 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
opErrorwith a filled suggestion and, wherever a next step exists, a filledfix(B10; receipt fixes only for CLI principals); op-handler parameter refusals viainvalidParam/paramUse; CLI-argument funnelsinvalid(message, suggestion); coded funnelsfail(code, message, suggestion, opts?);administration.tsandeval-gate.ts:464lose their defaults;dispatch.ts:854gets a hostFix; baseline file deleted; zero-hitdefaulted-suggestionrule (function/arrow declarations callingopError,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 filledfix. - Item 5: producer table governs basis: book-mirror and enrich --background store
authorizedwith onegroup_id; their pre-upgrade queued rows (statuses waiting, delayed, paused, waiting-children, active; key prefixesbook-mirror:,enrich:,cli:enrich:) are stampedlegacy_defaultunder the job-type cap else $5 default; every other producer stays NULL, reported as basisunrecorded. - Item 5 (taste T3 revised, CEO dual-voice D2): a group's jobs share the approved total through
budget-meter.tsgeneralized with agroup:<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;runWithJobSpendat both seams installs one tracker with async reserve/settle hooks; enrich receives the wrapper's tracker; exhaustion or a refused reservation is terminal (dead) withderived_cap_exhausted/cost_cap_exceeded, group spent/reserved/remaining and the resume command. - Item 5: migration adds
spend_authorization,claim_protocol, meterbudget_keycolumns and a trigger refusing old-protocol claims of spend-authorized rows (CEO dual-voice D4); strict parser; trustedMinionQueue.addoption only;uncappedrecords reserve nothing. - Item 5:
enrich --backgroundgates consent before queueing (first commit of the PR; exit 3, nothing queued without authorization;--dry-runexempt;--max-usd offstoresuncapped);maybeBackgroundforwardsspendAuthorization; coalesce CAS onto NULL/legacy rows (active rows at next claim), authorized rows keep their record with a printed line;job_spend_basislog line andjobs getfields; 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_toolswidening, 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 forrecall.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_generationcheck (notclaim_protocol); readiness/doctor useserve_status_onlywithtransport: 'http'(nothttp_serve_status_only);mute_noticejoinsSTARTER_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) withonboard --checkas preview; stdio mute bug fixed (dispatch reads thestdioaudience) and tested across a fresh process; first-run MCP-rendered fixes tested; doctor/onboard --checklist muted open decisions with the unmute command. - Item 2: hint is surface/access-aware (
request_toolsonly when callable, else persistent routetell_user_to_run); stdio widen returnspersisted:false, scope:'session'and the new ops' schemas, transport-neutral descriptions; surface provenance on startup,whoami,gbrain_status;--surfaceonbootstrap hooksand 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.tsrender 503serve_status_onlyenvelopes from discovery/token/mcp (tests: cold creds, expired creds, recovery); post-recovery 401 +WWW-Authenticatere-auth tested and documented;curl -i /healthtranscript. - Item 4: zero-hit
generic-suggestiondenylist 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_pricingkeeps its code and fix; unmetered-unpriced disclosure in preview, submit summary andjobs get;gbrain jobs list --groupandjobs cancel --group; rerun semantics + structured submit summary (test: mixed completed/active/dead fan-out); post-upgrade line forlegacy_defaultrows; enrich exit-3 payload carries the estimate and a--yes --max-usdfix; 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
withAIInvocationGuardper provider attempt (max-liability hold ongroup:<id>, exact settle) instead of asyncBudgetTrackerhooks or passing the wrapper's tracker to enrich;legacy_defaultis 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 collapsesreason(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
runInitNudgethresholds; PGLite refresh idle-gated, latency measured on a 100k-chunk brain; in-session previewfix.mcp get_health, CLI remedy timing stated;MUTEABLE_ASK_CODESexception forfirst_run_decisionsdocumented in AGENT_OPERATOR_v1; stdio mute usesmutedNoticeCodes('stdio');gbrain notices unmuteclears every owner audience (test MCP mute → CLI unmute → fresh process); read-only text omitsmute_notice. - Item 2: one mutable per-session allow-set shared by tools/list and dispatch (tested);
mcp.allow_session_widen(default true) withsurface_widenedaudit line; hint's persistent route names the per-server env block. - Item 3:
connectEngineForServethrow-only connect insrc/core/engine-connect.tswith partial-start cleanup, used by both status call sites;runServeHttp({ adoptServer })+ handler swap afterbuildServeHttpApp, failed build keeps the status handler and releases the lock; single-flight chained 5 s tick, shutdown serialized with recovery; markerserve-http-status-<port>.jsonwith instance nonce returned by/health; DEPLOY note on 503 health probes;mcp exposereports 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-v1child readiness feature (new parent + old child test); nullableclient_idwith one-key CHECK, admin/spend reads filtered,group_idexpression index; Postgres group test intest/e2e/budget-meter-group.test.tsandtest/minions/budget-meter.test.tsextended; 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 refusesno_pricing. - Item 5 (taste T8, provisional): CLI
gbrain jobs submit enrich|subagentruns the consent gate and stores anauthorizedrecord (testtest/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 artifactuser-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_progressduring 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.