Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/w16-pregate
garrytane356d5447444
diff --cc CHANGELOG.mdindex d3e9bda8f4,b9cbc03cb1..0f1b843754--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,91 -10,25 +10,110 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).- ## [0.60.188.0] - 2026-10-12++## [0.60.189.0] - 2026-10-12++**Fix wave 16: a page purge no longer holds its source hostage, duplicate-origin twins can be retired, managed sync's leftover bookkeeping has a repair instead of a permanent red doctor, fact extraction stops refusing whole entities for one forgotten claim, long items are no longer certified complete when the model read only their head, four community CLI and platform fixes land, the three test files failing CI without a product bug are fixed at the root, and the nightly routing eval is green again (#6511, #6517, #6518, #6513 follow-ups, #6506, #6523, #6503, #6333, #6521, #6512, #6514, #6510, #5312 in part, #6040, #6495 in part).** `gbrain delete <slug> --purge` searched the source's whole write journal inside its 5-second publication transaction and a timeout there was requeued forever, blocking every later write to the source; the search now runs at preparation under the preparation budget and the in-transaction lookups fail terminally. Two live pages recording one file had no supported exit short of raw SQL; a soft delete now keeps the file and hides the page. On a managed brain one forgotten claim refused the entity's whole fact group; the claim is skipped and counted. `extract_atoms` stamped an item complete after reading a 50,000-character head and could later retire the atoms a larger cap had produced from the tail; it now records the item as partial. Two additive migrations (v240 online index, v241 nullable column), no paid model call added, no change to any weights file. Plan reviewed by three voices and approved by Garry on 2026-10-12.++### Itemized changes++**Persistence: purge, origins, request indexes (#6511, #6517)**++- **Page purge journal sweep at preparation (#6511).** `preparePagePurge` (`src/core/persistence/page-purge.ts`) reads the page's claims (fact rows and takes filed on the page, trimmed, 8 characters or longer, at most 32 needles) and runs `sweepRequestsCarrying` (`intent-redaction.ts`) at claim steps `purge_claims` / `purge_journal_sweep`: a keyset walk of the source's journal in 2,000-row chunks, every needle in raw and JSON-escaped form against intent, outcome, error detail and error message, compacted rows included, stopped by the claim clock between chunks and at the 10,000-match cap. The sweep records the `sequence` ceiling and the rows pending at the scan; the publication transaction re-checks only the tail past the ceiling and those rows, so a carrying request admitted-then-cancelled or settled after the scan is still redacted and a request still queued at publication is left in place. The committed receipt reports `journal_sweep` (`ceiling`, `scanned`, `tail`, `pending_rechecked`, `complete`); `complete: false` means a cap was hit and is never swallowed. A sweep that outruns the preparation budget is a charged `preparation_deadline` release and `preparation_stalled` at the attempt limit, never a transaction timeout.+- **`purge_lookup_timeout` (#6511).** The lookups that stay inside the transaction (the slug lookup, the tail and pending re-checks, the locking read of `redactRequestIntents`) map a 57014 statement timeout to the terminal, non-retryable `purge_lookup_timeout` on the first claim: nothing removed, tombstoned or redacted, the failed receipt retained, a following write to the source commits, a same-id retry returns the failure and a new `request_id` is admitted. The message names `gbrain repair request-indexes --apply` only when the slug index is missing or INVALID. Registry row (`class: caller`, `actor: host_admin`), `docs/guides/write-refusals.md#purge_lookup_timeout`. `purge_fact` (`src/core/facts/purge.ts`) maps the same timeout of its planning read to the same code.+- **Migration v240 `persistence_request_slug_intent_index` (#6511).** Partial index `persistence_requests_slug_intent ON persistence_requests(source_id,slug,sequence) WHERE intent IS NOT NULL AND NOT compacted`, built online in the `v179` shape (`transaction: false`, CONCURRENTLY on Postgres after dropping an INVALID leftover, inline on PGLite). `readRequestIndexStates`, doctor `persistence_request_indexes` and `gbrain repair request-indexes` cover it through `PERSISTENCE_REQUEST_ONLINE_INDEXES`. DDL only: no column, no backfill.+- **Fault seams (#6511).** `purge:slug_lookup`, `purge:tail_recheck`, `purge:pending_recheck`, `purge:redaction_read`, `purge:sweep_chunk`, `purge:carrying_lookup` in `fault-points.ts`; production never installs a hook; the tests inject a 57014 or a stall at these seams, never through an SQL substring.+- **One origin rule (#6517).** `selectOriginClaimant` (`src/core/persistence/sync-origin.ts`) decides which page an origin file identifies when several pages record it: a live page wins over tombstones; several live pages refuse; a single tombstone may be reused; several tombstones stay ambiguous. Discovery's census (`sync-discovery.ts`, the one-statement identity snapshot now carries `deleted_at`) and `assertSyncPageOrigin` both apply it, so a soft-deleted twin no longer blocks the survivor's imports; the `page_identity_changed` refusals for several live claimants name the soft-delete exit. `assertSoleFileClaim` (`reconcile-state.ts`) uses the same census.+- **Shared-origin soft delete (#6517).** `delete_page` of a page whose file another live page of the source records (`findLiveFileClaimants`, new `src/core/persistence/file-claims.ts`) keeps the file and publishes database-only before any byte comparison: receipt `write_through.skipped: 'shared_origin'` with the warning "The selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents." and the `gbrain sync --source <id> --no-pull --full` that imports the kept file into the surviving page. The survivor is revalidated under the publication guards; the file moved or removed, or a different set of claimants, refuses `source_changed` and never removes the file as a fallback. A purge of a shared-origin page refuses and names the soft delete. The receipt names the surviving slug to the trusted local owner and to a remote writer whose grant, delegated namespace and page visibility independently cover it (`slugDisclosable`, `authority.ts`); every other remote writer reads "Another page of this source records the same file." with no slug and no path.++**Managed sync bookkeeping and diagnostics (#6518, #6513 follow-ups)**++- **Stale bookkeeping of a source incarnation the source no longer has is retirable; `doctor --fast` no longer reports a vanished failure as FAIL (#6518).** A source re-pointed at a new checkout, or removed and added again, left its old cursor, failure row and local-ledger mirror under the previous incarnation: `gbrain sync status` named a cursor no current sync could select, `readManagedSyncFailures` saw nothing while `doctor --fast` still failed on the mirrored row. `gbrain repair managed-sync-orphans --source <id>` now lists such rows as `incarnation_retired` and ledger rows whose durable failure row is gone as `mirror_only`, and applies them under the printed hash; a successful sync prunes a source's stale mirror rows. `gbrain doctor` (with a database) classifies the orphans and names the repair even when no current failure is visible; a classification that fails names its code and is never reported healthy. `gbrain doctor --fast` (no database) reports mirrored managed rows as `warn` "could not be verified without a database connection" instead of `fail`, while old unmanaged file failures keep their severity. `gbrain sync status --source <id> --json` reports an old-incarnation cursor as `cursor: null` with `last_error.code: cursor_incarnation_retired` and the repair preview as `next`.+- **A checkpoint whose cursor another run of the same source replaced is superseded, not failed (#6513 comments).** When a `--retry-failed` rediscovery or a newer sync replaced the cursor while an older run's final checkpoint was in flight, the loser's checkpoint refused `revision_conflict`, its run recorded a managed-sync failure, `gbrain doctor` reported it as unresolved and `--retry-failed` treated the receipt as a page fault. The refusal is now `sync_cursor_replaced` (receipt state `conflict`; new `sync-checkpoint-replaced.ts`), nothing is recorded for the superseded checkpoint, the run that awaited it goes on with the cursor that now covers the source, and `--retry-failed` converts nothing. A same-run index lag still reports `revision_conflict`; a missing manifest still reports `storage_error`.+- **A publication a database trigger refuses names the trigger, its table and a closed reason wherever the failure is shown (#6513 comments).** A managed sync blocked by a trigger gbrain does not know said only `storage_error: Publication failed (P0001 in <raiser>). Inspect owner diagnostics.`; the receipt's `write_error_detail` was the one place that named the raiser and table. The failure the run records, the failure ledger, `gbrain doctor` and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail`) now carry `raiser`, `table` and a `reason` from a closed set (`PUBLICATION_REASONS`): `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch between processes sharing the database), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, now recognized with a retry-later message instead of an owner-exception `storage_error`, and classified retry / no human in `sync status` and `sync unblock`), or `unknown`. The trigger's message text is kept nowhere: not on the receipt, not on the brain host.++**Facts and extraction (#6506, #6523, #6503, #6333, PR #6515)**++- **Managed automatic fact extraction skips a forgotten claim instead of refusing the entity (#6506; supersedes #6507, contributed by @BichengWang).** Sync import, `put_page`, `extract_facts` and the sweep skip a candidate whose exact claim was forgotten in that source and visibility and publish the entity's other facts, counting the skips as `withdrawn_skipped` on the entity and completion receipts and the extraction result; before, one forgotten claim refused the whole group with `fact_withdrawn`. `remember` of the forgotten claim and a purge tombstone still refuse. A claim forgotten between preparation and publication refuses that entity's write with `revision_conflict` and a detail naming the withdrawal. An input-keyed extraction recovers from such a refusal, and from a batch an older release refused for a forgotten claim, on its next run: the retained facts are re-admitted as a follow-up batch with no model call (`followWithdrawalRefusals`), at most three times per batch, historical receipts untouched.+- **The claude-cli provider maps Claude Code's output-cap envelope to `finishReason: 'length'` (#6523; supersedes #6525, contributed by @javieraldape).** "API Error: Claude's response exceeded the N output token maximum…" (any cap, any exit code, no `api_error_status`) becomes a length-limited answer with empty text and the usage as reported, so the escalation ladders fire again: `loops_extract` 2048 → 8192 and the facts extractor 1× → 2×. Every other error envelope stays a typed `ClaudeCliProcessError`.+- **`extract_atoms` no longer certifies an item complete when its text was cut at `cycle.extract_atoms.max_input_chars` (#6503; report and first visibility slice by @herman6888).** The head is extracted once and its atoms kept, but no completion stamp is written, no earlier atom is retired, the phase result and `gbrain dream --drain` count the item under `input_truncated` with a stderr line naming the knob, and the item is skipped with no model call until the cap rises or its content changes. Migration v241 adds nullable `partial_input_chars` to the two extract_atoms state tables; a managed brain records `partial` on the item's checkpoint and the completion receipt reads `status: 'partial'`. The cut moves to new `src/core/cycle/extract-atoms-input.ts`. #6503 stays open for the chunk+overlap feature.+- **The #6333 same-page rewording shadow counter also fires on a managed brain.** New `src/core/facts/same-page-shadow.ts` is shared by the backstop and `facts-prepare.ts`; managed extraction counts `would_dedup_same_page` on the entity and completion receipts and the `extract_facts` result and prints the same stderr line; nothing is dropped; the measurement can now accumulate on a managed brain (#6334 stays open).+- **Two managed enumeration regressions for the #6500 contract**, carried as already-green tests in `test/conversation-facts-managed.test.ts` (the production fix landed in #6516): a slug keyset drains a 23-page timestamp tie without crossing source, type or soft-deletion fences, and a 13-page extraction walk survives a mid-run edit of its oldest unvisited page (supersedes #6515, contributed by @javieraldape).+- #6508 (conversation segment tail clip) was already fixed by v0.60.177.0's window bounding; closed with that pointer.++**CLI and platform (#6521, #6512, #6510, #5312 in part)**++- **`gbrain core <sub> --help` and `gbrain loops <sub> --help` answer before any engine access (#6521, reported by @benswinney).** `core` and `loops` are routers in `src/cli/subcommands.ts` and `src/cli/router-help.ts`; `src/commands/core.ts` and `src/commands/loops.ts` export their `SUBCOMMANDS` and `printUsage`, and `gbrain transcripts status --help` answers the help flag instead of opening the brain. A 14-row table in `test/cli-help-without-brain.test.ts` runs each subcommand's `--help` with no brain configured (on master `internal_error: null is not an object`).+- **A compiled binary installed from a hoisted `node_modules` reaches its PGLite diagnostic (#6512, contributed by @tarush1989).** `src/core/pglite-embedded-assets.ts` imports `@electric-sql/pglite` lazily inside `build()`, so loading the module no longer needs the package and the tier-3 "PGLite assets missing" message is the one the user sees.+- **The Git-scope manifest refuses symlinks, not a filesystem's spelling of a tracked path (#6510; supersedes #6520, contributed by @javieraldape).** `trackedBytes` in `src/core/persistence/worktree-manifest.ts` `lstat`s every directory component and the leaf of each tracked path through Git's own spelling, so a path whose on-disk spelling differs (NFD on macOS, a case-folding volume) reads as the tracked file it is while a symlinked component or leaf is still refused.+- **Backup data-dir sweep on Windows: an owned socket the runtime cannot inspect is probed and claimed, removed only through the native tag check, otherwise kept and named (#5312, part A; native re-test by @xiaopeng6390).** `entryStat` in `src/core/backup/runtime-artefacts.ts` returns `Stats | 'missing' | 'unreadable'`; an unreadable owned entry is removed only via `removeStaleWindowsSocket`, anything nothing can verify is kept as `unreadable` and the refusal says `cannot inspect`. The `windows-latest` row of `test.yml` runs the test natively. The `private_backup_path_unavailable` text names the inherited-permissions cause and the fix (`docs/guides/in-agent-setup.md`).++**Search operations (#6495 in part, #6040)**++- **Postgres keyword search has an operator time bound, `search.keyword_statement_timeout_ms` (Refs #6495).** The keyword, keyword-count, keyword-page, title and CJK search statements used to run under a fixed 8 s `statement_timeout`; they now share one knob (integer milliseconds, default 8000, range 1000–60000; `gbrain config set search.keyword_statement_timeout_ms 20000`, then restart the serving process). It is resolved once per connection by the first keyword statement and never from a request, so a remote caller cannot widen it; `config set` refuses a value outside the range and writes nothing, and a stored value outside it reads as the default. `gbrain doctor` gains `keyword_plan`, a read-only canary that takes the brain's commonest keyword term from the planner's statistics, EXPLAINs the strict count statement and times the engine's own bounded count, warning when it times out or spends more than half the bound; it names the knob, says one canary term is not workload coverage, and never reports a timed-out count as "no matches". A longer bound buys time, not a cheaper statement: the bounded candidate set for broad terms stays open on #6495. PGLite is unchanged. Guide: `docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain`.+- **`query` and `search` route "all the people/companies/projects that do X" to `query` again (Refs #6040).** The search description rewrite that taught agents keyword OR lists also told Haiku 4.5 that `search` lists every matching page, and the nightly LLM routing eval has been red since (18/20; 28 of 80 concept phrasings misrouted at temperature 1 against 3 of 80 before). Both descriptions now say that people/companies/projects by topic are `query` work, the exact wording that measured 1/80; the batching sentence stays, so `search`'s per-tool budget grows 1800 → 1830. The description-edit checklist in KEY_FILES names the live test (`GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 bun test test/e2e/salience-llm-routing.test.ts`), 20/20 on this head.+- **The served starter tool list keeps 200 characters of headroom under its 25,000-character ceiling** (it sat at 24,998). Redundant words in tool text no other wave owns are gone (`Optional;` on the shared `request_id` parameter, examples and clauses that repeated the description on `capture.type`, `edit_page.expected_revision`, `get_recent_salience.slugPrefix`, `resolve_slugs.partial`, `mute_notice`, the write-receipt tools, `request_tools`, `list_pages`, `traverse_graph.link_type`, `get_skill`). Every pinned phrase is kept and every description stays at or above 60 characters; `test/mcp-schema-budget.test.ts` asserts the floor through the served list with `publish_skills` on and off (measured 24,796). The entity card, the `MEMORY VERB (v1)` labels and the rest of the query/search text belong to other waves and are untouched.++**CI, flakes, tooling (#6514, #6040 item 4, #6534)**++- **The unconfigured-gateway fixtures stop reaching the provider; lint R7 guards the restore (#6514, contributed by @tarush1989).** `test/think-gateway-adapter.test.ts` uses `__unconfigureGatewayForTests()` and asserts `AIConfigError` at the adapter fork and the backstop, restoring in `afterEach`. `scripts/check-test-isolation.sh` rule R7: `__unconfigureGatewayForTests(`/`_clearGatewayForTests(` without `resetGateway(` in an `afterEach`/`afterAll` hook fails the lint; `test/chronicle-upgrade-notice-5876.test.ts` was the one offender and gets its hook. No allowlist row added.+- **Secret scanner: one-pass `correctedEntropy`, `ScanWork` counters, allowlist in its own module.** `src/core/secret-scan.ts` computes the entropy histogram in one pass (about 80 → 25 ms per 250 × 4096-char segment on a 4-core box; `test/secret-scan-entropy-equivalence.test.ts` pins `Object.is` equality with the former function over 561 samples), counts candidates, gated characters, pattern execs and claims through an optional `ScanWork` (`src/core/secret-scan-work.ts`, pinned at the measured counts, two mutants fail), and the workspace allowlist moves to `src/core/secret-scan-allowlist.ts`. The 300 ms perf bound is unchanged.+- **Three deterministic test suites.** `test/migrate-retry.test.ts` runs its poll cases on a fake clock through the `_hooks.now/sleep` seam (exact pins: 30 iterations / 31 calls, `race_resolved` at t=15; the `> 5` assertion stays) (#6534). `test/helpers/managed-atoms-contract.ts` waits for the deferred batch to settle before asserting (forced probe with a 1 ms maintenance wait: 3/3 fail before, 6/6 pass after, both engines). `test/helpers/managed-facts-embedding-contract.ts` restores the 250 ms publish-wait override right after the `write_pending` assertion so replays wait under the product's deadline (forced 600 ms claim stall: `write_pending` before, `committed` after, both engines).+- **5530 Git-coalescing files.** Setup seeds go through `put_pages`; the `#6210` durability-probe cases move to `test/persistence-git-durability-probe-6210.slow.test.ts` with its Postgres wrapper; both share `test/helpers/git-coalescing-fixture.ts`. A new case asserts the batch seed leaves the same Git effect rows, page hashes, queued count and commit count as the per-page seed. Postgres file 74 → 45 s; PGLite 116 → 90 s. `BACKLOG = 600 × 1 s` unchanged.+- **Tier 2 OpenClaw install waits out a registry race.** `scripts/ci-install-openclaw.sh` (from the inline loop in `e2e.yml`): an attempt failing with npm `code ETARGET`/`E404` (a dependency version published but not yet visible everywhere, the 2026-10-12 master red) is retried up to 4 times 20/40/80 s apart; any other failure keeps 3 attempts 10 s apart. `test/scripts/ci-install-openclaw.test.ts` installs a one-file package from a loopback registry that answers ETARGET or E404 three times, forever, or with `EBADPLATFORM`.+- Docs: `docs/TESTING.md` (R7 row; back under its byte cap), new `docs/architecture/key-files/{secret-scan,core-persistence-request-indexes,core-persistence-facts,managed-sync-bookkeeping}.md`, `KEY_FILES.md` rows trimmed under the 10,000-byte cap, `docs/guides/{write-refusals,error-codes,repair,sync-unblock-runbook,memory-boundaries,troubleshooting,in-agent-setup}.md`, `docs/operations/spend-controls.md`; `llms-full.txt`, `scripts/structural-suites.tsv`, manifests and goldens regenerated.++### Things to watch++- `readRequestIndexStates(engine)` lists three indexes by default (`PERSISTENCE_REQUEST_ONLINE_INDEXES`); callers that need the checkpoint pair alone pass `PERSISTENCE_SYNC_RUN_INDEXES`. Doctor `persistence_request_indexes.details.indexes` gains the third row. A committed page purge's receipt gains `journal_sweep`.+- A soft delete can now commit with `write_through.skipped: 'shared_origin'` and a `write_through.warning`. Discovery's identity snapshot and the origin-check statement now select `deleted_at`; tests that match either statement by text were updated.+- New error codes `purge_lookup_timeout`, `cursor_incarnation_retired`, `sync_cursor_replaced` (`gbrain errors <code>`); new `gbrain repair managed-sync-orphans` reasons `incarnation_retired` / `mirror_only` and a `source_incarnation` field on each listed orphan. A `revision_conflict` checkpoint receipt is now only a same-run index lag.+- `ManagedSyncFailure` / `sync status --json last_error` gain `write_error_detail`; `last_error.detail` can now be a publication `reason`. Stored receipt messages for untyped trigger refusals read `Publication failed (P0001 in <raiser>: <reason>). Inspect owner diagnostics.`+- `gbrain doctor --fast` can score higher than before on a brain with stale mirrored managed rows: that is less certainty, not recovery; the engine-backed check stays authoritative.+- Managed facts: under the automatic-extraction flag, locked validation runs the per-entry purge and withdrawal checks before the page's fence re-validation; a purge written between preparation and publication refuses `purged_content`, a withdrawal in that window refuses `revision_conflict` with `error.withdrawn` set. Receipts and the `extract_facts` result gain `withdrawn_skipped` and `would_dedup_same_page`.+- The `extract_atoms` phase result and the drain result carry a new `input_truncated` count; a managed completion receipt for a cut item has `outcome.status: 'partial'` (+ `partial_input_chars`); discovery and the doctor backlog count exclude partial items until the cap rises.+- `search.keyword_statement_timeout_ms` takes effect on the next connection: the next CLI command picks it up, a running `gbrain serve`, autopilot or job worker needs a restart. `gbrain doctor --only keyword_plan --json` shows `details.timeout_ms`.+- `search`'s per-tool description budget is 1830 (was 1800), with the reason in `TOOL_BUDGETS`.+- Weights: `test/persistence-git-durability-probe-6210.slow.test.ts` (≈35 s PGLite) and `test/e2e/persistence-git-durability-probe-6210-postgres.test.ts` (≈18 s) are new and unweighted; the 5530 rows measured 90 s / 45 s. Weights files are not edited in this release.++### Migrations++- v240 `persistence_request_slug_intent_index`: online partial index on `persistence_requests(source_id, slug, sequence)`, `transaction: false`, CONCURRENTLY on Postgres, inline on PGLite. DDL only.+- v241 `extract_atoms_partial_input`: `ADD COLUMN IF NOT EXISTS partial_input_chars INTEGER` on `extract_atoms_page_state` and `extract_atoms_transcript_state`. Metadata-only, no backfill.- ## [0.60.187.0] - 2026-10-12++## [0.60.188.0] - 2026-10-12++### Itemized changes++- **`query` expands only when the search mode says so (GBRA-81 item 1b).** The `query` operation used to send `expand: true` on every call, so every mode, `balanced` included, made one expansion LLM call before retrieval. It now leaves `expand` unset unless the caller passes it, so the resolved mode decides: on in `tokenmax`, off in `balanced` and `conservative`. `expand: true` (CLI `--expand`) forces it and `expand: false` (`--no-expand`) skips it; `gbrain config set search.expansion true` restores it by default for a brain, and a `search.expansion` value set earlier, which `query` ignored, now takes effect. The expander stays wired whenever expansion can resolve on, so `tokenmax` still expands. CRAG's caller-expanded check reads `expansion_applied`; eval capture records the raw `expand` param (null when unset) and `gbrain eval replay` maps null to the mode default. The tool description, the concept-search hint, `gbrain search modes`, `search tune`, top-level help, the picker copy and the docs say the same, and a guard test rejects "in every mode" / "always expands" phrasing in `src/` and `docs/`. `test/search/operation-expansion-contract.serial.test.ts` is rewritten to pin the new contract.+- **`gbrain init` reads keys the way the gateway does.** Provider keys are read through `mergedProviderEnv`, so a key saved in `~/.gbrain/config.json` counts, and a brain with a ready reranker but no chat key gets `balanced` instead of `conservative` (the reranker branch uses `rerankerReadiness`, not a key name); `conservative` stays for a Haiku subagent or when neither a chat key nor a ready reranker exists.+- **`gbrain init --search-mode <mode>` and `search.mode_source`.** An agent that knows the operator's choice records it at install time: no recommendation, no first-run `search_mode` ask, `search.mode_source: operator`. On a brain with a different mode it refuses unless `--force`. Picker choices record `auto`; `gbrain config set search.mode` records `operator`.+- **One source for the mode advice.** `src/core/search/mode-advice.ts` holds the recommendation, its reasons and evidence, the `[AGENT]` and upgrade banners, init's first-run decision text and the cost matrix, now priced for Haiku 5.5, Sonnet 5.5 and Opus 5.5 from `src/core/model-pricing.ts` (about a 200x corner-to-corner spread). `INSTALL_FOR_AGENTS.md` Step 3.5 carries the generated matrix, kept in sync by a test. Switching modes no longer promises a cache refill while semantic result caching is off.+- **`gbrain eval longmemeval --via-operation query|search`.** Runs each question through the real operation with an agent's stdio MCP context (remote, stdio, source `default`) at the operation's default limit, with `--op-expand on|off` for `query`. Rows record the context, the `expand` sent, model calls per touchpoint, latency, the CRAG grade and the expansion outcome; `run_config.via_operation_summary` has the gbrain tree, commit and dirty flag of the checkout the harness runs from (not the caller's cwd), p50/p95 latency and model calls per query, and a row's `search_meta.reranked` comes from the operation's recorded rerank call. A run that expects expansion fails when any question did not expand.+- **Lean search rows drop `id` where `fetch` is not callable.** Remote `search` and `query` lean rows carry `id` (the deep-research `fetch` key, base64 of `source_id` and `slug`, so a duplicate of two fields already in the row) only when `fetch` is callable on the caller's surface at call time. MCP dispatch threads one `isCallable(op)` predicate into `OperationContext`, built from the same check tools/list uses: the stdio session's surface after any `request_tools` widening, the HTTP client's effective surface and scopes under the server ceiling. `fields: "full"`, `mcp.result_rows: full`, gbrain's thin client and the local CLI are unchanged. On the committed Cat 40 Hard transcripts (served on `starter`, 3,169 `search` calls) a keyless replay (`scripts/replay-lean-row-savings.ts`) saves 9.52% of `search` characters on the starter surface and 1.35% on the full surface, where `id` stays and only score rounding applies.+- **Lean-row `score` prints 4 significant digits.** Rounding happens only in `leanRow`, so full rows and trusted local callers keep the raw float; RRF-scale scores are small, so fixed decimals would have collapsed them. Two scores print equal only when they agree to 4 significant digits, and order never inverts.+- **`fetch` without an id names both routes.** The refusal says to re-run `search` once `fetch` is callable, or to pass the row's slug (accepted when unambiguous in the caller's read scope).+- **`degraded_recall` shows on every affected call on stdio and the CLI.** Transient degradations (`rerank_failed`, `embed_timeout`, a failed keyword or title arm, every other per-call stage) are no longer deduped per session, so a failure after a different earlier failure, or the same failure after a recovery, always carries its notice. A notice made only of configuration-persistent stages (a keyless brain's `embed_unavailable`, about 600 characters on every search otherwise) carries an unrendered `dedupe_key` of its sorted unique stage/reason pairs, which the notice ledger dedupes on per session and the wire never shows. HTTP stays per call. `docs/protocol/AGENT_OPERATOR_v1.md` now states one rule for stdio, CLI and HTTP.+- **`entity names[]` is 5 to 17 times faster on a large brain, with byte-identical output.** On a 55,838-page PGLite brain built from the Cat 40 Hard world M generator (seed 20261021, no embeddings), a 20-name batch's median went from 2,250 ms to 129 ms with every name found, from 1,743 ms to 155 ms with half found, and from 1,112 ms to 203 ms with none found. Profiling showed the name lookup itself dominated, not the cards: each found name ran two sequential scans of the source's pages, the alias resolver's "no other live page has this exact title" check and the card's exact-title / exact-slug / slug-suffix arm, about 50 ms each. Migration v240 adds `idx_pages_source_title_lower` (`source_id, lower(title)`) and a trigram index on `slug` (`idx_pages_slug_trgm`), built online on Postgres; the queries are unchanged and now run as index scans in about 1 ms. Single-name `entity`, context_pack cards and search's alias fan-out use the same two reads. The batch also stops assembling a full card per name it then threw away: candidate selection is now one exported function, `selectEntityCandidates`, that `buildEntityCard` and `lookupEntityNames` both call; the lead reuses the candidate row's body; siblings are read without the identity excerpt (`readSiblingIdentity`); and the private-page setting, mention policy and source pack are read once per batch (`entityLookupScope`). Parity tests compare the batch with the old full-card resolver over adversarial names (colliding aliases and titles, namespaced slugs, the same slug in two sources, private, deleted and quarantined candidates, identity siblings, stale aliases, LIKE wildcards) on PGLite and Postgres, and plan tests pin both reads to the new indexes.+- **A Postgres statement timeout in the keyword or title arm is reported as a timeout (#6495).** `isTimeoutError` (`src/core/search/hybrid/degraded.ts`) now recognizes SQLSTATE 57014 through `isStatementTimeoutError`, so the arms' 8 s `SET LOCAL statement_timeout` on a large brain stamps `keyword_arm_failed` / `title_arm_failed` with reason `timeout` instead of `provider_error`. Probe in `test/hybrid-arm-rethrow.test.ts` (fails before).+- **Flake fix: `test/pglite-repair-command.serial.test.ts` case 1 no longer writes a fixed PID 99999 as its stale `postmaster.pid`.** On a busy host that PID can belong to a live process, so validation correctly refused ("postmaster.pid names a LIVE process") and the dry-run assertion failed (seen on a Ubicloud gate). The case now uses the file's `deadPid()` helper; a forced probe writing a live PID reproduces the failure.+ ## [0.60.187.0] - 2026-10-12++ **`gbrain serve` on a Supabase transaction pooler (:6543) no longer wedges. Answers stop landing on the wrong statement, and a persistence owner that needs a restart says so in `/health?deep=1` (#6543).** The vendored postgres driver sent several statements down one connection without waiting for each answer (pipelining). Supavisor's transaction mode can't carry pipelined statements across transaction boundaries. On a local Supavisor 2.5.1, 8 workers on a pool of 3 for 20 s gave 13 to 22 statements another statement's rows, plus connections that hung until the in-flight watchdog fired at 330 s. With pipelining off: 6078 ok, 0 errors. The two `pg_statement_build_failed UNDEFINED_VALUE` lines in the report were symptoms: each statement bound a column from a row that belonged to another statement. Three driver defects made it worse, and each is fixed here. Same-day mitigation for an older install: `PGMAX_PIPELINE=0` in serve's environment.++ ### Itemized changes++ - **No pipelining on transaction-pooler URLs.** Read-side pools (module, engine instance, connection manager) default to `max_pipeline: 0` when the URL is on port 6543 or carries `?prepare=false`, or when `GBRAIN_PREPARE=0`. `resolveReadPoolPipeline` reads the URL itself, so `GBRAIN_PREPARE=1` can't hide a 6543 URL. Your explicit `?max_pipeline=` or a non-empty `PGMAX_PIPELINE` still wins. Direct connections and the Supabase session pooler on :5432 keep the driver default. PgBouncer transaction mode carries pipelining correctly. Turning it off measured no cost there. A new PgBouncer E2E pins `?max_pipeline=100` so pipelined-through-a-pooler coverage stays.+ - **Driver: a dropped connection's error no longer poisons its replacement.** `closed()` now clears the saved error, result and row state on every close, not only during startup. Before, the next connection's first statement got the dead socket's `57P01` (direct) or `XX000 DbHandler exited` (Supavisor).+ - **Driver: a statement that fails to build respects the pipeline limit.** Before, the connection always reported itself ready, so statements were sent behind the failed one even with `max_pipeline: 0`. `begin`'s `onexecute` runs once, after a successful build.+ - **Driver: `UNDEFINED_VALUE` names the parameter.** The `pg_statement_build_failed` warn line now prints `param=$n`, and its text says that on a transaction pooler a build failure usually means a misrouted row. Every driver edit goes through `patches/[email protected]`. `test/postgres-driver-vendor.test.ts` checks all three vendored copies offline.+ - **`/health?deep=1` stays report-only, with stable codes.** Each 503 carries `code`, `fix` and `docs`:+ - `persistence_restart_required` comes from the in-process consumer state and is checked before the pooled probe.+ - `pool_inflight_over_budget` covers a statement older than the pool budget.++ A `transport` block, read once at startup, shows `prepare`, `max_pipeline` and why, the server `statement_timeout` (`session_timeouts_not_applied` with the `ALTER ROLE` fix when the pooler drops it), and the backend `application_name` when it is Supavisor. Serve logs the same line at startup. The body never carries request ids, hostnames or credentials.+ - **Opt-in self-exit: `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=<n>` (n >= 120).** Serve exits with code 69 (`serve_unhealthy_exit`) after `restart_required` has held continuously for n seconds, so a `Restart=always` supervisor recovers it. The hold resets when the condition clears. Cleanup is bounded at 5 s. After 3 self-exits within an hour (recorded in `serve-self-exit.json` under the gbrain home), serve stops exiting, logs `serve_self_exit_suppressed`, and deep health asks for a manual restart. Off by default.+ - **`--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` runs the sync's own consumer.** `forceOwnConsumer()` had no production caller, so with `persistence.single_consumer` on, an opted-out sync waited behind a wedged serve. Opt-out, a serve that doesn't answer its IPC socket, and a genuinely stale serve now force the sync's own consumer. A healthy current serve with delegation disabled (`unsupported_kind`, `unsupported_flag`, `kill_switch`) does not. Fallback lines stop claiming "uses its own consumer" on rungs that wait behind serve.+ - **Read-only misroute audit: `scripts/audit-pooler-misroute.ts`.** Self-contained, so it runs from a v0.60.180.0 global install. It refuses a transaction-pooler URL and takes an explicit `--url` (direct or session pooler). Each bounded batch is one `REPEATABLE READ READ ONLY` transaction on a single connection. It reports `verified_ok`, `mismatch` and `unknown`, and rows changed during the audit or with missing history count as `unknown`, never as clean. Guide: `docs/guides/pooler-misroute-audit.md`. Any corrective write is a separate, approved step.+ - **Corrected docs.** The claim that a server-side `statement_timeout` bounds every statement is corrected in `db.ts`, `consumer.ts`, `docs/ENGINES.md` and the error registry, since Supavisor drops the startup parameter. `docs/architecture/postgres-cancellation.md`, `docs/mcp/DEPLOY.md`, `docs/guides/exit-codes.md` and the error-code docs are updated. `GBRAIN_SUPAVISOR_URL` passes through `scripts/run-e2e.sh`.## [0.60.186.0] - 2026-10-12diff --cc docs/architecture/key-files/agent-bootstrap-continued.mdindex a1dd94ad94,44c85ff2f7..c81389cd32--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@@ -24,11 -24,12 +24,11 @@@- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `retireCorpusFile` / `retireCorpusTurns` (#6091) record a file or its off-period turns as finished without extracting (`skipped_reason`; a retire overrides another extractor's lease, and a later rewrite extracts only unrecorded turns). `parseCorpusTurns` (defined in the provider-free `corpus-turns.ts`, re-exported here) splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).- `src/core/context/corpus-source.ts` — #6268, the session's source for every corpus file. Writers (`hook.ts` compact/stop/session-end, the OpenClaw `compact()`) call `openSessionCorpus`, which freezes one source per session at first use (GBRAIN_SOURCE, then the `.gbrain-source` dotfile, else unresolved) into `<sid>.source.json` in the `sourced/` spool and stamps it into the file name (`.src-<id>`, `default` included; `_unresolved` cannot collide with a real id). Pre-stamp sweepers never list the spool. `resolveCorpusFileSource` is the sweep/harvest/serve read: the stamp or frozen record, else the brain's cwd chain once (frozen, tier `engine`); legacy top-level files are held (`corpus_legacy_unstamped`) unless a legacy wb stamp, a frozen record or a single-source brain proves the source, never assigned the pass source. The first engine resolution binds the source incarnation; a recreated source holds the session (`corpus_source_incarnation_changed`). `gbrain sweep --assign-corpus <source>` is the operator mapping (preview, then `--apply`); doctor `memory_writeback` reports `details.corpus_source_holds`. Tests: `test/corpus-source-stamp.test.ts`.- - `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) keeps the CLI's own consumer with one actionable line. Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).+ - `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). #6317 (D1 a′), managed Postgres brains: `maybeDelegateManagedSyncToServe(engine, args, opts)` runs post-connect from `runSingleSourceSync` right before `performSync`; it probes the host's live full `serve` consumer through `persistence_consumers` (`consumer-heartbeat.ts`, the database, never a socket), admits the catch-up's flags (`--no-bulk`, `--lanes`/`--no-lanes`, `--json`, the processing flags), sends the CLI's durable `cli` registration in `sync_start`, prints the drain's own numbered lines from `sync_status` (`managed`, `lines`, `drain`, `next`) and returns the SyncResult to the in-process printers, so exit codes and the JSON envelope do not change. The serve verifies the registration (`withVerifiedLocalRegistration`) and runs `performSync({ drain: true })` as that writer under `withHumanLineSink`; the shared-secret lane stays under `withLegacySyncDelegation` and is still refused on a managed brain; a denied, revoked or stdio registration answers `sync_start` with `permission_denied` and the envelope (`refusal`), which the CLI rethrows. Every other rung (no owner, a non-serve owner, an unsupported flag, no socket, the kill switch, `stale_serve` / `unsupported_kind` from an older serve, `source_mismatch`, a serve lost mid-drain) runs without the serve with one actionable line; only the opt-out, a serve not answering its socket and a `stale_serve` serve call `forceOwnConsumer` (#6543), the rest admit writes the serve consumes under `persistence.single_consumer`. Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/serve-sync-handoff.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step) and `test/e2e/serve-delegated-managed-sync.serial.test.ts` (Postgres, spawned serve, MCP latency printed).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. A live status-only `serve --http` marker (`liveStatusMarkers`, config plane) makes CLI `harness_wiring` `serve_status_only` with `transport: 'http'` and the status reason's fix (`httpStatusServerEntry`, shared with doctor), never "start `gbrain serve --http`" on the port it holds. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `stdioServeArgv` with `REGISTRATION_SURFACE` = `starter`, or `input.surface` from `gbrain init --surface`; `configReadiness(cfg, {transport, surface})` skips the memo when a surface is passed), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).-- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The transcript-only `labeled_credential` rule (`ScanOpts.labeledCredentials`) lives in `secret-scan-labeled.ts` (Security). The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimate `correctedEntropy`, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list) (never an alternation RegExp, never over emitted tokens). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.+- Secret and sensitivity scanning (`src/core/secret-scan.ts`, `src/core/secret-scan-allowlist.ts`, `src/core/secret-scan-work.ts`, `src/core/context/sensitivity-scan.ts`): see [secret-scan.md](secret-scan.md).- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts at message boundaries once a part would pass `PART_TARGET_BYTES` (45,000 bytes, 0.9 × the content-sanity warn line `DEFAULT_BYTES_WARN`; `renderSessionParts(…, { partTargetBytes })` overrides it for measurement and refuses a non-positive or non-integer target). No message is truncated (#6388; the former 4,000-character `MESSAGE_CHAR_CAP` is gone): a message whose block would not fit a part becomes continuation blocks that repeat its speaker and timestamp anchor, cut at line breaks or, inside an over-long line, at a code-point boundary (a cut piece always lands on the generated anchor line, so every body line was escaped whole); overlap repeats only whole messages, never continuation blocks, and is trimmed so no part body passes the target (`test/transcript-long-message-render.test.ts`). `scripts/measure-transcript-split-cost.ts` imports one deterministic synthetic 1 MB session through the real redact → render → `importFromContent` path into in-memory PGLite with a token-counting stub embedder at the former 300,000-byte target and the current one: 4 → 27 pages (×6.75), 380 → 424 chunks (×1.116), 199,614 → 217,057 embed input tokens (×1.087); the extra tokens are the part headers and the two overlap messages repeated at each boundary. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`). `redactSession` plans every field with `highEntropy` and `labeledCredentials` on.-- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch. `formatSensitivityDrop(drop, workspaceRoot)` renders the one content-free stderr line `gbrain compile-context` prints per dropped entry: reason `sensitivity_scan`, the pattern family, the fingerprint and the absolute `.gbrain-scan-allow` path, never the value (`test/sensitivity-scan.test.ts`).- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v2`, which includes the `connector` asset kind; a cache with any other schema reads as absent and is recomputed; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.- Workspace push and backup coverage (`src/core/workspace-push.ts`, `src/core/backup/{coverage,repository}.ts`): see [workspace-push-and-backup.md](workspace-push-and-backup.md).- `src/core/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.diff --cc docs/architecture/key-files/engines-2.mdindex 46c8969497,11d835d5af..795a5f5d96--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@@ -38,9 -38,9 +38,9 @@@ Current behavior and load-bearing invar- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. `withReservedConnection(fn, { selfContained: true })` (migration DDL, `buildIndexOnline`, backfill batches: `fn` touches only its reserved connection, like a transaction) may take the only connection of a one-connection ordinary pool, never the only direct session; pinned by `test/pool-budget.test.ts` and `test/e2e/pool-size-one-migrations.test.ts`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.- - `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`).+ - `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`). `formatBuildFailureWarning` appends `param=$n` (or `param=?` for an array element) to an `UNDEFINED_VALUE` line from the driver's `onbuilderror(code, statement, parameter)` (#6543).-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + a transaction-local `set_config` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection; the keyword-side bound (`searchKeyword`, `countKeywordPages`, `searchKeywordPages`, `searchTitles`, `searchKeywordChunks`, `_searchKeywordCJK`) is `search.keyword_statement_timeout_ms` (#6495; default 8000, range 1000-60000), resolved once per connection by `keywordStatementTimeoutSetting()` on the first keyword statement (`postgres-engine/keyword-statement-timeout.ts`: the `EngineConfig.keyword_statement_timeout_ms` value the engine connected with, else the DB plane's row read by one parameterless pool statement so no pg-types cache entry is described and `connect()` issues nothing for it, else the default; never a request parameter), with `countKeywordPages` keeping a caller's narrower `timeoutMs`. Every search transaction (keyword, keyword chunks, CJK, title, the vector attempts and the vector `hasMore` witness) also passes `jitOff` and runs with `jit = off` (`postgres-engine/search-settings.ts`): the correlated visibility subplans push these short reads past the JIT cost thresholds, and LLVM compilation, not execution, dominated their latency on large brains. Inside a caller's transaction the search runs in a savepoint and restores the caller's `jit` afterwards. Pinned by `test/e2e/search-query-contract-postgres.test.ts`. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). When the DDL pool has more than one slot, `initSchema` reserves one backend and runs the advisory lock 42 acquire, the bootstrap, the schema replay and the unlock on it, releasing it in `finally` (checkout gauge only, no long-hold permit, so pending `transaction: false` migrations can still reserve); a one-slot pool is already a single backend and runs unreserved. Pinned by `test/e2e/postgres-initschema-advisory-lock.test.ts`. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`). #6278 PR 1.5: `runUnsafe` arms a settle timer after a signalled statement's `cancel()`; a statement still pending `cancelSettleMs()` later (`GBRAIN_CANCEL_SETTLE_MS`, default 2000) has its reserved connection discarded so the awaiting caller settles with `CONNECTION_DESTROYED` instead of parking on a round-trip a transaction-mode pooler never completed (backend in `ClientRead`). For excludePrivate callers `searchKeyword` runs its full-text match in an `OFFSET 0` subquery (`search/keyword-chunk-match.ts`): inside the join the private-visibility subplans inflate every candidate plan's cost, so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (about 1.1 s for a common term at 250k chunks); local callers keep the unfenced, parallel-capable join. Rows, order and scores are pinned on both engines by `test/search/keyword-arm-ranking.test.ts` (golden `test/fixtures/keyword-arm-ranking.json`, which also pins one keyword statement per search and two when the strict query matches nothing and the OR fallback runs) and its Postgres twin `test/e2e/keyword-arm-ranking-postgres.test.ts`.Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`), written as parity twins of the PGLite methods (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, transaction routing). Migrated domains are one-line delegations over the private `engineSql` getter (a fresh adapter over `this.sql` on every access); reads that were RLS-scoped on master keep their own `withScopedReadTransaction` call and hand engine-sql `scopedRead(this.engineSqlOn(tx))`, an adapter over the scoped handle; `runUnsafe` forwards `prepare`/`simple` only when the engine-sql adapter sets them.- `src/core/snapshot-schema-inputs.ts` — the inputs of the PGLite snapshot schema hash (`computeSnapshotSchemaHash` in `pglite-engine.ts` hashes each file's raw bytes). Computed, not hand-kept: the static import closure (`import`, `export ... from`; type-only imports skipped) of `SNAPSHOT_SCHEMA_ROOTS` (`pglite-schema.ts`, `schema-migrations/registry.generated.ts`, `migrate.ts`, `engine-sql/bootstrap.ts`) plus `SNAPSHOT_SCHEMA_LEAVES`; every literal dynamic `import()` inside the closure must be classified as a leaf or in `SNAPSHOT_DYNAMIC_IMPORTS_NOT_HASHED`. Pure (the caller supplies file access). `test/snapshot-inputs-closure.test.ts` names any missing file and checks every `pglite-snapshot-*` CI cache key covers the same inputs.diff --cc src/core/behavior-change-notice.tsindex 71aec6372b,4793c3965f..3bb590361a--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -481,26 -481,12 +481,32 @@@ export const BEHAVIOR_CHANGES: Readonly{ 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.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.' },+ // Low-hanging-fruit wave (GBRA-81 items 1 and 1b).+ { since: '0.60.187.0', text: '`query` now expands only when the search mode says so: on in `tokenmax`, off in `balanced` (the default) and `conservative`, so `query` on a `balanced` brain no longer makes an expansion LLM call before retrieval. `expand: true` (CLI `--expand`) expands one call in any mode, and `gbrain config set search.expansion true` restores expansion by default for the brain; `expand: false` (`--no-expand`) still skips it. A `search.expansion` value set earlier, which `query` used to ignore, now takes effect on `query`; `gbrain search modes` shows it. `search` never expands, as before. CRAG escalation now reads whether the first pass actually expanded (`expansion_applied`), and eval capture records the `expand` the caller sent (null when unset) so `gbrain eval replay` replays the mode default.' },+ { since: '0.60.187.0', text: '`gbrain init --search-mode <conservative|balanced|tokenmax>` records the operator\'s choice: no recommendation, no first-run `search_mode` question, and `search.mode_source: operator` (picker choices record `auto`, and `gbrain config set search.mode` records `operator`). On a brain that already has a different mode it refuses unless `--force`. Init now recommends `balanced` instead of `conservative` when a reranker is ready but no chat key exists, and provider keys saved in `~/.gbrain/config.json` count toward the recommendation. The install matrix now prices Haiku 5.5, Sonnet 5.5 and Opus 5.5 from gbrain\'s pricing table (about a 200x corner-to-corner spread), and switching modes no longer promises a cache refill while semantic result caching is off.' },+ // Low-hanging-fruit wave (GBRA-81 items 2 and 3).+ { since: '0.60.187.0', text: 'Lean `search` and `query` rows (remote callers) now carry `id`, the `fetch` key, only when the connection can call `fetch` at that moment: a `full` surface, a stdio session `request_tools` widened, or an HTTP client whose surface and scopes include it. On `starter` and `verbs` connections, `fetch` was never callable, so the row\'s `slug` and `source_id` identify the page; `fields: "full"` returns every field, `id` included, and the `mcp.result_rows: full` host setting does so for every remote caller. Lean-row `score` now prints 4 significant digits. The local CLI and gbrain\'s thin client keep full rows, unchanged. `fetch` called without an id now says to re-run `search` once `fetch` is callable, or to pass the row\'s slug.' },+ { since: '0.60.187.0', text: 'On stdio MCP and the CLI, the `degraded_recall` notice now shows on every call a transient degradation affects (`rerank_failed`, `embed_timeout`, a failed keyword or title arm, and every other per-call stage); it used to show once per session, so a rerank failure after an earlier embedding timeout returned fused-order results with no notice. A keyless brain whose only degradation is `embed_unavailable` still shows it once per session. HTTP is unchanged: every affected call. `_meta.retrieval.degraded` still records every call\'s stages.' },+ // wave 16 (GBRA-79). `since` is provisional at the current VERSION; the integrator restamps it to the merge-slot version.+ { since: '0.60.185.0', text: 'A page purge (`gbrain delete <slug> --purge`) now searches the source\'s write journal for the page\'s claims at preparation, in bounded keyset chunks under the preparation budget (`persistence.maintenance_preparation_ms`), and its publication transaction only re-checks the requests admitted or settled since; the receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`), and `complete: false` means a cap was hit and some requests were not tested. A purge whose remaining in-transaction lookup times out now ends `failed` with `purge_lookup_timeout` (nothing removed, tombstoned or redacted; later writes to the source move again) instead of being requeued as `database_contention` without bound, and a sweep that outruns its budget twice ends `preparation_stalled`; either failure needs a new request_id. A schema migration adds the request-table slug index (`gbrain repair request-indexes` rebuilds it).' },+ { since: '0.60.185.0', text: 'A soft delete (`delete_page`, `gbrain delete <slug>`) of a page whose canonical file another live page of the source records now keeps the file and publishes database-only (receipt `write_through.skipped: shared_origin`, with a warning): the selected database page is hidden; the file and the surviving page remain, and nothing is erased. It used to refuse `source_changed` (the shared file renders the other page), leaving no supported exit for a duplicate-origin twin. Managed sync\'s discovery census and its origin guards now apply one rule: a live page wins the origin over tombstones, several live pages refuse `page_identity_changed` naming that soft delete, a single tombstone may still be reused and several tombstones still refuse. The receipt names the surviving slug to the trusted local owner or to a remote writer whose grant and visibility cover it, never otherwise. A purge of a shared-origin page refuses and names the soft delete. The kept file is imported into the surviving page by the next sync that imports it (`gbrain sync --source <id> --no-pull --full` does it now); edit the file first if it holds the deleted page\'s text.' },+ // wave 16 (GBRA-79). `since` is provisional at the branch VERSION; the integrator restamps it at the merge slot.+ { since: '0.60.185.0', text: 'A managed sync checkpoint whose cursor another run of the same source replaced (a `--retry-failed` rediscovery or a newer sync) now refuses `sync_cursor_replaced` (receipt state `conflict`) instead of `revision_conflict`, the run that awaited it records no managed-sync failure for it and goes on with the winning cursor, and `--retry-failed` no longer treats the superseded checkpoint as a page fault; `gbrain doctor` stops reporting such a checkpoint as an unresolved sync failure. A same-run index lag still reports `revision_conflict` and a missing manifest `storage_error`.' },+ { since: '0.60.185.0', text: 'A write a database trigger gbrain does not know refuses now carries a closed `reason` in its public failure detail (`attribution_unclassified_table`, `trust_unclassified_table`, `graduation_in_progress`, or `unknown`), its stored message reads `Publication failed (P0001 in <raiser>: <reason>). Inspect owner diagnostics.`, and the engine-graduation fence (SQLSTATE 55000) is recognized as `graduation_in_progress` with a retry-later message instead of an owner-exception `storage_error`. The managed sync failure a run records, the failure ledger, `gbrain doctor` and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail`) now name the raiser, table and reason that only the receipt named before; the trigger\'s message text stays on the brain host (`gbrain write-request <id> --json`).' },+ { since: '0.60.185.0', text: 'Managed sync bookkeeping recorded under a source incarnation the source no longer has (a source re-pointed at a new checkout, or removed and added again) is now retirable: `gbrain repair managed-sync-orphans --source <id>` lists such cursor and failure rows as `incarnation_retired` and local ledger rows whose durable failure row is gone as `mirror_only`, and a successful sync prunes a source\'s stale mirror rows. `gbrain doctor` names them with the repair even when no current failure is visible; `gbrain doctor --fast` (no database) now reports mirrored managed rows as `warn` "could not be verified" instead of `fail` (a better fast score is less certainty, not recovery; the engine-backed check stays authoritative), while old unmanaged file failures keep their severity. `gbrain sync status` reports only a cursor a current sync can select: an old-incarnation cursor is `cursor: null` with `last_error.code: cursor_incarnation_retired` and the repair preview as `next`, instead of a resumable cursor whose `next` selected nothing.' },+ // wave 16 (GBRA-79)+ { since: '0.60.185.0', text: 'On a managed brain, automatic fact extraction (sync import, `put_page`, `extract_facts`, the sweep) now skips a candidate whose exact claim was forgotten in that source and visibility and publishes the other facts of the same entity, counting the skips as `withdrawn_skipped` on the entity and completion write receipts and the extraction result; before, one forgotten claim refused the entity\'s whole group with `fact_withdrawn`. Explicitly remembering the forgotten claim still refuses, and a purge tombstone still refuses the whole write. A claim forgotten after the facts were prepared refuses that entity\'s write with `revision_conflict` and a detail naming the withdrawal, publishing nothing. An extraction keyed by its input alone (no request id) recovers from such a refusal, and from a batch an older release refused for a forgotten claim, on its next run: the retained facts are re-admitted as a follow-up batch with no model call, at most three times per batch, and the refused receipts stay as they were. An extraction admitted under a request id replays its receipt; a new request_id extracts again.' },+ { since: '0.60.185.0', text: 'Atom extraction (`extract_atoms`, `gbrain dream --drain`) no longer marks an item complete when its text was cut at `cycle.extract_atoms.max_input_chars` (default 50,000 characters). The model reads the head once and its atoms are kept, but no completion stamp is written, no atom from an earlier extraction is retired, the phase result and the drain count the item under `input_truncated` with a stderr line naming the knob, and the item is skipped with no model call until the cap is raised or its content changes; raising the cap makes every such item eligible again on the next run. Before, a cut item was certified complete on its full content and a re-extraction could retire the atoms a larger cap had produced from its tail.' },+ { since: '0.60.185.0', text: 'With the `claude-cli` provider, a model answer Claude Code reports as "API Error: Claude\'s response exceeded the N output token maximum" is now treated as an answer that stopped at the output cap (`finishReason: length`), not as a provider failure, so the output-cap ladders run as designed: open-loop extraction (`loops_extract`) retries once at 8192 output tokens and fact extraction retries once at twice its output budget. Each retry is one more model call on the same input; every other claude-cli error envelope still fails the call.' },+ { since: '0.60.185.0', text: 'The same-page rewording measurement (`would_dedup_same_page`, 0.60.177.0) now also runs on a managed brain: automatic fact extraction there counts the rewordings on the entity and completion receipts and the `extract_facts` result and prints the same one stderr line per match. Nothing is dropped; a replay of the same request reports the recorded count without a model call.' },+ // wave 16 (GBRA-79) G5.1 #6495. `since` is provisional at the current VERSION; the integrator moves it to the merge-slot stamp.+ { since: '0.60.185.0', text: 'On Postgres, the keyword, keyword-count, keyword-page, title and CJK search statements run under one operator bound, `search.keyword_statement_timeout_ms` (default 8000, range 1000-60000; `gbrain config set`, then restart `gbrain serve` or the workers), instead of a fixed 8 s; a value outside the range is refused and never set from a request. `gbrain doctor` gains `keyword_plan`, a read-only canary that warns when the brain\'s commonest keyword term cannot be counted inside the bound (one term is not workload coverage, and a timed-out count is never "no matches"). A longer bound buys time, not a cheaper statement (#6495 stays open).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */