Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(serve): pool-size floor guidance and a boot-deadline line that names the stuck phase (#5205)

garrytan023c8bb9b2a8
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 10c749b79f..e7355d3555 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -516,7 +516,7 @@ names — reasons may be added, never renamed or removed). All 16:
| `permission_denied` | 28000/42501 — the role lacks a GRANT or hits RLS |
| `tenant_not_found` | Supavisor rejected the tenant — pooler usernames are `postgres.<project-ref>`; also raised by paused projects |
| `ssl_required` | the server demands SSL — `?sslmode=require` rewrite (rewrite tier) |
-| `pool_exhausted` | 53300 / session-slot exhaustion — `export GBRAIN_POOL_SIZE=2` guidance |
+| `pool_exhausted` | 53300 / session-slot exhaustion — [pool sizing](#pool-sizing) guidance: `export GBRAIN_POOL_SIZE=6` per long-running process, fewer processes |
| `conn_refused` | ECONNREFUSED — docker-start arm for gbrain's own container; pooler rewrite for Supabase direct URLs |
| `dns_failed` | ENOTFOUND/EAI_AGAIN — one bounded retry; persistent + Supabase suggests a paused project |
| `network_unreachable` | ENETUNREACH/ETIMEDOUT — often an IPv6-only direct host; session-pooler rewrite |
@@ -550,6 +550,42 @@ keep die-on-startup (that lane's repair is `gbrain pglite-repair`), and
mid-session outages ride the engine's own reconnect plus the per-call
classified envelopes.
+### Pool sizing
+
+<a id="pool-sizing"></a>Each gbrain process opens its own ordinary pool of
+`GBRAIN_POOL_SIZE` connections (default 10; environment variable only, no
+config key). A long-running process (`gbrain serve`, `gbrain autopilot`,
+`gbrain jobs work`) needs at least **6**: two for write publication, one for the
+idle work probe, one each for the projection and effects workers, and one for
+reads and tool calls. Below that, boot or projection draining stalls under
+traffic. One-shot CLI commands can use `GBRAIN_POOL_SIZE=2`.
+
+Size the pooler for every process at once:
+
+```
+long-running processes x GBRAIN_POOL_SIZE
+ + processes with GBRAIN_DIRECT_DATABASE_URL x GBRAIN_DIRECT_POOL_SIZE (default 3)
+ + one-shot commands running at the same time x their pool
+ <= the pooler's client limit (Supabase Supavisor: the project's pool_size)
+```
+
+When the sum does not fit, run fewer long-running processes (for example one
+shared `gbrain serve --http` instead of one stdio `serve` per agent session),
+or raise the pooler's limit. Do not lower a long-running process below 6.
+`pool_exhausted` errors (SQLSTATE `53300`) and the
+[serve boot timeout](#serve-boot-timeout) print this guidance.
+
+<a id="serve-boot-timeout"></a>**`serve_boot_timeout`** (stderr, exit 1).
+`gbrain serve` did not finish booting within `GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`
+(default 60; 0 disables), so it released the database and exited. The line
+names the boot phase that never finished (`source_preflight`,
+`writeback_config`, `mcp_connect`, `source_scope`, `persistence_consumer`,
+`resolve_ipc_bind`, `startup_sweep`) and the pool pressure
+(`pool=<tracked checkouts>/<pool max>`). When the pool is below 6 or saturated,
+the fix is `export GBRAIN_POOL_SIZE=6` plus pooler sizing as above; otherwise
+check the configured provider endpoints for the named phase, or raise the
+timeout.
+
### Pool and transaction diagnostics
These warn lines and errors come from the Postgres engine's connection pools.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 1fcd86c18a..c1700c5530 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -52,7 +52,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the registration loop replaces each handler with `withOutputRedaction(op)`, so a `'retrieval'` op's output is redacted on every dispatch path (see `src/core/ops/contract.ts`); the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx, scope?)` is the link-read sibling for `get_links`/`get_backlinks`/`traverse_graph` (`scope` defaults to `sourceScopeOpts(ctx)`; the link ops pass their resolved per-call `federatedSearchScope`): a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
- `src/core/ops/contract.ts` — the shared operation types (`Operation`, `OperationContext`, `ParamDef`, `OperationError`). `Operation.outputRedaction: OutputRedactionPolicy` is REQUIRED, so typecheck forces every op to say how its response treats stored text: `'retrieval'` (the whole response passes `redactRetrievalOutput`, uncapped, assignment rule on), `{ retrieval: { localVerbatim: [...] } }` (same, but the named top-level keys stay raw for the trusted local CLI, `ctx.remote === false`; the memory verbs' `facts`), `{ exempt: reason }` (deliberately raw with a one-line reason: page reads `get_page`/`fetch`/`get_chunks`/`get_raw_data`/`get_versions`, skill-catalog files, admin job ops) or `'no_stored_text'` (returns no page, chunk, fact, take or transcript text). `operations.ts` applies the policy at registration (`withOutputRedaction` in `src/core/search/output-redaction.ts`); `test/retrieval-op-redaction.test.ts` sweeps every classified op with a planted secret.
-- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.
+- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). `RESIDENT_POOL_FLOOR` (6) is the documented minimum `GBRAIN_POOL_SIZE` for a long-running process; `pool_exhausted` recommends it plus fewer processes (docs/ENGINES.md#pool-sizing), and `serve`'s boot-deadline line uses it. Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.
- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). `copyForwardLegacyFile` migrates a legacy layout that placed these files directly under `$GBRAIN_HOME` once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index e7e664a0a8..ca3a7ade31 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -13,7 +13,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 (socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run` via `resolveSocketPathForConfig`; the bound-source posture rejects requests naming any other source) 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 listener (another serve) returns the null binding (that serve is the IPC provider). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.
-- `src/mcp/server.ts` — MCP stdio server (generated from operations). 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`.
+- `src/mcp/server.ts` — MCP stdio server (generated from operations). `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`.
- `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/db-repair.ts b/src/commands/db-repair.ts
index bdfef4a286..fca57719cb 100644
--- a/src/commands/db-repair.ts
+++ b/src/commands/db-repair.ts
@@ -518,7 +518,7 @@ function buildPlan(d: PgAccessDiagnosis, tier: 'auto' | 'rewrite' | 'manual', ur
case 'server_starting':
return ['bounded reconnect (3 attempts, backoff)'];
case 'pool_exhausted':
- return ['re-probe on a single connection; emit GBRAIN_POOL_SIZE=2 guidance'];
+ return ['re-probe on a single connection; emit pool-sizing guidance (docs/ENGINES.md#pool-sizing)'];
case 'conn_refused': {
const lines = [];
if (url && isGbrainDockerUrl(url)) {
@@ -645,7 +645,7 @@ async function applyLadder(
case 'pool_exhausted': {
const retry = await deps.probeAccess(engineConfig, 3);
- human.push('guidance: export GBRAIN_POOL_SIZE=2 (recommended for low-cap poolers like Supabase Supavisor)');
+ human.push(`guidance: ${d.remediation}`);
if (retry === null) {
applied('single_connection_reprobe');
report.fixed = true;
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 1b9a6eed95..c50cd381d9 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -3,6 +3,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { isEngineDegraded as isEngineDegradedForServe } from '../core/degraded-marker.ts';
import { startMcpServer, stdioRpcsInFlightCount, resolveMcpStdioSourceScope } from '../mcp/server.ts';
import { VERB_NAMES } from '../core/verbs.ts';
+import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';
import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
import {
installLoopStallWatchdog,
@@ -77,7 +78,7 @@ export interface ServeOptions {
// (which unconditionally attaches a 'data' listener to real
// process.stdin and would pollute the test runner's stdin handle).
// Defaults to the real implementation when omitted.
- startMcpServer?: (engine: BrainEngine, opts?: { surface?: 'verbs' | 'starter' | 'full'; sourceGuard?: boolean }) => Promise<void>;
+ startMcpServer?: (engine: BrainEngine, opts?: { surface?: 'verbs' | 'starter' | 'full'; sourceGuard?: boolean; onBootPhase?: (phase: string) => void }) => Promise<void>;
// Test seam for the parent-process watchdog. The default
// (`readLiveParentPid`) reads the live kernel PPID via `ps` on POSIX
// because `process.ppid` is captured at process creation and does not
@@ -346,13 +347,12 @@ export async function runServe(
// us either.
const bootTimeoutMs = opts.bootTimeoutMs ?? resolveBootTimeoutMs();
let bootDeadline: ReturnType<typeof setTimeout> | null = null;
+ let bootPhase = 'starting';
if (bootTimeoutMs > 0) {
const log = opts.log ?? ((msg: string) => console.error(msg));
const exit = opts.exit ?? ((code?: number) => { process.exit(code); });
bootDeadline = setTimeout(() => {
- log(
- `GBrain MCP server: boot did not complete within ${bootTimeoutMs}ms — releasing DB lock and exiting so other consumers unblock (check configured provider endpoints; tune via GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS, 0 disables)`,
- );
+ log(formatBootTimeout(bootTimeoutMs, bootPhase, engine));
const cleanup = setTimeout(() => { exit(1); }, CLEANUP_DEADLINE_MS);
cleanup.unref?.();
Promise.resolve()
@@ -370,7 +370,7 @@ export async function runServe(
}
try {
- await start(engine, { surface, ...(sourceGuard ? { sourceGuard } : {}) });
+ await start(engine, { surface, ...(sourceGuard ? { sourceGuard } : {}), onBootPhase: phase => { bootPhase = phase; } });
// `--stdio-idle-timeout` arms its timer during lifecycle installation,
// but its stdin activity listener must wait until startMcpServer has
// attached the MCP SDK transport listener. Attaching any `data` listener
@@ -408,6 +408,26 @@ function resolveEofDrainMs(): number {
return Math.floor(n);
}
+/**
+ * #5205: the boot-deadline line names the boot phase that never finished and
+ * the engine's pool pressure, so a pool below the resident floor reads as a
+ * pool problem instead of a provider-endpoint one.
+ */
+function formatBootTimeout(timeoutMs: number, phase: string, engine: BrainEngine): string {
+ let pool: { tracked: Record<string, number>; poolMax: number | null } | null = null;
+ try { pool = (engine as { getPoolDiagnostics?: () => typeof pool }).getPoolDiagnostics?.() ?? null; } catch { /* diagnostic only */ }
+ const inFlight = pool ? Object.values(pool.tracked).reduce((sum, n) => sum + n, 0) : 0;
+ const max = pool?.poolMax ?? null;
+ const starved = max !== null && (max < RESIDENT_POOL_FLOOR || inFlight >= max);
+ const poolText = max === null ? '' : ` pool=${inFlight}/${max} tracked checkouts${max < RESIDENT_POOL_FLOOR ? ` (below the resident floor of ${RESIDENT_POOL_FLOOR})` : ''}`;
+ const fix = starved
+ ? `export GBRAIN_POOL_SIZE=${RESIDENT_POOL_FLOOR} (and size the pooler for every resident process)`
+ : 'check configured provider endpoints, or export GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS=<seconds> (0 disables)';
+ return `GBrain MCP server: boot did not complete within ${timeoutMs}ms — releasing DB lock and exiting so other consumers unblock. `
+ + `code=serve_boot_timeout phase=${phase}${poolText}; cause: ${starved ? 'the connection pool is too small or saturated for a resident serve' : `boot stalled in ${phase}`}; `
+ + `fix: ${fix}; docs: docs/ENGINES.md#serve-boot-timeout`;
+}
+
// Env resolution for the boot deadline. Lenient (warn + default) rather
// than throw: this is an incident-time escape hatch, and a typo'd env var
// must not turn a boot-safety net into a boot failure of its own.
diff --git a/src/core/pg-access-classify.ts b/src/core/pg-access-classify.ts
index 2566a7f7b6..c0b245fb66 100644
--- a/src/core/pg-access-classify.ts
+++ b/src/core/pg-access-classify.ts
@@ -121,6 +121,17 @@ export interface PgAccessDiagnosis {
export const DB_ACCESS_MARKER_PREFIX = 'GBRAIN_DB_ACCESS';
+/**
+ * #5205: the smallest GBRAIN_POOL_SIZE a long-running gbrain process (serve,
+ * autopilot, jobs work) needs: two publication long-holds, the idle probe lane,
+ * the projection and effects workers, and one connection for reads and tool
+ * calls. Below it, boot or projections stall under traffic. Pooler budget:
+ * processes x pool size (+ GBRAIN_DIRECT_POOL_SIZE per process with a direct
+ * route) must fit the pooler's client limit; run fewer processes rather than
+ * shrinking the pool. Documented in docs/ENGINES.md#pool-sizing.
+ */
+export const RESIDENT_POOL_FLOOR = 6;
+
/**
* The one emission-policy gate for stderr markers (agents read non-TTY
* stderr; humans on a TTY get the prose instead; GBRAIN_FORCE_DB_MARKER=1
@@ -222,8 +233,8 @@ const REASON_ROWS: ReadonlyArray<ReasonRow> = [
transient: true,
codes: ['53300'],
patterns: [/EMAXCONNSESSION/i, /too many clients already/i, /max.*clients?.*in session mode/i, /remaining connection slots are reserved/i],
- remediation: 'Connection slots are exhausted. Lower the pool: export GBRAIN_POOL_SIZE=2 (recommended for low-cap poolers like Supabase Supavisor).',
- fix: { kind: 'set_env', name: 'GBRAIN_POOL_SIZE', value: '2', why: 'low-cap poolers exhaust session slots under the default pool of 10' },
+ remediation: 'Connection slots are exhausted: the pooler client limit is below the sum of every gbrain process\'s pool. Keep each long-running process (serve, autopilot, jobs work) at export GBRAIN_POOL_SIZE=6 or more and run fewer of them (share one gbrain serve --http), or raise the pooler limit; one-shot CLI commands may use GBRAIN_POOL_SIZE=2. See docs/ENGINES.md#pool-sizing.',
+ fix: { kind: 'set_env', name: 'GBRAIN_POOL_SIZE', value: '6', why: 'the floor for a long-running process; when processes x 6 exceeds the pooler limit, run fewer processes instead of going lower' },
},
{
reason: 'server_starting',
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 48f8c5ee2f..8274c8fb48 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -196,10 +196,12 @@ export async function trackStdioRpc<T>(work: () => Promise<T>): Promise<T> {
}
}
-export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean } = {}) {
+export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean; onBootPhase?: (phase: string) => void } = {}) {
const config = loadConfig();
+ const bootPhase = (phase: string) => { try { opts.onBootPhase?.(phase); } catch { /* diagnostic only */ } };
// Refuse to serve a well-formed GBRAIN_SOURCE that no active source row
// backs (see source-preflight.ts). Throws before any transport is attached.
+ bootPhase('source_preflight');
await assertStdioSourceBindable(engine);
// MEMORY_VERBS v1 surface mode: 'full' (default — every op, byte-identical
// to pre-surface behavior), 'starter' (WP4 daily-driver set), or 'verbs'
@@ -225,6 +227,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// private brain. Read failure here yields the OFF bundle — no section,
// never a wrong posture — and the engine is already connected by the time
// serve reaches this call.
+ bootPhase('writeback_config');
const writeback = await resolveWritebackConfig(engine, config);
const server = new Server(
{ name: 'gbrain', version: VERSION },
@@ -357,6 +360,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
}));
const transport = new StdioServerTransport();
+ bootPhase('mcp_connect');
await server.connect(transport);
// Engine-dependent boot: the resolve-IPC listener, session-cursor GC, and
@@ -371,11 +375,12 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// (+ delegated sync/sweep) IPC listener. Wiring shared with `serve --http`
// via bindResolveIpcForServe (#4474) — best-effort; failure to bind never
// blocks the MCP server.
- ipcBinding = await bindResolveIpcForServe(
- engine,
- (await resolveMcpStdioSourceScope(engine)).sourceId,
- await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind }),
- );
+ bootPhase('source_scope');
+ const { sourceId: ipcSourceId } = await resolveMcpStdioSourceScope(engine);
+ bootPhase('persistence_consumer');
+ const persistence = await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind });
+ bootPhase('resolve_ipc_bind');
+ ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence);
// v0.45.7 ambient recall: age out stale session cursors once per serve boot
// (7-day TTL, indexed DELETE). Best-effort — GC failure never blocks serve.
@@ -388,6 +393,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// connect, unref'd (can never hold the process open), all errors
// swallowed inside armStartupSweep. Kill switch: GBRAIN_SWEEP=0 (checked
// inside the helper). Lazy import keeps sweep code off the boot path.
+ bootPhase('startup_sweep');
try {
const { armStartupSweep } = await import('../core/sweep.ts');
const { sourceId } = await resolveMcpStdioSourceScope(engine);
diff --git a/test/pool-diagnostics-fix-commands.test.ts b/test/pool-diagnostics-fix-commands.test.ts
new file mode 100644
index 0000000000..79817af5f9
--- /dev/null
+++ b/test/pool-diagnostics-fix-commands.test.ts
@@ -0,0 +1,56 @@
+/**
+ * O-DX-2 for fix wave 8 lane A: every new or changed Postgres pool warn line,
+ * error and remediation names a stable code and a literal fix command, and
+ * that command must exist. A typo'd or renamed command would send an operator
+ * to a dead end in the middle of an incident.
+ *
+ * Covers pg_connection_poisoned (#5730), backfill_rollback_failed (#5730),
+ * the persistence consumer line (#5233) and the pool_exhausted remediation
+ * (#5205). The serve boot-deadline line is pinned in
+ * test/serve-stdio-lifecycle.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { formatPoisonedDiscardWarning } from '../src/core/pool-gauge.ts';
+import { BackfillRollbackError } from '../src/core/backfill-base.ts';
+import { RESIDENT_POOL_FLOOR, classifyPgAccessError } from '../src/core/pg-access-classify.ts';
+
+function assertCommandExists(command: string): void {
+ const words = command.trim().split(/\s+/);
+ expect(words[0]).toBe('gbrain');
+ const name = words[1]!;
+ expect(CLI_FLAG_REGISTRY[name], `gbrain ${name} is not a CLI command`).toBeDefined();
+ for (const flag of words.filter(word => word.startsWith('--'))) {
+ expect(CLI_FLAG_REGISTRY[name], `gbrain ${name} has no ${flag}`).toContain(flag);
+ }
+}
+
+describe('lane A fix commands', () => {
+ test('pg_connection_poisoned names its code, status byte, fix and docs anchor', () => {
+ const line = formatPoisonedDiscardWarning('read', 'E');
+ expect(line).toContain('code=pg_connection_poisoned status=E pool=read');
+ expect(line).toContain('docs=docs/ENGINES.md#pg-connection-poisoned');
+ assertCommandExists(/fix="([^"]+)"/.exec(line)![1]!);
+ expect(formatPoisonedDiscardWarning('direct', '\n')).toContain('status=?');
+ });
+
+ test('backfill_rollback_failed names a resumable fix command', () => {
+ const error = new BackfillRollbackError('effective_date', new Error('batch'), new Error('rollback'));
+ expect(error.code).toBe('backfill_rollback_failed');
+ expect(error.docs_url).toBe('docs/ENGINES.md#backfill-rollback-failed');
+ assertCommandExists(error.fix.replace('effective_date', ''));
+ });
+
+ test('the persistence consumer line points at an existing writer status command', () => {
+ assertCommandExists('gbrain sources writer status --json');
+ });
+
+ test('pool_exhausted recommends the resident floor, not a pool of 2', () => {
+ const diagnosis = classifyPgAccessError(Object.assign(new Error('max clients reached in session mode'), { code: '53300' }));
+ expect(diagnosis.reason).toBe('pool_exhausted');
+ expect(diagnosis.fix).toEqual(expect.objectContaining({ kind: 'set_env', name: 'GBRAIN_POOL_SIZE', value: String(RESIDENT_POOL_FLOOR) }));
+ expect(diagnosis.remediation).toContain(`GBRAIN_POOL_SIZE=${RESIDENT_POOL_FLOOR}`);
+ expect(diagnosis.remediation).toContain('docs/ENGINES.md#pool-sizing');
+ assertCommandExists('gbrain serve --http');
+ });
+});
diff --git a/test/serve-stdio-lifecycle.test.ts b/test/serve-stdio-lifecycle.test.ts
index 2db6a78d50..792a0f3812 100644
--- a/test/serve-stdio-lifecycle.test.ts
+++ b/test/serve-stdio-lifecycle.test.ts
@@ -645,6 +645,43 @@ describe('boot-readiness deadline (#3273)', () => {
expect(h.logs.some(l => l.includes('boot did not complete'))).toBe(false);
});
+ // #5205: the deadline line used to blame provider endpoints even when the
+ // boot was starved by a pool below what a resident serve needs.
+ test('names the stuck boot phase and a pool below the resident floor', async () => {
+ const h = makeHarness();
+ Object.assign(h.engine, { getPoolDiagnostics: () => ({ tracked: { raw: 0, direct: 0, reserved: 1, tx: 1 }, poolMax: 2, poisonedDiscards: 0 }) });
+ h.opts.startMcpServer = (_engine, startOpts) => {
+ startOpts?.onBootPhase?.('persistence_consumer');
+ return new Promise<void>(() => {});
+ };
+ h.opts.bootTimeoutMs = 20;
+ void runServe(h.engine as unknown as BrainEngine, [], h.opts);
+
+ expect(await h.exited).toBe(1);
+ const line = h.logs.find(l => l.includes('boot did not complete'))!;
+ expect(line).toContain('code=serve_boot_timeout phase=persistence_consumer pool=2/2 tracked checkouts (below the resident floor of 6)');
+ expect(line).toContain('fix: export GBRAIN_POOL_SIZE=6');
+ expect(line).toContain('docs: docs/ENGINES.md#serve-boot-timeout');
+ expect(line).not.toContain('provider endpoints');
+ });
+
+ test('a stall with pool headroom points at the phase, not the pool', async () => {
+ const h = makeHarness();
+ Object.assign(h.engine, { getPoolDiagnostics: () => ({ tracked: { raw: 0, direct: 0, reserved: 0, tx: 0 }, poolMax: 10, poisonedDiscards: 0 }) });
+ h.opts.startMcpServer = (_engine, startOpts) => {
+ startOpts?.onBootPhase?.('startup_sweep');
+ return new Promise<void>(() => {});
+ };
+ h.opts.bootTimeoutMs = 20;
+ void runServe(h.engine as unknown as BrainEngine, [], h.opts);
+
+ expect(await h.exited).toBe(1);
+ const line = h.logs.find(l => l.includes('boot did not complete'))!;
+ expect(line).toContain('phase=startup_sweep pool=0/10 tracked checkouts;');
+ expect(line).toContain('cause: boot stalled in startup_sweep');
+ expect(line).toContain('GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS');
+ });
+
test('bootTimeoutMs = 0 disables the deadline', async () => {
const h = makeHarness();
let resolveBoot!: () => void;