Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/fix-6543-wedge
garrytanf0ebc056139f
diff --cc docs/ENGINES.mdindex efe9766fcc,ff1c214e92..f23fde012a--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@@ -775,16 -772,9 +775,16 @@@ its error, left the culprit queued witlater reply one statement late until the process restarted (the`null is not an object (evaluating 'query.statement.types')` line and a backendstuck `active / ClientRead` were that desync). The line names the pool and the-statement by first keyword and table; the call site that bound `undefined` is a-gbrain bug, so report the line. `getPoolDiagnostics().buildFailures` counts-them.+statement by first keyword and table, and an `UNDEFINED_VALUE` line names the+parameter (`param=$2`, or `param=?` for an array element). Behind a+transaction-mode pooler (port 6543, `?prepare=false`) a build failure usually+means a misrouted answer: the statement bound a value read from a row that+belonged to another statement, so earlier reads on that pool are suspect too.+Check `/health?deep=1` `transport.max_pipeline` (gbrain sends `0` there since- v0.60.186.0; `PGMAX_PIPELINE=0` forces it) and audit the window with++v0.60.187.0; `PGMAX_PIPELINE=0` forces it) and audit the window with+[the pooler misroute audit](guides/pooler-misroute-audit.md). Elsewhere the+call site that bound `undefined` is a gbrain bug, so report the line.+`getPoolDiagnostics().buildFailures` counts them.<a id="pg-pool-stalled"></a>**`pg_pool_stalled`** (warn, resident processes).`gbrain serve` reads its pool every 30 s; when connections are checked out or@@@ -814,68 -804,6 +814,68 @@@ same pool numbers ride the persistence`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for theowner process.+Every 503 body carries a stable `code` with `fix` and `docs` from the error+registry (#6543):++- `persistence_restart_required`: this serve's persistence consumer reports+ `restart_required` (an abandoned preparation or a publication past its+ deadline), so it claims no write until the process restarts. Restart serve.+- `pool_inflight_over_budget`: a pooled statement has waited past the read+ pool's in-flight budget. Restart serve; behind a transaction-mode pooler read+ `transport` first and set `PGMAX_PIPELINE=0` if `max_pipeline` is not `0`.+ No request id or statement text reaches either body: the endpoint is+ unauthenticated.+- `deep_health_probe_failed` with `reason` `pending`, `timeout` or `error`: the+ pooled `SELECT 1` did not answer. Retry; if it persists, `gbrain doctor --json`.++Both 200 and 503 bodies carry `transport`, read once at startup through the+read pool and logged as a `[gbrain serve] transport` line:+`{ pooler_mode, prepare, max_pipeline, max_pipeline_reason, statement_timeout,+session_timeouts_not_applied, fix?, application_name? }`. `prepare` and+`max_pipeline` are the live pool's options; `max_pipeline_reason` says why+(`transaction_pooler_port`, `url_prepare_false`, `gbrain_prepare_off`,+`url_max_pipeline`, `env_pgmax_pipeline` or `default`): gbrain builds the read+pools with `max_pipeline: 0` for a transaction-mode URL (port 6543 or- `?prepare=false`) or `GBRAIN_PREPARE=0` since v0.60.186.0, and a URL++`?prepare=false`) or `GBRAIN_PREPARE=0` since v0.60.187.0, and a URL+`?max_pipeline=` or a non-empty `PGMAX_PIPELINE` always wins.+PgBouncer in transaction mode carries pipelined statements correctly, so a+PgBouncer deployment on port 6543 or with `?prepare=false` can opt back in with+`?max_pipeline=100`: on a 3-connection pool with 8 concurrent workers at about+40 ms round trip, pipelining off measured about 37% fewer statements per second+(1185 vs 1890 in 30 s); at localhost latency there was no measurable cost. Do+not opt back in behind Supavisor.+`application_name: "Supavisor"` appears when the backend names Supavisor.+`session_timeouts_not_applied: true` means gbrain configured a+`statement_timeout` but it reads `0` through the pool (a transaction-mode+pooler drops startup parameters), so no server-side timeout bounds an+autocommit statement; `fix` is the same `ALTER ROLE` the+doctor's `persistence_session_timeouts` check prints+([troubleshooting](guides/troubleshooting.md#session-timeouts-not-applied)).+The endpoint is unauthenticated, so it only reports: it never retires a+connection or restarts anything.++<a id="serve-unhealthy-exit"></a>To let a supervisor recover a wedged serve+without a human, set `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (off by default;+`n` must be a whole number of at least `120`, and a smaller value refuses to+start with `invalid_params`). When `persistence_restart_required` has held+continuously for `n` seconds (read in-process; the hold restarts whenever the+stuck work settles and the flag clears), serve logs+`[gbrain serve] error code=serve_unhealthy_exit cause=persistence_restart_required`,+disconnects under a 5 s deadline (the consumer's stop waits on the stuck work,+so the exit never depends on it draining) and exits `69`.+`pool_inflight_over_budget` never triggers the exit (the variable is named for+its one trigger): restart serve yourself or from your health check. A loop+guard records each self-exit in `serve-self-exit.json` under the gbrain home;+after 3 self-exits within an hour serve stops exiting, logs+`serve_self_exit_suppressed`, and the deep-health 503 carries+`self_exit_suppressed: true` with a fix that asks for a manual restart and a+look at `gbrain sources writer status --json`.+The service `gbrain mcp expose` installs restarts it (systemd `Restart=always`,+launchd `KeepAlive`), so a fresh serve comes up; the floor keeps a restart loop+under the systemd unit's start limit (10 starts per 300 s). For the installed service put the variable+in `~/.gbrain/env`; for a foreground serve set it in the shell or your own+supervisor's environment. A foreground serve with no supervisor just exits.+<a id="backfill-rollback-failed"></a>**`backfill_rollback_failed`** (error).A `gbrain backfill` batch failed, and its `ROLLBACK` failed too. The run stopsrather than retrying on a connection whose transaction state is unknown; thediff --cc docs/architecture/postgres-cancellation.mdindex 6dd7598f31,6f7178426e..53d268671f--- a/docs/architecture/postgres-cancellation.md+++ b/docs/architecture/postgres-cancellation.md@@@ -28,7 -28,7 +28,7 @@@ Direct PostgreSQL closes the cancellati`test/e2e/persistence-chaos.test.ts` exercises active, queued, delayed and failed cancellation; transaction siblings; stale ownership; atomic reservation settlement; reconnects; completed cursors; and real socket backpressure in both module formats. Its optional PgBouncer case requires `GBRAIN_PGBOUNCER_URL` and `GBRAIN_PGBOUNCER_DIRECT_URL`, uses a dedicated test database, and verifies another client can reuse the same server backend without receiving a late cancellation.- Keep the response-mapping, actual-settlement and unchanged persistence latency checks alongside these protocol tests. Global `max_pipeline: 1`, serializer fallbacks and blind retries are not substitutes for ownership isolation. The one place pipelining is off is transport, not cancellation: since v0.60.186.0 the read pools of a transaction-mode pooler URL (port 6543, `?prepare=false`, `GBRAIN_PREPARE=0`) are built with `max_pipeline: 0`, because a transaction pooler cannot carry pipelined statements across transaction boundaries (#6543; `db.resolveReadPoolPipeline`, the reason is in `/health?deep=1` `transport`). A URL `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins, and the direct pool keeps the driver default.-Keep the response-mapping, actual-settlement and unchanged persistence latency checks alongside these protocol tests. Global `max_pipeline: 1`, serializer fallbacks and blind retries are not substitutes for ownership isolation.++Keep the response-mapping, actual-settlement and unchanged persistence latency checks alongside these protocol tests. Global `max_pipeline: 1`, serializer fallbacks and blind retries are not substitutes for ownership isolation. The one place pipelining is off is transport, not cancellation: since v0.60.187.0 the read pools of a transaction-mode pooler URL (port 6543, `?prepare=false`, `GBRAIN_PREPARE=0`) are built with `max_pipeline: 0`, because a transaction pooler cannot carry pipelined statements across transaction boundaries (#6543; `db.resolveReadPoolPipeline`, the reason is in `/health?deep=1` `transport`). A URL `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins, and the direct pool keeps the driver default.## Worker admission and configuration shutdowndiff --cc docs/guides/pooler-misroute-audit.mdindex c51209698d,0000000000..2ab18b9290mode 100644,000000..100644--- a/docs/guides/pooler-misroute-audit.md+++ b/docs/guides/pooler-misroute-audit.md@@@ -1,77 -1,0 +1,77 @@@+# Pooler misroute audit++A brain whose `gbrain serve` read pool pipelined statements through a+transaction-mode pooler (Supavisor or PgBouncer on port 6543, or a URL with- `?prepare=false`) before v0.60.186.0 could hand a statement another++`?prepare=false`) before v0.60.187.0 could hand a statement another+statement's rows (#6543). Most of the time that failed loudly+(`pg_statement_build_failed` with `error=UNDEFINED_VALUE`, `pg_connection_stuck`),+but a statement that bound a value from someone else's row and succeeded+leaves a persistence row whose identity belongs to another row.+`scripts/audit-pooler-misroute.ts` looks for those rows. It only reads.++**Say to your agent:** *"Run the gbrain pooler misroute audit for the window+the serve ran through the transaction pooler, and show me the result before+changing anything."*++## When to run it++Run it once after upgrading if, before the upgrade, any of these held for a+serve or worker on the brain:++- the database URL used port 6543 or `?prepare=false`;+- the log carried `pg_statement_build_failed`, `pg_connection_stuck` or+ `pg_connection_desync` lines;+- `/health?deep=1` showed `transport.max_pipeline` other than `0` behind such a+ URL.++The window is from the first such serve start (or the first warn line) until+the upgraded serve started.++## Run++The script is one self-contained file: it needs no checkout and imports+nothing from gbrain, only the postgres driver your install already ships+(`vendor/postgres` under the gbrain install; set+`GBRAIN_AUDIT_POSTGRES_DRIVER=<path to vendor/postgres/src/index.js>` if it is+not found). On a host without a checkout, copy `scripts/audit-pooler-misroute.ts`+from the gbrain repository at this version or later, then:++```bash+bun audit-pooler-misroute.ts \+ --url 'postgresql://postgres:<password>@db.<project>.supabase.co:5432/postgres' \+ --since 2026-10-01T00:00:00Z --until 2026-10-12T18:00:00Z --json > audit.json+```++- `--url` is explicit (never read from the environment) and must be the direct+ URL or the session pooler (Supabase: port 5432). A transaction-mode URL (port+ 6543 or `?prepare=false`) is refused: the audit must not read through the+ transport it audits. It opens one connection.+- Each batch (`--batch-size`, default 500 rows) is one+ `REPEATABLE READ READ ONLY` transaction with a transaction-local timeout+ (`--batch-timeout-ms`, default 15000). There is no snapshot across batches;+ a row written while the audit runs is reported `unknown`+ (`changed_during_audit`). Running it beside a live serve is safe.+- Exit `0`: no mismatch. Exit `1`: at least one mismatch. Exit `2`: usage error+ or refused URL.++## Read the result++- `verified_ok` counts requests and effects whose identity values all agree.+- `mismatch` lists each row and field whose value belongs to another row:+ an effect whose `source_id`, `source_incarnation` or `worktree_id` differs+ from its own request (they are copied in one statement), a request whose+ `source_incarnation` is another source's (`belongs_to`), or a request whose+ `page_id` names a page in another source.+- `unknown` lists rows the audit cannot judge, with `reasons`+ (`unknown_by_reason` counts them): `changed_during_audit`,+ `compacted_history`, `token_reclaimed` (the claim stamp names another+ execution token), `source_removed`, `source_reincarnated`, `page_removed`,+ `page_slug_differs` (usually a later move) and `effect_identity_unset` (rows+ from before those columns). Unknown is not clean: it is a coverage gap.++## After a mismatch++Do not repair anything from the audit alone. A corrective write is a one-way+door: send `audit.json` (it holds row ids and identity values, no page+content) with the serve logs of the window to the brain's owner, and decide+the fix together from a preview. Re-running the audit is always safe.diff --cc src/core/behavior-change-notice.tsindex c0146224de,d2857c001e..4793c3965f--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -479,12 -479,8 +479,14 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.185.0', text: 'gbrain\'s own brain-repo commits (page write-through, facts fences, takes, timeline, `lint --fix`, and `sources harden` scaffolding) now take the checkout\'s commit lock (write-through waits 2 seconds, then commits its one path without it), commit only their own paths, and include both sides of a staged `git mv` rename. Paths passed to the helper or `gbrain git commit-push` are literal: a quoted glob no longer expands and fails `commit_paths_invalid`; name the files.' },{ since: '0.60.185.0', text: 'The pull that `gbrain sources pull`, the pull cron, `sources harden` and the workspace push run no longer rebases: a branch whose local and remote sides diverged is merged in memory and the checkout fast-forwards to the merge, for `pull_strategy: rebase` as well as `merge` (`set-pull-strategy` is still accepted). `gbrain sync`\'s pull is now a fetch plus a fast-forward under the commit lock. `gbrain sources harden` sets `rebase.autoStash=false`, `merge.autoStash=false` and `pull.ff=only` in the checkout\'s local git config so a stray `git pull` refuses instead of autostashing. A conflict now stops with `integrate_conflict` (ask the user; resolve with `gbrain git commit-push --push-only --expect-remote <sha> --resolve <path>=ours|theirs`), and `put_page` reports an unresolved one for that checkout.' },{ since: '0.60.185.0', text: 'The committed `scripts/brain-commit-push.sh` written by `gbrain sources harden` needs a gbrain that knows `git commit-push` to integrate remote commits. Without one it does only a locked, path-scoped commit and a plain push, and a rejected push now fails loudly (exit 4, PUSH FAILED) instead of rebasing. A helper written by a newer gbrain (a higher `# gbrain-protocol:` line) is never downgraded by an older harden.' },+ // GBRA-60 D2/D4 in-band notices. `since` is provisional (current VERSION); restamped at the merge slot.+ { since: '0.60.186.0', text: 'Two new info notices on MCP results; nothing a connection can call changes. `grant_blocked_operations` tells an authenticated connection once per session (once per grant revision for stateless HTTP) that its grant\'s operation snapshot, stored client surface or the server surface keeps operations its scopes allow out of reach, with counts and no operation names, and gives the brain owner\'s preview-then-apply rescope command (a missing scope is named only on a refused call). `hidden_tool_content` on get_page, search and query says when the result left out takes that a tool outside the tool list serves, with the next step that connection can take: the takes_list call (stdio also lists it), one request_tools {surface} widen, or the owner\'s repair. Fixes no longer name an MCP tool outside the grant\'s operation snapshot, and the stdio unknown-tool hint no longer offers a widen that read-only access or GBRAIN_MCP_FORCE_SURFACE would refuse.' },+ // #6543 (GBRA-84). `since` is the release this PR is slotted for (restamped at the merge slot).- { since: '0.60.186.0', text: 'Read pools no longer pipeline statements behind a transaction-mode pooler: a database URL on port 6543 or with `?prepare=false`, or `GBRAIN_PREPARE=0`, now builds the read pools with `max_pipeline: 0` (through Supavisor, pipelined statements hung or came back with another statement\'s rows, #6543). A session-mode pooler (Supabase port 5432) and direct URLs keep the driver default; a URL `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins. The direct pool is unchanged.' },- { since: '0.60.186.0', text: '`/health?deep=1` now answers 503 `persistence_restart_required` when the serve\'s persistence consumer reports restart_required (it answered 200 before), and every deep-health 503 carries a stable `code` (`persistence_restart_required`, `pool_inflight_over_budget`, `deep_health_probe_failed` with `reason`), `fix` and `docs`. Both answers carry a `transport` block (pooler mode, the live `prepare` and `max_pipeline` with its reason, the server `statement_timeout`, `session_timeouts_not_applied`), and `gbrain serve` logs it once at startup as a `[gbrain serve] transport` line.' },- { since: '0.60.186.0', text: 'New opt-in `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (at least 120; a smaller value refuses to start serve): once the persistence consumer has reported restart_required continuously for n seconds, `gbrain serve` disconnects under a 5 s deadline and exits 69 (`serve_unhealthy_exit`) so a supervisor restarts it; after 3 self-exits within an hour (`serve-self-exit.json` under the gbrain home) it stops exiting and reports `self_exit_suppressed`. Off by default: nothing changes unless it is set.' },- { since: '0.60.186.0', text: '`gbrain sync --no-delegate` (or `GBRAIN_SYNC_NO_DELEGATE=1`), and a sync that falls back because the serve is not answering its IPC socket or predates delegated sync, now run this process\'s own consumer even under persistence.single_consumer (they waited behind the serve they bypassed), and log `two_consumers_on_host` while a serve consumes on the same host. The other fallback lines no longer claim the run uses its own consumer: they say it does not delegate and, with single_consumer on, the serve publishes its writes.' },- { since: '0.60.186.0', text: 'A `pg_statement_build_failed` line for `UNDEFINED_VALUE` now names the parameter (`param=$2`, or `param=?` for an array element), and a pipelined build failure no longer lets the pool queue more statements behind it on a connection built not to pipeline. A connection closed by the server (57P01) or a pooler no longer hands its error to the first statement on the replacement connection.' },++ { since: '0.60.187.0', text: 'Read pools no longer pipeline statements behind a transaction-mode pooler: a database URL on port 6543 or with `?prepare=false`, or `GBRAIN_PREPARE=0`, now builds the read pools with `max_pipeline: 0` (through Supavisor, pipelined statements hung or came back with another statement\'s rows, #6543). A session-mode pooler (Supabase port 5432) and direct URLs keep the driver default; a URL `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins. The direct pool is unchanged.' },++ { since: '0.60.187.0', text: '`/health?deep=1` now answers 503 `persistence_restart_required` when the serve\'s persistence consumer reports restart_required (it answered 200 before), and every deep-health 503 carries a stable `code` (`persistence_restart_required`, `pool_inflight_over_budget`, `deep_health_probe_failed` with `reason`), `fix` and `docs`. Both answers carry a `transport` block (pooler mode, the live `prepare` and `max_pipeline` with its reason, the server `statement_timeout`, `session_timeouts_not_applied`), and `gbrain serve` logs it once at startup as a `[gbrain serve] transport` line.' },++ { since: '0.60.187.0', text: 'New opt-in `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (at least 120; a smaller value refuses to start serve): once the persistence consumer has reported restart_required continuously for n seconds, `gbrain serve` disconnects under a 5 s deadline and exits 69 (`serve_unhealthy_exit`) so a supervisor restarts it; after 3 self-exits within an hour (`serve-self-exit.json` under the gbrain home) it stops exiting and reports `self_exit_suppressed`. Off by default: nothing changes unless it is set.' },++ { since: '0.60.187.0', text: '`gbrain sync --no-delegate` (or `GBRAIN_SYNC_NO_DELEGATE=1`), and a sync that falls back because the serve is not answering its IPC socket or predates delegated sync, now run this process\'s own consumer even under persistence.single_consumer (they waited behind the serve they bypassed), and log `two_consumers_on_host` while a serve consumes on the same host. The other fallback lines no longer claim the run uses its own consumer: they say it does not delegate and, with single_consumer on, the serve publishes its writes.' },++ { since: '0.60.187.0', text: 'A `pg_statement_build_failed` line for `UNDEFINED_VALUE` now names the parameter (`param=$2`, or `param=?` for an array element), and a pipelined build failure no longer lets the pool queue more statements behind it on a connection built not to pipeline. A connection closed by the server (57P01) or a pooler no longer hands its error to the first statement on the replacement connection.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */