Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes (lean IPC option name, KEY_FILES for the lean serve, interrupted wording, = form idle-sweep row)
garrytanf91a9be53afd
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex eb6dfe99ae..74f4f6a995 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. OAuth discovery's `scopes_supported` (RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes from `scopesSupportedForDiscovery({ enableDcr })` in `src/core/scope.ts`: with `--enable-dcr` it is exactly the self-registration ceiling (`read write`), so a client that copies discovery into its `/register` request succeeds; without DCR it is every scope except operator-only `agent`. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and per-IP `express-rate-limit` buckets: the MCP SDK's defaults on `/authorize` (100 / 15 min), `/register` (20 / hour) and `/token` (50 / 15 min) because `authRouterOptions` passes no `rateLimit: false`, the custom `client_credentials` handler's `ccRateLimiter`, and independent owner limits: 60 total authentication requests/min/IP, 10 failed authentications/min/IP (verified authority, independent of response status), and 60 consent requests/min/authenticated session in `serve-http-admin-limits.ts`. Admin no-store, no-referrer and framing headers precede login/link handlers. Explicit pending IDs survive fresh-browser links; invalid or restarted requests require native authorization to restart. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` in `serve-http-registration.ts` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging. DCR startup copy: the SECURITY WARNING states self-registered clients are limited to read/write (read-only for `client_credentials` under `--enable-dcr-insecure`) and that every authorization_code connection needs owner approval in the admin UI; banner `DCR:` values are `enabled (consent; DCR max read write)` / `enabled (INSECURE: read-only M2M)` / `disabled`.Layout: `runServeHttp` binds through `listenOrRefuse` (`serve-http-listen.ts`: `serve_port_in_use` on a taken port; with `options.adoptServer` from status-only recovery it hands the app to the already-bound listener instead of binding). `buildServeHttpApp` builds one shared `ServeHttpContext` (sessions, nonce stores, limiters, `requireAdmin`, SSE fan-out, OAuth provider, resource verifier, non-`localOnly` op list) and mounts in registration order `serve-http-oauth.ts` (CORS gates, DCR TTL hook, confidential credentials, SDK router, discovery, owner login links, consent), `serve-http-metrics.ts` (`/health`, `/metrics`, probes), `serve-http-admin-api.ts` (`requireAdmin`, `/admin/login`, `/admin/api/*`, `/admin/events`), `serve-http-spa.ts`, `serve-http-mcp.ts` (`/mcp`; writes `[gbrain-serve] dispatch op=<name> args_sha256=<16 hex>` to stderr before each tool call so a stall's last line names its request, never the arguments) and `serve-http-webhooks.ts` (`/ingest`, which maps a legacy-authority `permission_denied` from submission to 409 `{error, message, hint, docs_url}` (`test/serve-http-ingest-legacy.test.ts`) and every other submission error to 500, `/webhooks/github`); `runServeHttp` keeps listen, banner, resolve-IPC binding and shutdown, and the façade re-exports moved symbols. Order is pinned by `test/serve-http-route-golden.test.ts` (AST) and `test/serve-http-route-runtime-golden.test.ts` (router stack). Size ceiling: `scripts/module-size-limits.tsv`.-- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. `--http --token-ttl` goes through `parseTokenTtl` (`src/commands/auth.ts`) and refuses anything outside 60 to 7,776,000 seconds before the server starts. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block). #6543: after the pool stall watch, `recordServeTransport` (`src/commands/serve-health.ts`) reads the read pool's transport once (live `prepare`/`max_pipeline` with `max_pipeline_reason`, the doctor probe's `SHOW statement_timeout` and its ALTER ROLE fix when a configured timeout reads 0, `application_name` when Supavisor), logs one `[gbrain serve] transport` line and caches it for `/health?deep=1` (never re-read per probe). `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (>= 120, else `invalid_params` at start) arms `installRestartRequiredExit`: an in-process `restart_required` held continuously for n seconds (the hold resets when it clears) disconnects under a 5 s deadline and exits `SERVE_UNHEALTHY_EXIT_CODE` (69, `serve_unhealthy_exit`); a durable ledger (`serve-self-exit.json` under the gbrain home) suppresses the exit after 3 within an hour (`serve_self_exit_suppressed`, `self_exit_suppressed` in the deep 503). `probeDeepHealth` (`serve-http-metrics.ts`) answers 503 `persistence_restart_required` before its pooled probe, `pool_inflight_over_budget` or `deep_health_probe_failed` (`reason`), each with `fix`/`docs` from the registry and the cached `transport`, no request ids. Pinned by `test/serve-health-6543.test.ts` (a real `PersistenceConsumer` driven to restart_required).+- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. `--http --token-ttl` goes through `parseTokenTtl` (`src/commands/auth.ts`) and refuses anything outside 60 to 7,776,000 seconds before the server starts. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). #7599: `lean` (`readOnlyServeSkipsResidentDuties`, a read-only stdio serve on Postgres; PGLite keeps both) turns off the idle sweep and `installResidentTickers` (facts drain, movement watch, on-commit head watcher). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block). #6543: after the pool stall watch, `recordServeTransport` (`src/commands/serve-health.ts`) reads the read pool's transport once (live `prepare`/`max_pipeline` with `max_pipeline_reason`, the doctor probe's `SHOW statement_timeout` and its ALTER ROLE fix when a configured timeout reads 0, `application_name` when Supavisor), logs one `[gbrain serve] transport` line and caches it for `/health?deep=1` (never re-read per probe). `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (>= 120, else `invalid_params` at start) arms `installRestartRequiredExit`: an in-process `restart_required` held continuously for n seconds (the hold resets when it clears) disconnects under a 5 s deadline and exits `SERVE_UNHEALTHY_EXIT_CODE` (69, `serve_unhealthy_exit`); a durable ledger (`serve-self-exit.json` under the gbrain home) suppresses the exit after 3 within an hour (`serve_self_exit_suppressed`, `self_exit_suppressed` in the deep 503). `probeDeepHealth` (`serve-http-metrics.ts`) answers 503 `persistence_restart_required` before its pooled probe, `pool_inflight_over_budget` or `deep_health_probe_failed` (`reason`), each with `fix`/`docs` from the registry and the cached `transport`, no request ids. Pinned by `test/serve-health-6543.test.ts` (a real `PersistenceConsumer` driven to restart_required).- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex c9715e6500..8668a59a34 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. `turn_context` and `context_pack` (`context-pack-handler.ts`) read `context.hot_memory.session_only` per request (`readHotMemorySessionOnly`) and pass it as `sessionOnly` to the assembler (pinned by `test/hot-memory-session-only-7026.test.ts`). Pinned by `test/resolve-ipc-binding.test.ts`.-- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`. Each tool call resolves its source inside one request config snapshot that dispatch reuses for a read op (the config table is read alongside the source rows), so the pre-op reads cost one round trip (GBRA-156).+- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep; #7599: a read-only stdio serve on Postgres (`readOnlyServeSkipsResidentDuties`) binds IPC with no delegation kinds (`lean`), starts no consumer, runs no session-cursor GC or startup sweep and writes `READ_ONLY_SERVE_NOTE` to stderr; PGLite keeps all of it) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`. Each tool call resolves its source inside one request config snapshot that dispatch reuses for a read op (the config table is read alongside the source rows), so the pre-op reads cost one round trip (GBRA-156).- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 760cd23080..ef38d1a257 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -281,7 +281,7 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'statecase 'head_blocked': return `Source ${status.source_id} is blocked: its oldest write waits on something only an operator clears.`;case 'recovery_blocked': return `Source ${status.source_id} is blocked: a write's recovery record found changed bytes on disk.`;case 'pass_unfinished': return `Source ${status.source_id} is resumable: the newest sync pass did not finish; the next sync continues it.`;- case 'pass_interrupted': return `Source ${status.source_id} is resumable: the newest sync pass stopped before it ended and no process owns it (killed or crashed); the next sync continues it.`;+ case 'pass_interrupted': return `Source ${status.source_id} is resumable: the newest sync pass stopped before it ended and no process owns it (killed, crashed or stopped by an unrecorded error); the next sync continues it.`;case 'pass_abandoned': return `Source ${status.source_id} is blocked: its sync passes keep stopping before they end; another plain sync will not change that (report what doctor shows).`;case 'not_converged': return `Source ${status.source_id} is resumable: the newest sync pass ran out of rounds before every path settled.`;case 'settle_mismatch': return `Source ${status.source_id} is resumable: a path keeps settling without reading settled; three passes in a row hold it.`;diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsindex 869d8a8098..6cce9efae5 100644--- a/src/core/persistence/sync-pass-status.ts+++ b/src/core/persistence/sync-pass-status.ts@@ -115,7 +115,7 @@ export function passStatusNext(sourceId: string, reason: PassStatusReason, row:return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `The last ${abandonedPasses(row, Date.now(), interrupted)} sync passes of ${sourceId} stopped before they ended (the drain abandoned them for making no progress, or their process was killed), so another plain sync is likely to stop the same way. Report what doctor shows, with the gbrain version and the newest sync run's drain.stall (read-only).` };case 'pass_interrupted':- return { ...sync, why: `The newest pass of ${sourceId} stopped before it ended and no process holds its drain lease: its process was killed or crashed (an out-of-memory kill or a timeout), so nothing recorded a failure. The plain sync continues it from the current level; if that pass stops the same way, status reads pass_abandoned.` };+ return { ...sync, why: `The newest pass of ${sourceId} stopped before it ended and no process holds its drain lease: its process was killed or crashed (an out-of-memory kill or a timeout), or stopped on an error it does not record (a dropped connection), so nothing recorded a failure. The plain sync continues it from the current level; if that pass stops the same way, status reads pass_abandoned.` };case 'selection_scoped':return { ...sync, why: 'The last pass converged at a narrower selection and did not advance last_commit; the plain sync runs the configured selection.' };default:diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsindex 947587c881..eb2bb919fd 100644--- a/src/mcp/resolve-ipc-binding.ts+++ b/src/mcp/resolve-ipc-binding.ts@@ -143,8 +143,8 @@ export async function bindResolveIpcForServe(persistenceProvider?: PersistenceIpcProvider,opts: {rememberCallable?: boolean | (() => boolean);- /** #7599: a read-only stdio serve registers no delegated sync, nudge or sweep kind (clients get the polite refusal). */- readOnly?: boolean;+ /** #7599: a lean serve (a read-only stdio serve on Postgres, `readOnlyServeSkipsResidentDuties`) registers no delegated sync, nudge or sweep kind (clients get the polite refusal); PGLite keeps them. */+ lean?: boolean;/** Delay before each re-bind attempt of a socket this serve does not hold; tests inject a short one. */rebindDelayMs?: () => number;} = {},@@ -193,7 +193,7 @@ export async function bindResolveIpcForServe(// catch would otherwise swallow the error and start NO listener).// Kill switch: GBRAIN_SERVE_SYNC_IPC=0 → the kinds are simply not// registered and clients get 'unsupported_kind' (the polite refusal).- const delegation = process.env.GBRAIN_SERVE_SYNC_IPC !== '0' && !opts.readOnly;+ const delegation = process.env.GBRAIN_SERVE_SYNC_IPC !== '0' && !opts.lean;let syncHandlers: Pick<IpcHandlers, 'sync_start' | 'sync_status' | 'sync_abort' | 'sync_nudge'> = {};if (delegation) {try {diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex fe6f5c30d0..66e4930b0f 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -540,7 +540,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSconst lean = readOnlyServeSkipsResidentDuties(!!session.readOnly, engine.kind);const persistence = lean ? undefined : await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind });bootPhase('resolve_ipc_bind');- ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence, { rememberCallable: () => !session.allowedOps || session.allowedOps.has('remember'), readOnly: lean });+ ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence, { rememberCallable: () => !session.allowedOps || session.allowedOps.has('remember'), lean });import('../core/onboard/mcp-onboarding.ts').then(m => m.startOnboardingRefresher(engine, { idle: () => _stdioRpcsInFlight === 0 })).catch(() => { /* coaching is best-effort */ });if (lean) return void process.stderr.write(READ_ONLY_SERVE_NOTE);diff --git a/test/resolve-ipc-binding.test.ts b/test/resolve-ipc-binding.test.tsindex 8c237bfc70..4e000ed7b3 100644--- a/test/resolve-ipc-binding.test.ts+++ b/test/resolve-ipc-binding.test.ts@@ -103,16 +103,16 @@ describe('bindResolveIpcForServe (#4474)', () => {mkdirSync(join(tmp, '.gbrain'), { recursive: true });writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dataDir }));await withEnv({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined, GBRAIN_SERVE_SYNC_IPC: undefined }, async () => {- for (const readOnly of [true, false]) {- const binding = await bindResolveIpcForServe({} as unknown as BrainEngine, 'default', undefined, { readOnly });+ for (const lean of [true, false]) {+ const binding = await bindResolveIpcForServe({} as unknown as BrainEngine, 'default', undefined, { lean });try {const secret = readIpcSecret(dataDir) ?? '';const sync = await requestSyncStatus(binding.socketPath!, { secret, jobId: 'no-such-job' });const sweep = await requestSweepStatus(binding.socketPath!, { secret, jobId: 'no-such-job' });- const want = readOnly ? 'unsupported_kind' : 'unknown_job';+ const want = lean ? 'unsupported_kind' : 'unknown_job';expect((sync as { error?: string }).error).toBe(want);expect((sweep as { error?: string }).error).toBe(want);- if (!readOnly) continue;+ if (!lean) continue;for (const write of [requestSyncStart, requestSyncAbort, requestSyncNudge, requestSweepStart]) {expect(((await write(binding.socketPath!, { secret } as never)) as { error?: string }).error).toBe('unsupported_kind');}diff --git a/test/serve-idle-sweep-source.serial.test.ts b/test/serve-idle-sweep-source.serial.test.tsindex 5d7719f8eb..ba39a29fd2 100644--- a/test/serve-idle-sweep-source.serial.test.ts+++ b/test/serve-idle-sweep-source.serial.test.ts@@ -112,7 +112,7 @@ describe('serve idle sweep source resolution (#4679)', () => {test('#7599: a read-only serve on Postgres arms no idle sweep; read-write, or on PGLite, it does', async () => {const armed: string[] = [];- for (const [kind, args] of [['postgres', ['--access', 'read-only']], ['postgres', []], ['pglite', ['--access', 'read-only']]] as const) {+ for (const [kind, args] of [['postgres', ['--access', 'read-only']], ['postgres', ['--access=read-only']], ['postgres', []], ['pglite', ['--access', 'read-only']]] as const) {let timers = 0;await withEnv({ GBRAIN_SOURCE: undefined }, () => runServe({ ...makeEngine(['default']), kind } as BrainEngine, [...args], {stdin: new EventEmitter() as never, signals: new EventEmitter() as never, exit: () => {}, log: () => {}, startMcpServer: async () => {},@@ -121,6 +121,6 @@ describe('serve idle sweep source resolution (#4679)', () => {}));armed.push(`${kind} ${args.join(' ') || 'read-write'}: ${timers}`);}- expect(armed).toEqual(['postgres --access read-only: 0', 'postgres read-write: 1', 'pglite --access read-only: 1']);+ expect(armed).toEqual(['postgres --access read-only: 0', 'postgres --access=read-only: 0', 'postgres read-write: 1', 'pglite --access read-only: 1']);}, 20_000);});