Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytande19812fec23
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex aecd999171..05eb1a2f26 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/serve-http-grants.ts` + `admin/src/components/ClientGrant.tsx` — typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes in `serve-http-registration.ts`, `serve-http-grants.ts`, and `serve-http-admin-api.ts` use canonical grant validation and audit; legacy response shapes remain available. Registration and permission-edit failures add safe classifications, stage, outcome and inspection remedies; an unacknowledged mutation stays outcome-unknown, while read/preview failures and known refusals remain failed. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit. `admin/src/pages/Agents.tsx` previews machine/public PKCE/confidential PKCE registration and current permissions, and exposes versioned lifecycle actions. Explicit downloads select machine `HarnessCredentials` or native `OAuthClientSetup`; mixed clients require a flow choice. Loading errors preserve stale rows with Retry and disable creation when required source metadata is missing. Browser downloads and native connection evidence remain distinct. Rebuild committed `admin/dist` and `src/admin-embedded.ts` after SPA edits.-- `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 write source and normalized target slug (hashed) join the queue idempotency key, so a rescoped client or a second slug gets its own capture (`test/serve-http-ingest-write-loss.test.ts`). 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`.+- `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 write source and normalized target slug (hashed) join the queue idempotency key, so a rescoped client or a second slug gets its own capture, and a slug over 1024 bytes gets 400 `invalid_slug` (`test/serve-http-ingest-write-loss.test.ts`). 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`), answers 429 `ingest_backlog_full` when the 50-capture waiting cap hands back another job, and every other submission error to 500; `/webhooks/github`, which HMACs every body, with a throwaway key when there is no source or secret); `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`). #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).diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.tsindex 2c123f05aa..1d82afc9cb 100644--- a/src/commands/serve-http-webhooks.ts+++ b/src/commands/serve-http-webhooks.ts@@ -244,6 +244,9 @@ async function handleGitHubItemEvent(}}+/** A longer slug cannot be stored under the page key index, so its capture would be accepted and never land. */+const MAX_INGEST_SLUG_BYTES = 1024;+/** Stands in for a missing webhook secret; no source holds it and a match against it is still refused. */const THROWAWAY_WEBHOOK_KEY = randomBytes(32);@@ -499,6 +502,14 @@ async function handleIngest(const writer = authInfo.principal ? { principal: { kind: authInfo.principal.kind, id: authInfo.principal.id } } : undefined;let targetSlug = '';if (callerSlug) {+ const slugBytes = Buffer.byteLength(callerSlug, 'utf8');+ if (slugBytes > MAX_INGEST_SLUG_BYTES) {+ res.status(400).json({+ error: 'invalid_slug',+ message: `Invalid slug: X-Gbrain-Slug is ${slugBytes} bytes; the limit is ${MAX_INGEST_SLUG_BYTES}.`,+ });+ return;+ }try {targetSlug = validateSlug(callerSlug);} catch (err) {diff --git a/test/serve-http-ingest-write-loss.test.ts b/test/serve-http-ingest-write-loss.test.tsindex bb414fd299..0b1d4bd95f 100644--- a/test/serve-http-ingest-write-loss.test.ts+++ b/test/serve-http-ingest-write-loss.test.ts@@ -115,11 +115,28 @@ describe('POST /ingest idempotency includes the target slug', () => {expect(await ingest(body, 'notes/inbox-copy')).not.toBe(inbox);});- test('a valid slug of about 3 KB is queued rather than failing the key index, and its retry collapses', async () => {- const body = note('Long-slug capture');- const slug = `notes/${Array.from({ length: 47 }, (_, i) => createHash('sha256').update(String(i)).digest('hex')).join('')}`;- const first = await ingest(body, slug);- expect(await ingest(body, slug)).toBe(first);+ const entropy = Array.from({ length: 47 }, (_, i) => createHash('sha256').update(String(i)).digest('hex')).join('');+ const queuedWith = async (marker: string) =>+ (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs WHERE data::text LIKE $1', [`%${marker}%`]))[0]!.n;++ test('a slug of about 3 KB, which no page can be stored under, is refused with 400 invalid_slug and nothing queued', async () => {+ const res = await post(note('Long-slug capture'), `notes/${entropy}`);+ expect(res.status).toBe(400);+ expect((await res.json() as { error: string }).error).toBe('invalid_slug');+ expect(await queuedWith('Long-slug capture')).toBe(0);+ });++ test('a slug of exactly 1024 bytes is queued, and its retry collapses; 1025 bytes is refused', async () => {+ const atLimit = `notes/${entropy.slice(0, 1024 - 'notes/'.length)}`;+ expect(Buffer.byteLength(atLimit, 'utf8')).toBe(1024);+ const body = note('Slug at the limit');+ const first = await ingest(body, atLimit);+ expect(await ingest(body, atLimit)).toBe(first);++ const over = await post(note('Slug over the limit'), `${atLimit}b`);+ expect(over.status).toBe(400);+ expect((await over.json() as { error: string }).error).toBe('invalid_slug');+ expect(await queuedWith('Slug over the limit')).toBe(0);});});