Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): cut serve, read-transaction and post-rerank round trips
garrytan8561b4154c1f
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex ddb596876c..77494b8c8e 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/search/crag.ts` + `src/core/search/hybrid/rerank-gate.ts` — the CRAG retrieval-confidence grade on the final list (`gradeRetrievalConfidence`, read by the `query` op's `crag` meta and escalation) and the W3 rerank gate's PRE-rerank grade. `gradePreRerank` is pure and reads the deduped candidates in fused order plus the identity lookups, never mutating them: strong is exactly one exact-lookup page, else exactly one full-query alias page, else a full-title identity at rank 1 (normalized title equals the normalized query; a phrase inside a longer title is not identity), else `high_vector_match` (rank-1 raw cosine ≥ `search.evidence_cosine_floor`) whose gap over the best cosine of a DIFFERENT page (image rows excluded; rank-1's own chunks never count) is at least δ (`search.reranker.gate_min_gap`, 0.05). More than one identity page, or a single-token alias hop that would move rank 1, is `identity_ambiguous`; multimodal queries and image rows are never strong; `applyRerankGateTrust` demotes a strong page below `max(caller min_trust, unknown)` to `below_trust_floor`. `RERANK_GATE_SKIP_REASONS` (only `high_vector_match`) decides `would_skip`; title, alias and exact-lookup strengths are `skip_blocked: shadow_only_reason`, and an active System One rerank slot is `decide_rerank_slot`. `prepareRerankGate` (the stage) runs only when `search.reranker.gate` is not `off`, alongside the reranker call: it reads `lookupAliasHop` and `structuralExactLookup` once, grades, reads rank-1's page tier through `stampPageTrust` on a copy, and returns `meta.rerank_gate` (`mode`, `eligible`/`ineligible_reason` — reranker off, egress denied, no candidates — `grade`, `reason`, `top_cosine`, `gap`, `candidates`, `would_skip`, `skip_blocked`, `provider_called`) plus the lookups, which `sizeReturnPool` applies (`applyAliasHopLookup`, `applyExactLookupHits`) instead of looking up again. `shadow` results, provider payloads and lookup counts are identical to `off`. Pinned by `test/search/rerank-gate-grade.test.ts`, `test/search/rerank-gate-hybrid.test.ts` (both engines), `test/search/rerank-gate-knobs.test.ts`, `test/search/rerank-gate-telemetry.test.ts` (both engines).+- `src/core/search/crag.ts` + `src/core/search/hybrid/rerank-gate.ts` — the CRAG retrieval-confidence grade on the final list (`gradeRetrievalConfidence`, read by the `query` op's `crag` meta and escalation) and the W3 rerank gate's PRE-rerank grade. `gradePreRerank` is pure and reads the deduped candidates in fused order plus the identity lookups, never mutating them: strong is exactly one exact-lookup page, else exactly one full-query alias page, else a full-title identity at rank 1 (normalized title equals the normalized query; a phrase inside a longer title is not identity), else `high_vector_match` (rank-1 raw cosine ≥ `search.evidence_cosine_floor`) whose gap over the best cosine of a DIFFERENT page (image rows excluded; rank-1's own chunks never count) is at least δ (`search.reranker.gate_min_gap`, 0.05). More than one identity page, or a single-token alias hop that would move rank 1, is `identity_ambiguous`; multimodal queries and image rows are never strong; `applyRerankGateTrust` demotes a strong page below `max(caller min_trust, unknown)` to `below_trust_floor`. `RERANK_GATE_SKIP_REASONS` (only `high_vector_match`) decides `would_skip`; title, alias and exact-lookup strengths are `skip_blocked: shadow_only_reason`, and an active System One rerank slot is `decide_rerank_slot`. `rerankAndPin` starts `readIdentityLookups` (alias and exact lookups, any gate mode) alongside the reranker; `sizeReturnPool` applies them. `prepareRerankGate` (the stage, gate not `off`) grades with them, reads rank-1's page tier through `stampPageTrust` on a copy, and returns `meta.rerank_gate` (`mode`, `eligible`/`ineligible_reason` — reranker off, egress denied, no candidates — `grade`, `reason`, `top_cosine`, `gap`, `candidates`, `would_skip`, `skip_blocked`, `provider_called`). `shadow` results, provider payloads and lookup counts are identical to `off`. Pinned by `test/search/rerank-gate-grade.test.ts`, `test/search/rerank-gate-hybrid.test.ts` (both engines), `test/search/rerank-gate-knobs.test.ts`, `test/search/rerank-gate-telemetry.test.ts` (both engines).- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | rate_limited | unreachable | auth | provider_error` (gateway `rate_limit` → `rate_limited`, a transport failure with no HTTP response → `unreachable`, 401/403 → `auth`, 5xx and everything else → `provider_error`; Cat 40 R0, pinned on the real wire by `test/rerank-failure-reason.serial.test.ts`), which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.@@ -32,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.- `src/core/link-ranking-policy.ts` — the link-type ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer.-- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it by a ranking link type, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.+- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it by a ranking link type, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Its page read (`readGeneratedPages`) starts before `runPostFusionStages`. Tests: `test/search-provenance-demotion.test.ts`.- `src/core/search/frontmatter-where.ts` + `src/core/ops/where-param.ts` — the `where` frontmatter equality filter on `search`, `query`, `list_pages` (#7159; CLI `--where key=value`). Bounded keys and values, else `invalid_params`; each value is a bound `p.frontmatter @> $n::text::jsonb` test (GIN-served), pushed into every SQL leg; a filtered call skips the hybrid cache and `keepFrontmatterMatches` re-checks the other arms. Tests: `test/search-frontmatter-where.test.ts`, its e2e parity file.- `src/core/search/filter-hint.ts` — one `search_filter_hint` info notice per session when a first-page `search`/`query` names a type or time it did not filter on, or one type fills its top rows. Never changes results.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 1bfa50c4a9..2d0c277458 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -50,7 +50,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate (projection_by_design when the only unsealed pages in scope are protected-OCR images, #6803). Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local; a lean row keeps `id` only when `ctx.isCallable('fetch')`, the MCP dispatch predicate `buildOperationContext` threads in, says the caller can call `fetch` (unset keeps it), and prints `score` at 4 significant digits) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). Each handler times its request (`SearchTimings`, search/stage-timings.ts) and `searchOutput` emits `retrieval.timings` last. The typed-search type check lives in `ops/search-type-filter.ts` (`reconcileTypeFilter`): one statement of per-type `EXISTS` probes over each type's schema-expanded set, with the `DISTINCT` type list for the `type_filter_notice` evaluated only when a probe misses, run `jitOff` and unprepared (a generic plan scans every page per missing type); pinned by `test/search-type-filter-reconcile.test.ts` and `test/e2e/typed-search-jit-postgres.test.ts`. `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`); `coverage` counts pending, held and embedding-held items with `could_affect` (`search/retrieval-coverage.ts`). Its safe-index probe, projection readiness, entity saved facts, saved-fact match and held-file coverage run concurrently, each with its own catch; the answer-feedback write runs after them (`test/search-response-meta-concurrency.test.ts`).+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate (projection_by_design when the only unsealed pages in scope are protected-OCR images, #6803). Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local; a lean row keeps `id` only when `ctx.isCallable('fetch')`, the MCP dispatch predicate `buildOperationContext` threads in, says the caller can call `fetch` (unset keeps it), and prints `score` at 4 significant digits) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). Each handler times its request (`SearchTimings`, search/stage-timings.ts) and `searchOutput` emits `retrieval.timings` last. The typed-search type check lives in `ops/search-type-filter.ts` (`reconcileTypeFilter`): one statement of per-type `EXISTS` probes over each type's schema-expanded set, with the `DISTINCT` type list for the `type_filter_notice` evaluated only when a probe misses, run `jitOff` and unprepared (a generic plan scans every page per missing type); pinned by `test/search-type-filter-reconcile.test.ts` and `test/e2e/typed-search-jit-postgres.test.ts`. `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`); `coverage` counts pending, held and embedding-held items with `could_affect` (`search/retrieval-coverage.ts`). Its safe-index probe, projection readiness, entity saved facts, saved-fact match and held-file coverage run concurrently, each with its own catch; the answer-feedback write runs after them (`test/search-response-meta-concurrency.test.ts`). The saved-fact match is one statement: an uncorrelated `EXISTS` probe (a one-time filter) skips its `LIKE ANY` scan when no fact qualifies. The handlers start the alias fan-out's `resolveQueryEntity` alongside the hybrid search, and `evidenceOutput` reads page trust (`loadPageTrust` over the rows every delivered row is copied from) alongside evidence delivery (`test/search-post-rerank-concurrency.test.ts`).- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.mdindex ebe1e30423..9a65015fb7 100644--- a/docs/architecture/key-files/entity-recall.md+++ b/docs/architecture/key-files/entity-recall.md@@ -21,7 +21,7 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).- `src/core/verbs/entity-names.ts` — `entity` with `names` (up to `ENTITY_NAMES_MAX` 50): `lookupEntityNames` reads `entityLookupScope` once per batch, then resolves each name through the card's candidate selection (`selectEntityCandidates`, no card assembled), 8 at a time, deduped in first-seen order, into compact rows `{name, found, slug, title, type, aka, lead, siblings?}`; the lead comes from the candidate row's bounded, withdrawal-overlaid `compiled_truth` prefix (`page-window/bounded-lead.ts`), siblings from `readSiblingIdentity` with the batch's policy and pack. Output is byte-identical to the old full-card path (`test/entity-names-parity.test.ts`, Postgres twin `test/e2e/entity-names-parity-postgres.test.ts`, fixtures and the reference resolver in `test/helpers/entity-names-parity.ts`). `pageLead` is the body's opening prose from `boundedProjectedPrefix` (the 64 KiB prefix, sanitized and credential-projected) plus secret redaction, headings, markers and table rows dropped, `ENTITY_LEAD_CHARS` 200. `attachReferences` adds `referenced_by_count`, the card `next` and `records` to every found page and sibling from one `readRowReferences` call. Tests: `test/entity-names.test.ts`, `test/entity-names-parity.test.ts`, `test/entity-records.test.ts`.- `src/core/verbs/entity-references.ts` — the F1 reference fields on compact rows: `readRowReferences` (config gate per surface `names` / `pack` / `full_card`, `REFERENCES_DEADLINE_MS` 2 s cooperative deadline, `references_unavailable` marker + degraded notice, per-type `next` to `get_backlinks` returning exactly the rest, `record_types_undeclared` notice), `readPackReferences` (context_pack pull verb only: card page + identity siblings), `renderRecordLines` / `RECORDS_HEADER` (packed text, "page date"). Config: `src/core/entity-references-config.ts` (`entity.names_references` default on, `entity.record_types` default empty). Tests: `test/entity-records.test.ts`, `test/e2e/entity-records-postgres.test.ts`.- `src/core/verbs/entity-card-identity.ts` — the `entity` card's `aka_sources`, `identity_siblings`, `identity_excerpt` (verbatim lines of the page and its siblings from `sanitizeRemoteBody`, tiered: declarations, label lines with a name-like value, other label lines, lines with another capitalized run or code; 600 characters per page, 1,200 per card, `identity_excerpt_omitted`), `alias_guidance` (surface-aware) and the `identity_siblings_capped` notice. A segmented page is excerpted from its trusted, withdrawal-overlaid lead (`truthLead`, `EXCERPT_LEAD_BYTES` = 64 KiB, cut back to a whole line), never its body getters; the card equals the inline page's when the qualifying lines sit in that lead (`test/large-pages/segmented-read-refusals.test.ts`). `readSiblingIdentity` is its siblings-and-aliases half (one alias read for the page and its siblings; optional preloaded mention policy and pack), used alone by `entity names[]`. Tests: `test/mentions-identity-siblings.test.ts`.-- `src/core/search/alias-fanout.ts` — search and query's alias fan-out: `resolveQueryEntity` (query n-grams up to 4 tokens through `resolveAliases` and linkable exact titles, longest first, capitalized or code-shaped unless a multi-word n-gram resolves to one page, case-sensitive aliases as written, a tie only when the pages are identity siblings), the names of the entity and its siblings by origin then length, at most `search.alias_fanout_max` (4) keyword queries of 5 rows (`searchAliasRequired`: the name as a required websearch phrase, ranked by the query's other terms through `SearchOpts.rankQuery` on both engines), at most 8 spliced rows with `matched_alias`, and the `fanout` meta (`alias_fanout` notice when capped). Offset 0 only. Tests: `test/search-alias-fanout.test.ts`, `test/search-other-names.test.ts`, `test/e2e/mentions-parity.test.ts`. `wholeQueryEntityNames`: when the whole query is one entity's name or alias, `match: "keyword"` lists pages matching any of its names (one websearch OR of phrases; `match_names` in the meta and the count line; rows found by another name carry `matched_alias`). `resolveQueryEntities` returns every entity a text names; its alias, linkable-title and case-sensitive alias reads run concurrently (`test/search-entity-resolve-concurrency.test.ts`).+- `src/core/search/alias-fanout.ts` — search and query's alias fan-out: `resolveQueryEntity` (query n-grams up to 4 tokens through `resolveAliases` and linkable exact titles, longest first, capitalized or code-shaped unless a multi-word n-gram resolves to one page, case-sensitive aliases as written, a tie only when the pages are identity siblings), the names of the entity and its siblings by origin then length, at most `search.alias_fanout_max` (4) keyword queries of 5 rows (`searchAliasRequired`: the name as a required websearch phrase, ranked by the query's other terms through `SearchOpts.rankQuery` on both engines), at most 8 spliced rows with `matched_alias`, and the `fanout` meta (`alias_fanout` notice when capped). Offset 0 only. `resolving` takes the handler's `resolveQueryEntity` started before the search, so its reads overlap it. Tests: `test/search-alias-fanout.test.ts`, `test/search-other-names.test.ts`, `test/e2e/mentions-parity.test.ts`. `wholeQueryEntityNames`: when the whole query is one entity's name or alias, `match: "keyword"` lists pages matching any of its names (one websearch OR of phrases; `match_names` in the meta and the count line; rows found by another name carry `matched_alias`). `resolveQueryEntities` returns every entity a text names; its alias, linkable-title and case-sensitive alias reads run concurrently (`test/search-entity-resolve-concurrency.test.ts`).- `src/core/search/entity-facts.ts` — `entitySavedFacts`: when a search names an entity, its newest active saved facts (`factEntitySlugs`, 5) lead the model-visible saved-facts block, then up to 3 facts each of up to 2 entities those facts name (`linked_from`), before the word-overlap matches. Same active, audit-row and visibility rules as recall. Tests: `test/memory-sibling-facts.test.ts`.- `src/core/schema-migrations/v206-entity-mention-index.ts` — additive: `page_aliases.origin` (`frontmatter` default, `declared`, `subject`), `case_sensitive`, `alias_text`, unique key `(source_id, alias_norm, slug, origin)`; tables `page_mention_state`, `mention_gazetteer_entries`, `mention_index_status` (RLS on when the role bypasses RLS). `GUARDED_TABLE_COLUMNS` lists the new `page_aliases` columns.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex df46d8c739..4047bb892d 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -49,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed); `NO_SOURCES = '__none__'` is the explicit no-source legacy-token grant, refused rather than translated. `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.-- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating. A request snapshot serves tiers 4, 5.5 and the federated set from one sources read.+- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating. A request snapshot serves tiers 4, 5.5 (its rows carry the 'default' emptiness probe, `default_has_pages`), `assertSourceExists` and the federated set from one sources read, sent with the config table (`resolveSourceWithTier` reads tier 5's key beside the tier-4 listing) (GBRA-156).- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`, `sources purge`, the `sources_remove` op, expired-archive purge) deletes the `sources` row and that incarnation's `persistence_source_bindings` row in one statement; bindings have no FK to `sources`. Bindings of other incarnations are left to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only a binding of the source's current incarnation. `EXPIRED_ARCHIVE_SQL` is the one purge-eligibility predicate (unmanaged sweep, its per-row DELETE and the managed `expiredOnly` purge): both archive timestamps must be later than the epoch and the expiry past; `UNVERIFIED_ARCHIVE_SQL` lists archived rows with a missing or epoch timestamp, which the sweep reports blocked with restore-then-archive guidance instead of purging.- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling. #6946: `isOwnedClone`/`defaultCloneDir` live in `src/core/url-clone.ts`, re-exported here.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex 11a648c181..c6a3aa71dc 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority.+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)` (a read op (`mutating === false`) runs inside `withRequestConfigSnapshot`, a write op under `withoutRequestConfigSnapshot`; `src/core/config-snapshot.ts`), `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts`; for a read op on a live engine it runs beside the handler instead of after it (GBRA-156), and reads its withdrawal watermark and trust generation in one round trip — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v230: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`). Large pages: after a read's result is assembled (notices and `_meta` included), `frameOverCap` measures the final encoded frame against the connection's cap and replaces an oversized read with `result_too_large` (writes are never replaced); `DispatchOpts.thinClient` (from `X-Gbrain-Client` on both HTTP transports) reaches `OperationContext.thinClient`, a default-body-mode hint, never authority.- `src/core/egress-budget.ts` — the per-connection result cap: `resultByteCap` (Infinity for the trusted local CLI; else `mcp.max_result_bytes_stdio` 4 MiB / `mcp.max_result_bytes_http` 1 MiB, DB plane then file plane, clamped to 256 KiB–9 MiB), `encodedFrameBytes` (the complete JSON-RPC frame plus a framing reserve), and the dispatcher backstop pair `frameOverCap` / `resultTooLargeError`.- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge. The brief clause puts the `referenced_by` walk on the single-name `entity` card and names only the fields compact `names` rows carry on the brain (`references: {namesRow, records}`, read at every per-initialize call site by `readInstructionContent` from `src/core/entity-references-config.ts`; the static contract is the defaults rendering; `test/mcp-instructions-references.test.ts`). Instruction 7's governing rule (`mcp.instructions_governing_rule`: `in_effect` default, `newest` the earlier recency sentence) leads the answering clause so it ends inside the first 2,048 characters (`test/mcp-instructions-governing-rule.test.ts` records its offset per surface).@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.-- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.+- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`. Each tool call resolves its source inside one request config snapshot that dispatch reuses for a read op (the config table is read alongside the source rows), so the pre-op reads cost one round trip (GBRA-156).- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.diff --git a/scripts/bench/retrieval-scale/run.ts b/scripts/bench/retrieval-scale/run.tsindex f0ada3257a..440e063944 100644--- a/scripts/bench/retrieval-scale/run.ts+++ b/scripts/bench/retrieval-scale/run.ts@@ -25,6 +25,9 @@* -> last reply) and tail (last reply -> exit), plus round trips.* warm one long-lived gbrain serve stdio MCP process; per-stage search* timings come from _meta.retrieval.timings.+ * socket one long-lived `gbrain serve --cli-socket` and a CLI process per+ * sample that answers through the warm socket (GBRAIN_CLI_SOCKET=1),+ * the path a shell-out agent pays once a serve is running.** Queries are 2-4 generated words from a random page body plus, for half of* them, a word of its title: synthetic text only. Rows carry timings and@@ -155,6 +158,26 @@ async function main() {}}+ if (modes.includes('socket')) {+ const proc = Bun.spawn([process.execPath, CLI, 'serve', '--cli-socket'], { cwd: REPO, env: { ...env, GBRAIN_CLI_SOCKET: '1' }, stdin: 'pipe', stdout: 'ignore', stderr: 'pipe' });+ let serveErr = '';+ (async () => { const dec = new TextDecoder(); for await (const c of proc.stderr as ReadableStream<Uint8Array>) serveErr += dec.decode(c); })();+ for (let waited = 0; !serveErr.includes('cli-socket: listening') && waited < 60_000; waited += 250) await new Promise(r => setTimeout(r, 250));+ if (!serveErr.includes('cli-socket: listening')) throw new Error('serve --cli-socket did not start: ' + serveErr.slice(-400));+ for (const op of ops) {+ for (let i = 0; i < WARMUP; i++) await runCli(cli[op]!(3000 + i), { GBRAIN_CLI_SOCKET: '1' });+ const samples: Sample[] = [];+ for (let i = 0; i < N; i++) {+ const r = await runCli(cli[op]!(i), { GBRAIN_CLI_SOCKET: '1' });+ samples.push({ ms: r.ms, ok: r.code === 0 });+ }+ add(op, 'socket', samples);+ }+ try { (proc.stdin as any).end(); } catch { /* closed */ }+ proc.kill();+ await proc.exited;+ }+if (modes.includes('warm')) {const warmTrace = join(home, 'trace-serve.jsonl');const profDir = flag('--serve-cpu-prof');diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 75884ada01..51cd51e6dd 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,7 +21,7 @@ src/core/import-file.ts 2075 ratchet +2 W1 belief ledger: the legacy import is asrc/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 244 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact importsrc/core/pglite-engine.ts 3087 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move)-src/core/postgres-engine.ts 3117 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured)+src/core/postgres-engine.ts 3135 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured)src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.tssrc/core/types.ts 2347 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured)src/core/minions/queue.ts 2544 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured)diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex b3a74bb6be..fbafe4880a 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -529,7 +529,7 @@ src/core/search/entity-anchor.ts entityAnchoredPages sql STREAMsrc/core/search/evidence-delivery.ts deliverEvidence field STREAM inline pages: the fence overlay over the whole body; a segmented page (no body) skips it and is planned from windows (search/segmented-evidence.ts)src/core/search/evidence-delivery.ts selectLongPages sql META sizes a segmented page from its NULL body (0), so it is never selected as a long page; moves to body_bytessrc/core/search/provenance-demotion.ts applyGeneratedDemotion field LEAD-src/core/search/provenance-demotion.ts applyGeneratedDemotion sql LEAD+src/core/search/provenance-demotion.ts readGeneratedPages sql LEADsrc/core/search/read-enrichment.ts readAliases sql NONE not the page body: SELECT * FROM pages used for identity columnssrc/core/search/read-enrichment.ts readChainHop sql META SELECT * FROM pages by id; protectedBodyFilter(ev) reads body_flags for a segmented pagesrc/core/search/relational-recall.ts hydrate field LEAD synopsis from boundedBodyPrefixSqldiff --git a/src/core/cli-socket/execute.ts b/src/core/cli-socket/execute.tsindex ba7113ad3f..3581a933d7 100644--- a/src/core/cli-socket/execute.ts+++ b/src/core/cli-socket/execute.ts@@ -39,8 +39,10 @@ export async function mergedRequestConfig(engine: BrainEngine): Promise<GBrainCo/** The CLI's OperationContext for one request: makeContext's fields, with the caller's routing. */export async function cliRequestContext(engine: BrainEngine, params: Record<string, unknown>, op: Pick<Operation, 'params'>,- request: Pick<CliSocketRequest, 'routing' | 'cli'>, config: GBrainConfig,+ request: Pick<CliSocketRequest, 'routing' | 'cli'>, config: GBrainConfig | Promise<GBrainConfig>,sinks: { emitResponseMeta: (key: string, value: unknown) => void; emitNotice: (notice: Notice) => void }): Promise<OperationContext> {+ const merged = Promise.resolve(config);+ merged.catch(() => {});let sourceId: string | undefined;let localFederated: string[] | undefined;let sourceImplicit = true;@@ -57,7 +59,7 @@ export async function cliRequestContext(engine: BrainEngine, params: Record<stri}return {engine,- config,+ config: await merged,logger: { info: (...args: unknown[]) => console.log(...args), warn: (...args: unknown[]) => console.warn(...args), error: (...args: unknown[]) => console.error(...args) },dryRun: (params.dry_run as boolean) || false,remote: false, admissionOrigin: 'interactive',@@ -101,7 +103,8 @@ async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { k};let stage = `gbrain ${request.command}: context`;try {- const ctx = await withTimeout(track(work, (async () => cliRequestContext(engine, params, op, request, await mergedRequestConfig(engine), sinks))()), wallclockMs, stage);+ // GBRA-156: the merged config and the source resolution read the request's snapshot together (one round trip).+ const ctx = await withTimeout(track(work, cliRequestContext(engine, params, op, request, mergedRequestConfig(engine), sinks)), wallclockMs, stage);stage = `gbrain ${request.command}`;const raw = await withTimeout(track(work, op.handler(ctx, params)), wallclockMs, stage);// src/cli/main.ts runSharedOperation: captureRetrievalNotices after the handler, before the JSON round trip.diff --git a/src/core/eligibility/stamp.ts b/src/core/eligibility/stamp.tsindex 7da14fe857..51fa90d638 100644--- a/src/core/eligibility/stamp.ts+++ b/src/core/eligibility/stamp.ts@@ -57,16 +57,18 @@ export async function loadPageTrust(engine: Exec, refs: readonly PageRef[]): Pro* page's tier is labeled with the marker tier (origin `facts-fence`) and is* held to the floor at that tier. The floor is already applied inside every arm's SQL; this is* the backstop for rows a stage adds by slug (exact lookup, alias hop, graph- * walk), so no row below the floor leaves the operation.+ * walk), so no row below the floor leaves the operation. `pageTrust` is+ * `loadPageTrust` started early over the rows these rows were copied from.*/-export async function stampPageTrust<T extends PageRef>(engine: Exec, rows: T[], floor?: TrustTier): Promise<T[]> {+export async function stampPageTrust<T extends PageRef>(engine: Exec, rows: T[], floor?: TrustTier,+ pageTrust?: ReturnType<typeof loadPageTrust>): Promise<T[]> {if (rows.length === 0) return rows;const factRows = rows.filter(row => typeof row.fact_row?.id === 'number');const factTrust = factRows.length ? await stampRowTrust(engine, 'facts', factRows, row => row.fact_row!.id) : [];factRows.forEach((row, i) => Object.assign(row, factTrust[i]));const pageRows = rows.filter(row => typeof row.fact_row?.id !== 'number');let found: Awaited<ReturnType<typeof loadPageTrust>> | null = null;- try { found = pageRows.length ? await loadPageTrust(engine, pageRows) : null; } catch { found = null; }+ try { found = pageRows.length ? await (pageTrust ?? loadPageTrust(engine, pageRows)) : null; } catch { found = null; }for (const row of pageRows) {const fields = (typeof row.page_id === 'number' ? found?.byId.get(row.page_id) : undefined)?? found?.byKey.get(key(row.source_id, row.slug))diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 215cb64fe0..13cc2998ea 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -1095,8 +1095,8 @@ export function cosineByChunkIdsStatement(ids: number[], column: string, query:const col = trustedSql(`cc.${quoteIdentifier(column)}`);const q = `[${Array.from(query).join(',')}]`;return renderFragment(sqlFragment`- SELECT cc.id, CASE WHEN vector_dims(${col}::vector) <> ${query.length}::int OR vector_norm(${col}::vector) = 0 OR vector_norm(${q}::vector) = 0- THEN 0::float8 ELSE 1 - (${col}::vector <=> ${q}::vector) END AS cosine+ SELECT cc.id, CASE WHEN vector_dims(${col}::vector) <> ${query.length}::int OR vector_norm(${col}::vector) = 0 OR vector_norm(${q}::text::vector) = 0+ THEN 0::float8 ELSE 1 - (${col}::vector <=> ${q}::text::vector) END AS cosineFROM content_chunks cc JOIN pages p ON p.id = cc.page_idWHERE cc.id = ANY(${ids}::int[]) AND ${col} IS NOT NULL AND ${trustedSql(chunkVisibleFilter('p', 'cc'))}`);diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.tsindex 3f23507c04..7ea0b43c74 100644--- a/src/core/facts/meta-hook.ts+++ b/src/core/facts/meta-hook.ts@@ -155,12 +155,16 @@ export async function getBrainHotMemoryMeta(// build that raced a forget or a trust transition stores the older value// and the next hit rebuilds. The eligibility is read after the generation:// a `trust.%` config change bumps it.+ // The two are independent, so they are sent together (one round trip).const generation = _generations.get(ctx.engine) ?? 0;- const withdrawals = await withdrawalWatermark(ctx.engine, sourceId);+ const withdrawalsRead = withdrawalWatermark(ctx.engine, sourceId);+ const trustGenerationRead = readTrustGeneration(ctx.engine);+ trustGenerationRead.catch(() => {});+ const withdrawals = await withdrawalsRead;let trustGeneration: string;let policy: Awaited<ReturnType<typeof proactiveEligibility>>;try {- trustGeneration = await readTrustGeneration(ctx.engine);+ trustGeneration = await trustGenerationRead;policy = await proactiveEligibility(ctx, 'hot_memory');} catch {return undefined;diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex e9a364157b..841cc7aaf0 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -54,7 +54,7 @@ import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts'import { pageReadFilter } from '../search/read-policy-sql.ts';import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION, SEARCH_MATCH_DESCRIPTION } from '../operations-descriptions.ts';import { declaredNames, titleName } from '../mentions/aliases.ts';-import { aliasPhrase, wholeQueryEntityNames, withAliasFanOut, type FanoutMeta, type ResolvedEntity } from '../search/alias-fanout.ts';+import { aliasPhrase, resolveQueryEntity, wholeQueryEntityNames, withAliasFanOut, type FanoutMeta, type ResolvedEntity } from '../search/alias-fanout.ts';import { entitySavedFacts } from '../search/entity-facts.ts';import { mentionCoverageNotice, readMentionCoverage } from '../mentions/coverage.ts';import { keepEnumeratedRows, keywordCountMeta, parseSearchPaging, readKeywordPage, startKeywordCount, withCountMeta } from '../search/keyword-paging.ts';@@ -63,7 +63,7 @@ import { heldFilesNotice, stampHeldHits } from '../persistence/held-reads.ts';import { opError } from './contract.ts';import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';import { projectionEligibleSql } from '../eligibility/sql.ts';-import { stampPageTrust } from '../eligibility/stamp.ts';+import { loadPageTrust, stampPageTrust } from '../eligibility/stamp.ts';import type { TrustTier } from '../trust/tier.ts';import type { Operation, OperationContext } from './contract.ts';import { invalidParam, paramUse, readFix } from './op-fix.ts';@@ -203,8 +203,11 @@ async function withEvidence(ctx: OperationContext, p: Record<string, unknown>, rasync function evidenceOutput(ctx: OperationContext, p: Record<string, unknown>, results: SearchResult[], plan: EvidencePlan | null, scope: DeliveryScope,meta: HybridSearchMeta | null, snippetCap: number, timings: SearchTimings, buildMeta: (rows: SearchResult[]) => Promise<Record<string, unknown>>, keepEnumerated = false): Promise<SearchResult[]> {return timings.stage('response', async () => {+ // Every returned row is a copy of one of `results`, so their page trust is read alongside evidence delivery.+ const pageTrust = loadPageTrust(ctx.engine, results.filter(r => typeof r.fact_row?.id !== 'number'));+ pageTrust.catch(() => {});const ev = await withEvidence(ctx, p, results, plan, scope, meta);- const rows = await stampPageTrust(ctx.engine, keepEnumerated ? keepEnumeratedRows(results, ev.rows) : ev.rows, scope.minTrust);+ const rows = await stampPageTrust(ctx.engine, keepEnumerated ? keepEnumeratedRows(results, ev.rows) : ev.rows, scope.minTrust, pageTrust);return searchOutput(ctx, p, rows, await buildMeta(rows), snippetCap, timings, ev.evidence);});}@@ -348,6 +351,17 @@ async function emitFanoutNotices(ctx: OperationContext, fanout: FanoutMeta | undif (notice) ctx.emitNotice?.(notice);}+/**+ * The alias fan-out's entity resolution depends on the query alone, so the+ * handlers start it before the search; withAliasFanOut awaits it with its own+ * error handling (the catch here only covers a search that throws first).+ */+function startEntityResolution(ctx: OperationContext, queryText: string, scope: SourceScope & { excludePrivate: boolean }): Promise<ResolvedEntity | null> {+ const resolving = resolveQueryEntity(ctx.engine, queryText, scope);+ resolving.catch(() => {});+ return resolving;+}+export interface SavedFactMatch { id: number; fact: string; entity_slug: string | null; kind: string; valid_from: string; source: string }/**@@ -367,28 +381,21 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, queconst excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);const visibility = `${ctx.remote !== false ? `AND f.visibility = 'world'` : ''} ${excludePrivate ? `AND ${privateProvenanceFilterFragment('f')}` : ''}AND ${projectionEligibleSql('facts', 'f', { floor: scope.minTrust })}`;- try {- // Most searches have no saved fact to find: one indexed probe (idx_facts_since) with the- // same active-fact and visibility predicates skips the LIKE ANY scan when no fact qualifies.- const any = await ctx.engine.executeRaw(- `SELECT 1 FROM facts f- WHERE f.source_id = ANY($1::text[])+ const active = `f.source_id = ANY($1::text[])AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())AND f.source != ALL($2::text[])- ${visibility}- LIMIT 1`,- [sources, [...AUDIT_ROW_SOURCES]],- );- if (any.length === 0) return [];+ ${visibility}`;+ try {+ // Most searches have no saved fact to find: the uncorrelated EXISTS is an indexed probe+ // (idx_facts_since) the planner runs once, before the LIKE ANY scan, and the scan is skipped+ // when no fact qualifies; one statement, so one round trip either way.const rows = await ctx.engine.executeRaw<SavedFactMatch & { haystack: string }>(`SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source,lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) AS haystackFROM facts f- WHERE f.source_id = ANY($1::text[])- AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())- AND f.source != ALL($2::text[])+ WHERE ${active}AND lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) LIKE ANY($3::text[])- ${visibility}+ AND EXISTS (SELECT 1 FROM facts f WHERE ${active} LIMIT 1)ORDER BY f.valid_from DESC, f.id DESCLIMIT 200`,[sources, [...AUDIT_ROW_SOURCES], terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`)],@@ -787,6 +794,7 @@ const search: Operation = {let capturedMeta: HybridSearchMeta | null = null;const searchDone = Promise.withResolvers<void>();const keywordCount = timings.overlap('keyword_count', startKeywordCount(ctx.engine, queryText, types, readOpts, searchDone.promise));+ const resolving = offset === 0 ? startEntityResolution(ctx, queryText, { ...scope, excludePrivate }) : undefined;const explainPrep = await setup(() => prepareExplainTarget(ctx, p, scope, excludePrivate, 'search'));const searchOpts = {limit,@@ -812,7 +820,7 @@ const search: Operation = {const declarations = new DeclarationMemo();const fanned = offset === 0? await timings.stage('alias_fanout', () => withAliasFanOut(ctx.engine, primary, queryText, { ...scope, excludePrivate },- { excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...scope }, () => declarations.scan(primary, queryText)))+ { excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...scope }, () => declarations.scan(primary, queryText), resolving)): { results: primary };let results = fanned.results.map(r => ({ ...r }));await emitFanoutNotices(ctx, fanned.fanout, scope);@@ -1005,7 +1013,7 @@ const query: Operation = {// cross-source mode (matches SearchOpts.sourceId contract).const typeFilter = await setup(() => reconcileTypeFilter(ctx, querySourceScope, excludePrivate, types));types = typeFilter.types;- let capturedMeta: HybridSearchMeta | null = null; let queryEmbedding: Float32Array | null = null;+ let capturedMeta: HybridSearchMeta | null = null; let queryEmbedding: Float32Array | null = null; const resolving = startEntityResolution(ctx, queryText, { ...querySourceScope, excludePrivate });const explainPrep = await setup(() => prepareExplainTarget(ctx, p, querySourceScope, excludePrivate, 'query'));// v0.32.x search-lite: route the query op through hybridSearchCached so// token budget and intent weighting apply at the operation boundary.@@ -1070,7 +1078,7 @@ const query: Operation = {const declarations = new DeclarationMemo();const primaryRows = results;const fanned = await timings.stage('alias_fanout', () => withAliasFanOut(ctx.engine, primaryRows, queryText, { ...querySourceScope, excludePrivate },- { excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...querySourceScope }, () => declarations.scan(primaryRows, queryText)));+ { excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...querySourceScope }, () => declarations.scan(primaryRows, queryText), resolving));await emitFanoutNotices(ctx, fanned.fanout, querySourceScope);results = await applyQueryArms(ctx.engine, p, queryText, fanned.results, { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types || !!where, evidencePlan: !!plan, evidenceBudget: plan?.budgetTokens, remote: ctx.remote !== false, queryEmbedding, rowCap: () => resolveEffectiveLimit(ctx, p), timer: timings });// #1663 — CRAG confidence gate. Grade what retrieval returned (zero-LLM;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 305d172013..02e8dec39b 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -369,8 +369,7 @@ export class PostgresEngine implements BrainEngine {} else if (sourceId) {scopesValue = sourceId;}- return this.transaction(async engine => {- const tx = (engine as PostgresEngine).sql;+ return this.readTransaction(tx => {// One settings statement for the scope binding, JIT off and the// caller's settings (a thunk is read here, after BEGIN, so a deadline// budget is measured one round trip before the query). A savepoint in@@ -388,7 +387,26 @@ export class PostgresEngine implements BrainEngine {/** An unscoped read in its own transaction with JIT off (search-settings.ts); a savepoint inside a caller's transaction. */private jitOffRead<T>(callback: (tx: ReturnType<typeof postgres>) => Promise<T>): Promise<T> {- return this.transaction(engine => withSearchJitOff((engine as PostgresEngine).sql, this._pageTransaction, () => callback((engine as PostgresEngine).sql)));+ return this.readTransaction(tx => withSearchJitOff(tx, this._pageTransaction, () => callback(tx)));+ }++ /**+ * GBRA-156: a top-level read transaction answers when its read returns, without waiting for COMMIT's round trip.+ * The driver keeps the connection reserved, and the gauge counts it, until COMMIT settles; a failed COMMIT cannot+ * change rows already read, so it is not the caller's error. `run` lets its statement errors propagate (every read here does).+ */+ private readTransaction<T>(run: (tx: ReturnType<typeof postgres>) => Promise<T>): Promise<T> {+ if (this._pageTransaction) return this.transaction(engine => run((engine as PostgresEngine).sql));+ return new Promise<T>((resolve, reject) => {+ let answered = false;+ this.transaction(async engine => {+ const tx = (engine as PostgresEngine).sql;+ const result = await run(tx);+ answered = true;+ resolve(result);+ return result;+ }).catch(error => { if (!answered) reject(error); });+ });}// Lifecyclediff --git a/src/core/search/alias-fanout.ts b/src/core/search/alias-fanout.tsindex c1e03eb9fe..8d06bc50cd 100644--- a/src/core/search/alias-fanout.ts+++ b/src/core/search/alias-fanout.ts@@ -198,20 +198,25 @@ export async function aliasFanoutMax(engine: BrainEngine): Promise<number> {/*** Splice rows found under the entity's other names into `results`. `fallback`* supplies (name, alias) pairs the top rows declare, used when no entity- * resolves. Fail-soft: any error returns `results` unchanged.+ * resolves. `resolving` is `resolveQueryEntity` for the same query and scope,+ * when the caller started it before the search. Fail-soft: any error returns+ * `results` unchanged.*/export async function withAliasFanOut(engine: BrainEngine, results: SearchResult[], queryText: string, scope: Scope, searchOpts: SearchOpts,- fallback: () => Array<{ name: string; alias: string; slug: string }>): Promise<{ results: SearchResult[]; fanout?: FanoutMeta; entity?: ResolvedEntity }> {+ fallback: () => Array<{ name: string; alias: string; slug: string }>, resolving?: Promise<ResolvedEntity | null>): Promise<{ results: SearchResult[]; fanout?: FanoutMeta; entity?: ResolvedEntity }> {try {const max = await aliasFanoutMax(engine);- if (max === 0) return { results, ...(await resolveEntityQuiet(engine, queryText, scope)) };+ if (max === 0) {+ const entity = await (resolving ?? resolveQueryEntity(engine, queryText, scope)).catch(() => null);+ return { results, ...(entity ? { entity } : {}) };+ }const words = (text: string) => normalizeAlias(text).split(/[^\p{L}\p{N}]+/u).filter(Boolean);const queryWords = words(queryText);const inQuery = (name: string) => {const w = words(name);return w.length > 0 && queryWords.some((_, i) => w.every((t, k) => queryWords[i + k] === t));};- const resolved = await resolveQueryEntity(engine, queryText, scope);+ const resolved = await (resolving ?? resolveQueryEntity(engine, queryText, scope));let names: Array<{ alias: string; page: string }>;let usedTokens: [number, number] | null = null;if (resolved) {@@ -253,8 +258,3 @@ export async function withAliasFanOut(engine: BrainEngine, results: SearchResultreturn { results };}}--async function resolveEntityQuiet(engine: BrainEngine, query: string, scope: Scope): Promise<{ entity?: ResolvedEntity }> {- const entity = await resolveQueryEntity(engine, query, scope).catch(() => null);- return entity ? { entity } : {};-}diff --git a/src/core/search/embedding-column.ts b/src/core/search/embedding-column.tsindex f5bb4b0cb0..79e24cbc38 100644--- a/src/core/search/embedding-column.ts+++ b/src/core/search/embedding-column.ts@@ -36,8 +36,9 @@* │ column │ │ │ │ col: quoted ident │* │ → 'embedding' │ │ │ │ "<name>" (D12) │* │ │ │ │ │ castSql: │- * │ Returns Resolved- │ │ │ │ '$1::vector' OR │- * │ Column descriptor. │ │ │ │ '$1::halfvec(N)' │+ * │ Returns Resolved- │ │ │ │ '$1::text::vector' │+ * │ Column descriptor. │ │ │ │ OR '$1::text:: │+ * │ │ │ │ │ halfvec(N)' │* └──────────┬───────────┘ └──────────────────────┘ └─────────────────────┘* │* ▼ (descriptor passed to engines + cosineReScore)@@ -247,8 +248,12 @@ export function quoteIdentifier(name: string): string {* Returns:* col — identifier-quoted column name for SELECT / WHERE / ORDER BY.* castSql — placeholder cast for the query vector parameter:- * '$1::vector' for type='vector'- * '$1::halfvec(<dims>)' for type='halfvec'+ * '$1::text::vector' for type='vector'+ * '$1::text::halfvec(<dims>)' for type='halfvec'+ * The parameter is bound as text (GBRA-156): the vendored+ * driver shares only built-in parameter types across a pool's+ * connections, so a vector-typed parameter cost a describe+ * round trip on every run under a transaction-mode pooler.** Callers interpolate both into the SQL string. The `$1` is the* positional parameter that postgres.js / PGLite will bind the query@@ -261,7 +266,7 @@ export function buildVectorCastFragment(resolved: ResolvedColumn): {col: string;castSql: string;} {- return { col: quoteIdentifier(resolved.name), castSql: `$1${vectorCastSuffix(resolved)}` };+ return { col: quoteIdentifier(resolved.name), castSql: `$1::text${vectorCastSuffix(resolved)}` };}/**@@ -534,7 +539,7 @@ export function isBuiltinColumn(name: string): name is BuiltinKey {* accepted at the engine layer (per D11 — engine purity).** `dims` for the 'embedding' builtin is hardcoded 1536 here purely as- * a no-op placeholder; the engine's SQL cast is `$1::vector` (no+ * a no-op placeholder; the engine's SQL cast is `$1::text::vector` (no* parenthesized N) when type='vector', so the dims field is unused by* `buildVectorCastFragment` and never touches the wire. Tests that* care about dims should pass a real descriptor.@@ -557,7 +562,7 @@ export function normalizeEngineColumn(return {name: 'embedding',type: 'vector',- dimensions: 1536, // placeholder — not used by $1::vector cast+ dimensions: 1536, // placeholder — not used by $1::text::vector castembeddingModel: '', // engine doesn't embed; left blank};}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex cc5eb8cc22..9e655d6c0b 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -1161,7 +1161,7 @@ export async function hybridSearch(}));opts?.explainTarget?.observe('reranked', rerankPinned);const { returnPool, adaptiveDecision, autocutDecision, relationalSlotDecision } = await timer.stage('post_fusion', () => sizeReturnPool(req, {- rerankPinned, deduped, exactLookupOpts: lexical.exactLookupOpts, relationalList, effectiveModality, identityLookups,+ rerankPinned, deduped, relationalList, effectiveModality, identityLookups,}));opts?.explainTarget?.observe('return_pool', returnPool);return timer.stage('post_fusion', () => finalizeHybridResults(req, returnPool, {diff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.tsindex b16dbb189a..95233e19ef 100644--- a/src/core/search/hybrid/keyword-only.ts+++ b/src/core/search/hybrid/keyword-only.ts@@ -18,6 +18,7 @@ import { pushDegraded, stampBudgetStage } from './degraded.ts';import { stampEvidence } from '../evidence.ts';import { applyEvidenceGate } from '../decide-stage.ts';import { collapsePool, prioritize } from './rank.ts';+import { readGeneratedPages } from '../provenance-demotion.ts';import { warnOncePerProcess } from '../../utils.ts';/** No embedding provider (and no multimodal route): keyword + title + relational only. */@@ -52,8 +53,9 @@ export async function searchWithoutEmbeddings(noEmbedResults = rrfFusionWeighted(noEmbedLists, ctBoost, opts?.explain === true || trace !== undefined);}if (noEmbedResults.length > 0) {+ const generatedRead = readGeneratedPages(engine, noEmbedResults);await runPostFusionStages(engine, noEmbedResults, postFusionOpts);- await applyIdentityBoosts(req, noEmbedResults);+ await applyIdentityBoosts(req, noEmbedResults, generatedRead);noEmbedResults.sort((a, b) => b.score - a.score);noEmbedResults = await applyFeedbackStage(engine, noEmbedResults, { reranked: false });}@@ -175,8 +177,9 @@ export async function searchVectorFallback(fallbackResults = rrfFusionWeighted(fallbackLists, ctBoost, opts?.explain === true || trace !== undefined);}if (fallbackResults.length > 0) {+ const generatedRead = readGeneratedPages(engine, fallbackResults);await runPostFusionStages(engine, fallbackResults, postFusionOpts);- await applyIdentityBoosts(req, fallbackResults);+ await applyIdentityBoosts(req, fallbackResults, generatedRead);fallbackResults.sort((a, b) => b.score - a.score);fallbackResults = await applyFeedbackStage(engine, fallbackResults, { reranked: false });}diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.tsindex 17614047db..62254de203 100644--- a/src/core/search/hybrid/rank.ts+++ b/src/core/search/hybrid/rank.ts@@ -6,7 +6,7 @@import type { ModalityMode } from '../query-intent.ts';import { type AdaptiveReturnDecision, adaptiveReturnFromConfig, applyAdaptiveReturn, resolveAdaptiveReturn } from '../return-policy.ts';import { type AutocutDecision, applyAutocut } from '../autocut.ts';-import { type ExactLookupOpts, applyExactLookupHits, applyExactLookupTier } from '../exact-lookup.ts';+import { type ExactLookupOpts, applyExactLookupHits } from '../exact-lookup.ts';import { type FusionListEntry, type VectorArm, composeFusionLists } from '../fusion-lists.ts';import { type HybridRequest, applyIdentityBoosts, emitHybridMeta } from './request.ts';import type { KeywordArmConfidenceDecision } from '../arm-confidence.ts';@@ -17,14 +17,15 @@ import { type RelationalRerankPinDecision, pinRelationalRows } from '../relationimport { applyFeedbackStage } from '../feedback-boost.ts';import { capPerSession } from '../diverse-pool.ts';import { collapseResults } from '../collapse.ts';+import { readGeneratedPages } from '../provenance-demotion.ts';import { applyRankPriors } from '../rank-priors.ts';import { type RerankFailedReason, type RerankPassThroughReason, type RerankSkipReason, applyReranker } from '../rerank.ts';import type { RerankMeta } from '../../ai/gateway.ts';import { applyEvidenceGate, recordRerankReceipts, startRerankShadow } from '../decide-stage.ts';import { rerankEgressDenied } from '../decide-retrieval.ts';import type { SearchResult } from '../../types.ts';-import { applyAliasHop, applyAliasHopLookup } from '../alias-hop.ts';-import { type IdentityLookups, type RerankGateMeta, prepareRerankGate } from './rerank-gate.ts';+import { applyAliasHopLookup } from '../alias-hop.ts';+import { type IdentityLookups, type RerankGateMeta, prepareRerankGate, readIdentityLookups } from './rerank-gate.ts';import { effectiveRrfK } from '../intent-weights.ts';import { enforceTokenBudget } from '../token-budget.ts';import { expandAnchors, hydrateChunks } from '../two-pass.ts';@@ -177,12 +178,13 @@ export async function fuseArms(// boost surface. Salience and recency are independent axes — either,// both, or neither fires depending on resolved modes.if (fused.length > 0) await req.timer.stage('post_fusion', async () => {+ const generatedRead = readGeneratedPages(engine, fused);await runPostFusionStages(engine, fused, {...postFusionOpts, skipMetadataBoosts: !metadataBoostGate.boosts_applied,});// v0.32.x search-lite: intent exact-match boost (entity/event intents).// No-op when boost factor is 1.0 (general intent or weighting disabled).- await applyIdentityBoosts(req, fused);+ await applyIdentityBoosts(req, fused, generatedRead);fused.sort((a, b) => b.score - a.score);});trace?.observe('fused', fused);@@ -321,10 +323,11 @@ export async function rerankAndPin(// decide.egress.deny_sources; such a query keeps fused order (egress_denied).const egressDenied = rerankerOpts.enabled && rerankEgressDenied(req.modeInput.decide, rerankerOpts.model ?? resolvedMode.reranker_model, deduped.slice(0, rerankerOpts.topNIn));if (egressDenied) { s1Failure = 'egress_denied'; pushDegraded(degraded, 'reranker_skipped', 'egress_denied'); }- // W3 rerank gate (no-op under `off`): grades a read-only view of `deduped`- // and reads the identity tiers without applying them, alongside the- // reranker call. The reranker's input is unchanged.- const gatePending = prepareRerankGate(req, { deduped, rerankerOpts, egressDenied, exactLookupOpts, multimodal });+ // The identity tiers' reads run alongside the reranker call; sizeReturnPool+ // applies them after it. W3 rerank gate (no-op under `off`): grades a+ // read-only view of `deduped` with the same reads. The reranker's input is unchanged.+ const identityPending = readIdentityLookups(req, exactLookupOpts);+ const gatePending = prepareRerankGate(req, { deduped, rerankerOpts, egressDenied, lookups: identityPending, multimodal });const reranked = rerankerOpts.enabled && !egressDenied? await applyReranker(query, deduped, {...(rerankerOpts as any),@@ -357,26 +360,24 @@ export async function rerankAndPin(const rerankPinned = reranked !== deduped && effectiveModality !== 'image'? pinRelationalRows(ordered, relationalList, { max: resolvedMode.relational_rerank_pin, fusedOrder: deduped, onPin: (d) => { relationalRerankPin = d; } }): ordered;- return { rerankPinned: prioritize(req, rerankPinned), relationalRerankPin, rerankGate, identityLookups: gate.lookups };+ return { rerankPinned: prioritize(req, rerankPinned), relationalRerankPin, rerankGate, identityLookups: await identityPending };}/** Alias hop + exact-lookup tier, evidence stamp, adaptive return, autocut and the relational evidence slot. */export async function sizeReturnPool(req: HybridRequest,- { rerankPinned, deduped, exactLookupOpts, relationalList, effectiveModality, identityLookups }: {- rerankPinned: SearchResult[]; deduped: SearchResult[]; exactLookupOpts: ExactLookupOpts;+ { rerankPinned, deduped, relationalList, effectiveModality, identityLookups }: {+ rerankPinned: SearchResult[]; deduped: SearchResult[];relationalList: SearchResult[]; effectiveModality: ModalityMode;- /** Lookups the rerank gate already read (gate not `off`): applied here, never re-read. */- identityLookups?: IdentityLookups;+ /** Lookups rerankAndPin read alongside the reranker: applied here, never re-read. */+ identityLookups: IdentityLookups;},) {const { engine, query, opts, resolvedMode, cfgForColumn, limit, offset, suggestions, aliasHopOpts } = req;- // T3 — free-text alias hop. Runs AFTER rerank so a query that is a page's+ // T3 — free-text alias hop. Applied AFTER rerank so a query that is a page's// declared chosen name reliably surfaces that page regardless of how the// reranker scored body chunks. Fail-open on pre-v110 brains.- const preExact = identityLookups- ? await applyAliasHopLookup(engine, rerankPinned, identityLookups.alias, aliasHopOpts)- : await applyAliasHop(engine, rerankPinned, query, aliasHopOpts);+ const preExact = await applyAliasHopLookup(engine, rerankPinned, identityLookups.alias, aliasHopOpts);// #1663 — structural exact-lookup tier: a query that IS a page identity// (slug / exact normalized title) gets that page at rank-1 regardless of@@ -384,9 +385,7 @@ export async function sizeReturnPool(// the already-fetched title arm (no extra queries); pure no-op for// non-lookup-shaped queries. Runs after the alias hop so all three// identity surfaces (alias, slug, title) share the same injection shape.- const aliasHopped = await collapsePool(req, identityLookups- ? applyExactLookupHits(preExact, identityLookups.exactHits)- : await applyExactLookupTier(engine, preExact, query, exactLookupOpts));+ const aliasHopped = await collapsePool(req, applyExactLookupHits(preExact, identityLookups.exactHits));// T4 — stamp evidence + create_safety so the agent's don't-duplicate// decision keys off WHY a page matched, not a raw blended score. Stamp ondiff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex 1662fce143..e57624a33c 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -3,7 +3,7 @@* Each stage reads the resolved request (HybridRequest, request.ts) and* writes its per-request accumulators only as `req.<field>`.*/-import { applyGeneratedDemotion } from '../provenance-demotion.ts';+import { applyGeneratedDemotion, type GeneratedPage } from '../provenance-demotion.ts';import { normalizeChainSlots } from '../relational-chain.ts';import type { BrainEngine } from '../../engine.ts';import { perArmPoolLimit } from '../eval-pool-depth.ts';@@ -338,9 +338,9 @@ export async function resolveHybridRequest(// Intent identity boosts (exact/mentioned title or slug, mentioned alias),// shared by the fused path and both keyword-only paths. Caller re-sorts.-export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult[]): Promise<void> {+export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult[], generatedRead?: Promise<GeneratedPage[] | null>): Promise<void> {const { engine, query, opts, suggestions, intentWeightingOn, intentWeights, resolvedMode } = req;- await applyGeneratedDemotion(engine, list, query, { sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate });+ await applyGeneratedDemotion(engine, list, query, { sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate }, generatedRead);if (intentWeights.exactMatchBoost === 1.0) {// #4694: general and temporal questions still honor a multi-token// title that is the query's subject. Not concept intent (Cat 13: adiff --git a/src/core/search/hybrid/rerank-gate.ts b/src/core/search/hybrid/rerank-gate.tsindex b8beeb4be3..2aed85f4b5 100644--- a/src/core/search/hybrid/rerank-gate.ts+++ b/src/core/search/hybrid/rerank-gate.ts@@ -3,13 +3,14 @@* cross-encoder. Runs on the deduped candidates, before `rerankAndPin` calls* the reranker, only when `search.reranker.gate` is not `off`.*- * It reads the identity tiers without applying them: the alias table read- * (`lookupAliasHop`) and the structural exact lookup (`structuralExactLookup`)- * return what the post-rerank tiers would apply, the grade reads them plus a- * detached view of the candidates (`gradePreRerank`, pure), and- * `sizeReturnPool` applies the same lookups at today's post-rerank position,- * so each lookup runs once and the reranker's input is unchanged. `off`- * returns nothing and the pipeline is untouched.+ * It reads the identity tiers without applying them: `readIdentityLookups`+ * (the alias table read and the structural exact lookup, started by+ * `rerankAndPin` alongside the reranker whatever the gate mode) returns what+ * the post-rerank tiers would apply, the grade reads them plus a detached+ * view of the candidates (`gradePreRerank`, pure), and `sizeReturnPool`+ * applies the same lookups at today's post-rerank position, so each lookup+ * runs once and the reranker's input is unchanged. `off` returns nothing+ * and the pipeline is untouched.*/import type { SearchResult } from '../../types.ts';import type { HybridRequest } from './request.ts';@@ -53,6 +54,15 @@ export interface IdentityLookups {exactHits: SearchResult[];}+/** The identity tiers' reads; they depend on the query alone, so they run alongside the reranker. */+export async function readIdentityLookups(req: HybridRequest, exactLookupOpts: ExactLookupOpts): Promise<IdentityLookups> {+ const [alias, exactHits] = await Promise.all([+ lookupAliasHop(req.engine, req.query, req.aliasHopOpts),+ structuralExactLookup(req.engine, req.query, exactLookupOpts).catch(() => [] as SearchResult[]),+ ]);+ return { alias, exactHits };+}+/** True when the opt-in single-token alias hop has a candidate it would move (full-query alias absent). */function tokenHopWouldFire(lookup: AliasHopLookup, opts: HybridRequest['aliasHopOpts']): boolean {if ((lookup.aliasMap.get(lookup.qNorm)?.length ?? 0) > 0) return false;@@ -76,11 +86,11 @@ async function pageTrust(req: HybridRequest, top: { slug: string; source_id: str*/export async function prepareRerankGate(req: HybridRequest,- { deduped, rerankerOpts, egressDenied, exactLookupOpts, multimodal }: {+ { deduped, rerankerOpts, egressDenied, lookups, multimodal }: {deduped: readonly SearchResult[]; rerankerOpts: Pick<RerankerOpts, 'enabled' | 'topNIn'>; egressDenied: boolean;- exactLookupOpts: ExactLookupOpts; multimodal: boolean;+ lookups: Promise<IdentityLookups>; multimodal: boolean;},-): Promise<{ meta?: RerankGateMeta; lookups?: IdentityLookups }> {+): Promise<{ meta?: RerankGateMeta }> {const mode = req.resolvedMode.reranker_gate;if (mode === 'off') return {};const base = { mode, candidates: deduped.length, would_skip: false, provider_called: false } as const;@@ -88,11 +98,8 @@ export async function prepareRerankGate(if (egressDenied) return { meta: { ...base, eligible: false, ineligible_reason: 'egress_denied' } };if (deduped.length === 0) return { meta: { ...base, eligible: false, ineligible_reason: 'no_candidates' } };- const { engine, query, aliasHopOpts, resolvedMode } = req;- const [alias, exactHits] = await Promise.all([- lookupAliasHop(engine, query, aliasHopOpts),- structuralExactLookup(engine, query, exactLookupOpts).catch(() => [] as SearchResult[]),- ]);+ const { query, aliasHopOpts, resolvedMode } = req;+ const { alias, exactHits } = await lookups;let grade = gradePreRerank({candidates: deduped,query,@@ -122,5 +129,5 @@ export async function prepareRerankGate(would_skip: grade.strong && blocked === undefined,...(blocked ? { skip_blocked: blocked } : {}),};- return { meta, lookups: { alias, exactHits } };+ return { meta };}diff --git a/src/core/search/provenance-demotion.ts b/src/core/search/provenance-demotion.tsindex f08393fd2c..e3ab700bcd 100644--- a/src/core/search/provenance-demotion.ts+++ b/src/core/search/provenance-demotion.ts@@ -39,15 +39,32 @@ export function recordsCorrection(frontmatter: Record<string, unknown> | null, b}}-export async function applyGeneratedDemotion(engine: BrainEngine, list: SearchResult[], query: string,- scope: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<void> {+export type GeneratedPage = { id: number; frontmatter: Record<string, unknown> | null; compiled_truth: string | null };++const pageIds = (list: SearchResult[]) => [...new Set(list.map(r => r.page_id).filter((id): id is number => typeof id === 'number'))];++/**+ * The generated pages among `list`; null when the read failed. It reads only the+ * pool's page ids, so callers start it before stages that change scores but not membership.+ */+export async function readGeneratedPages(engine: BrainEngine, list: SearchResult[]): Promise<GeneratedPage[] | null> {try {- const ids = [...new Set(list.map(r => r.page_id).filter((id): id is number => typeof id === 'number'))];- if (!ids.length) return;- const generated = await engine.executeRaw<{ id: number; frontmatter: Record<string, unknown> | null; compiled_truth: string | null }>(+ const ids = pageIds(list);+ if (!ids.length) return [];+ return await engine.executeRaw<GeneratedPage>(`SELECT id, frontmatter, compiled_truth FROM pagesWHERE id = ANY($1::int[]) AND (frontmatter->>'dream_generated' = 'true' OR type = 'extract_receipt')`, [ids]);- if (!generated.length) return;+ } catch {+ return null;+ }+}++export async function applyGeneratedDemotion(engine: BrainEngine, list: SearchResult[], query: string,+ scope: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }, generatedRead = readGeneratedPages(engine, list)): Promise<void> {+ try {+ const ids = pageIds(list);+ const generated = await generatedRead;+ if (!generated?.length) return;const generatedIds = new Set(generated.map(g => Number(g.id)));for (const r of list) if (generatedIds.has(r.page_id)) r.provenance = 'generated';if (isOff(await engine.getConfig('search.demote_generated'))) return;diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex a6303fc221..5c9b6167ea 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -336,14 +336,15 @@ async function listRegisteredLocalPathSources(/*** Every source row in one statement, once per request config snapshot (#7147): a CLI read or an MCP request resolves* its source through tier 4, tier 5.5 and the federated set, three reads of a table that does not change under one- * read. Undefined without an open snapshot (no await, so a live read keeps its timing) and null on a brain older than+ * read. Each row also carries tier 5.5's emptiness guard (`default_has_pages`), so the request pays one round trip.+ * Undefined without an open snapshot (no await, so a live read keeps its timing) and null on a brain older than* the `archived` column; the callers then read live.*/function requestSourceRows(engine: BrainEngine,-): Promise<Array<{ id: string; local_path: string | null; archived: boolean; config: unknown }> | null> | undefined {- return requestSnapshotRead(engine, 'sources', () => engine.executeRaw<{ id: string; local_path: string | null; archived: boolean; config: unknown }>(- `SELECT id, local_path, archived, config FROM sources ORDER BY id`,+): Promise<Array<{ id: string; local_path: string | null; archived: boolean; config: unknown; default_has_pages: boolean }> | null> | undefined {+ return requestSnapshotRead(engine, 'sources', () => engine.executeRaw<{ id: string; local_path: string | null; archived: boolean; config: unknown; default_has_pages: boolean }>(+ `SELECT id, local_path, archived, config, EXISTS (SELECT 1 FROM pages WHERE source_id = 'default' AND deleted_at IS NULL) AS default_has_pages FROM sources ORDER BY id`,).catch(() => null));}@@ -354,12 +355,15 @@ async function pickSoleNonDefaultSource(// archived column was added in v34 (v0.26.5). Older brains may not have// it — fall back to the un-archived query in that case via try/catch.const pending = requestSourceRows(engine);- // GBRA-133: the emptiness guard's read is sent with the listing (one round trip); it is used only for a sole candidate.- const defaultPagesRead = engine.executeRaw<{ one: number }>(- `SELECT 1 AS one FROM pages WHERE source_id = 'default' AND deleted_at IS NULL LIMIT 1`,- );- defaultPagesRead.catch(() => {});const request = pending && await pending;+ // GBRA-133: the emptiness guard's read is sent with the listing (one round trip); it is used only for a sole candidate.+ // The request's rows carry its answer already.+ const defaultHasPages = request+ ? Promise.resolve(request.some(row => row.default_has_pages))+ : engine.executeRaw<{ one: number }>(+ `SELECT 1 AS one FROM pages WHERE source_id = 'default' AND deleted_at IS NULL LIMIT 1`,+ ).then(found => found.length > 0);+ defaultHasPages.catch(() => {});let rows: Array<{ id: string }> = request ? request.filter(row => row.local_path !== null && row.id !== 'default' && row.archived === false) : [];if (!request) {try {@@ -375,8 +379,7 @@ async function pickSoleNonDefaultSource(if (rows.length !== 1) return null;// #3070 emptiness guard: fire only when 'default' holds no active pages.try {- const defaultPages = await defaultPagesRead;- if (defaultPages.length > 0) {+ if (await defaultHasPages) {// The flip must not be silent: one stray page in 'default' reroutes// every bare command away from the sole side-source, and the user// hunts for "lost" writes. One stderr line names both sides so the@@ -660,10 +663,15 @@ export async function assessUnscopedDefaultWrite(async function assertSourceExists(engine: BrainEngine, id: string): Promise<void> {// GBRA-133: inside a CLI sync's routing scope the source's routing row answers this (sync-dispatch-read.ts).const routing = await syncDispatchRow(engine, id);- const rows = routing ? (routing.id !== null && routing.archived === false ? [routing] : []) : await engine.executeRaw<{ id: string }>(- `SELECT id FROM sources WHERE id = $1 AND archived = false`,- [id],- );+ // GBRA-156: inside a request snapshot the request's source rows answer it.+ const pending = routing ? undefined : requestSourceRows(engine);+ const request = pending && await pending;+ const rows = routing ? (routing.id !== null && routing.archived === false ? [routing] : [])+ : request ? request.filter(row => row.id === id && row.archived === false)+ : await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE id = $1 AND archived = false`,+ [id],+ );if (rows.length === 0) {throw new SourceTargetError(`Source "${id}" not found or is archived. Available active sources: ` +@@ -864,6 +872,9 @@ async function resolveSourceWithTierChain(// 4. Registered source whose local_path contains CWD.// #3880 active-over-archived tiering + parallel realpath both live in// the shared resolveRegisteredPathMatch helper.+ // GBRA-156: tier 5's config read is sent with the listing, as in resolveSourceIdChain.+ const defaultRead = engine.getConfig('sources.default');+ defaultRead.catch(() => {});const best = await resolveRegisteredPathMatch(await listRegisteredLocalPathSources(engine), cwd);if (best) {await assertSourceExists(engine, best.id);@@ -871,7 +882,7 @@ async function resolveSourceWithTierChain(}// 5. Brain-level default. Silent-fallback (P1-F) like tier 5 in resolveSourceId.- const globalDefault = await engine.getConfig('sources.default');+ const globalDefault = await defaultRead;if (globalDefault && isValidSourceId(globalDefault)) {await assertSourceExists(engine, globalDefault);return { source_id: globalDefault, tier: 'brain_default', detail: 'sources.default config' };diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 68cf105c84..c55017fb16 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -47,6 +47,7 @@ import { maybeRefreshBackupStatusInProcess } from '../core/backup/coverage.ts';import { operationScopesAllowed } from '../core/scope.ts';import { enforceReadTrustFloor } from '../core/eligibility/registry.ts';import { invalidateHotMemoryForEngine } from '../core/facts/meta-hook.ts';+import { isEngineDegraded } from '../core/degraded-marker.ts';import { admittedPendingReceipt, type WriteReceipt } from '../core/persistence/types.ts';import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';import { frameOverCap, resultTooLargeError } from '../core/egress-budget.ts';@@ -878,6 +879,12 @@ export async function dispatchToolCall(: withoutRequestConfigSnapshot(run);}+/** The response-meta hook's keys, or its failure message; never rejects (a hook failure degrades to no keys). */+async function runMetaHook(hook: NonNullable<DispatchOpts['metaHook']>, name: string, ctx: OperationContext): Promise<{ meta?: Record<string, unknown>; failure?: string }> {+ try { return { meta: await hook(name, ctx) }; }+ catch (metaErr) { return { failure: metaErr instanceof Error ? metaErr.message : String(metaErr) }; }+}+async function dispatchResolvedCall(engine: BrainEngine,name: string,@@ -1063,6 +1070,8 @@ async function dispatchResolvedCall(enforceBoundClientOpAllowList(ctx.auth, op);// #5575 CEO-18: a floored connection only reaches read ops that enforce its floor.enforceReadTrustFloor(ctx.auth, op);+ // GBRA-156: a read op does not change what the hook reads, so it runs beside the handler (a degraded engine's reconnect stays the handler's).+ const earlyMeta = opts.metaHook && op.mutating === false && !isEngineDegraded(engine) ? runMetaHook(opts.metaHook, name, ctx) : undefined;const sharedStdio = ctx.transport === 'stdio' && !ctx.auth &&(op.requiredScopes?.length || ['list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack'].includes(name));let registration: Awaited<ReturnType<typeof readLocalWriter>> | undefined;@@ -1154,13 +1163,9 @@ async function dispatchResolvedCall(// helper crash degrades to no hook keys rather than flipping the whole// tool call to error.if (opts.metaHook) {- try {- const meta = await opts.metaHook(name, ctx);- if (meta && Object.keys(meta).length > 0) out._meta = { ...(out._meta ?? {}), ...meta };- } catch (metaErr) {- const msg = metaErr instanceof Error ? metaErr.message : String(metaErr);- ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${msg}; degrading to no hook keys`);- }+ const { meta, failure } = await (earlyMeta ?? runMetaHook(opts.metaHook, name, ctx));+ if (meta && Object.keys(meta).length > 0) out._meta = { ...(out._meta ?? {}), ...meta };+ if (failure !== undefined) ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${failure}; degrading to no hook keys`);}// Large pages: the egress backstop measures the final frame; a read over the connection's cap is refused whole, never cut.const over = op.mutating ? null : await frameOverCap(out, { remote: ctx.remote, transport: ctx.transport, engine, config: ctx.config });diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 48494133d1..dda7e3b742 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -16,6 +16,7 @@ import { noticeBlock, renderNotice, type Notice } from '../core/agent-output.ts'import { disabledOpsForPublishGates } from './publish-gates.ts';import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';import { loadConfig } from '../core/config.ts';+import { requestConfigRows, withRequestConfigSnapshot } from '../core/config-snapshot.ts';import { gcSessionContextState } from '../core/context/session-state.ts';import { installInstructionsResolver, readInstructionContent, resolveMcpInstructions } from './instructions.ts';import { instructionReadiness, stdioCapabilityReadiness } from './initialize-context.ts';@@ -105,6 +106,7 @@ function deferredBoot(opts: { degraded: boolean }) {export async function resolveMcpStdioSourceScope(engine: BrainEngine,cwd: string = process.cwd(),+ opts: { warmConfig?: boolean } = {},): Promise<{sourceId: string;localFederatedSourceIds?: string[];@@ -131,7 +133,9 @@ export async function resolveMcpStdioSourceScope(}try {const { resolveSourceWithTier, localFederatedSourceIds, explicitReadBinding } = await import('../core/source-resolver.ts');- const resolved = await resolveSourceWithTier(engine, null, cwd);+ // GBRA-156: a tool call resolves inside the request's config snapshot (which dispatch reuses for a read op), so+ // `warmConfig` reads the config table beside the source rows: one round trip before the op.+ const [resolved] = await Promise.all([resolveSourceWithTier(engine, null, cwd), opts.warmConfig ? requestConfigRows(engine) : undefined]);const federated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);// #5081: the admission set is optional; a failed lookup must not discard// the resolved binding (the catch below would fall back to 'default').@@ -438,7 +442,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// The MCP SDK's response type widened in 1.29 to allow a managed-task wrapper;// gbrain ops are synchronous, so we return the legacy `{ content, isError? }`// shape and cast through `any` (the SDK accepts it via the ServerResult union).- server.setRequestHandler(CallToolRequestSchema, async (request: any): Promise<any> => trackStdioRpc(async () => {+ server.setRequestHandler(CallToolRequestSchema, async (request: any): Promise<any> => trackStdioRpc(() => withRequestConfigSnapshot(engine, async () => {const { name, arguments: params } = request.params;const [{ dispatchToolCall, dispatchRenderContext, requestMetaSessionId }, { getBrainHotMemoryMeta }] = await gate.awaitCall();// F4: status-only mode answers gbrain_status and refuses the rest until@@ -452,7 +456,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// as local CLI dispatch: GBRAIN_SOURCE, then .gbrain-source, then the// non-explicit fallback tiers. Non-explicit tiers may widen to federated// local reads; explicit/env/dotfile scopes stay scalar.- const sourceScope = await resolveMcpStdioSourceScope(engine);+ const sourceScope = await resolveMcpStdioSourceScope(engine, process.cwd(), { warmConfig: OPERATION_MANIFEST.find(o => o.name === name)?.mutating === false });// v0.28: stdio MCP has no per-token auth (local pipe). Default the// takes-holder allow-list to ['world'] so agent-facing callers don't// see private hunches via takes_list / takes_search / query. Operators@@ -504,7 +508,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSsurfaceCeiling: session.surface, stdioSurface: session, revealTools: listing.reveal, isListed: listing.isListed,resultRows,}), dispatchRenderContext);- }));+ })));const transport = mcpStdioTransport();bootPhase('mcp_connect');diff --git a/test/cold-read-folded-statements.test.ts b/test/cold-read-folded-statements.test.tsindex f3863edf6a..0d61733db8 100644--- a/test/cold-read-folded-statements.test.ts+++ b/test/cold-read-folded-statements.test.ts@@ -85,7 +85,7 @@ describe('source resolution inside one request snapshot', () => {expect(live.value.source_id).toBe('source-a');expect(snapshot.value).toEqual(live.value);expect(sourceScans(live.sql).length).toBeGreaterThan(1);- expect(sourceScans(snapshot.sql)).toEqual(['SELECT id, local_path, archived, config FROM sources ORDER BY id']);+ expect(sourceScans(snapshot.sql)).toEqual([`SELECT id, local_path, archived, config, EXISTS (SELECT 1 FROM pages WHERE source_id = 'default' AND deleted_at IS NULL) AS default_has_pages FROM sources ORDER BY id`]);});});}diff --git a/test/e2e/embedding-column-pglite.test.ts b/test/e2e/embedding-column-pglite.test.tsindex 2de8ccb766..d9c89aa3e7 100644--- a/test/e2e/embedding-column-pglite.test.ts+++ b/test/e2e/embedding-column-pglite.test.ts@@ -343,7 +343,7 @@ describe('upsertChunks — model provenance uses gateway-resolved model, not com});describe('buildVectorCastFragment — engine SQL composer (D3)', () => {- test('vector descriptor emits $1::vector', () => {+ test('vector descriptor emits $1::text::vector', () => {const r: ResolvedColumn = {name: 'embedding',type: 'vector',@@ -352,10 +352,10 @@ describe('buildVectorCastFragment — engine SQL composer (D3)', () => {};const { col, castSql } = buildVectorCastFragment(r);expect(col).toBe('"embedding"');- expect(castSql).toBe('$1::vector');+ expect(castSql).toBe('$1::text::vector');});- test('halfvec descriptor emits $1::halfvec(N) with parenthesized N', () => {+ test('halfvec descriptor emits $1::text::halfvec(N) with parenthesized N', () => {const r: ResolvedColumn = {name: 'embedding_fixture',type: 'halfvec',@@ -364,6 +364,6 @@ describe('buildVectorCastFragment — engine SQL composer (D3)', () => {};const { col, castSql } = buildVectorCastFragment(r);expect(col).toBe('"embedding_fixture"');- expect(castSql).toBe('$1::halfvec(2560)');+ expect(castSql).toBe('$1::text::halfvec(2560)');});});diff --git a/test/e2e/vector-candidate-safety-postgres.test.ts b/test/e2e/vector-candidate-safety-postgres.test.tsindex 655e5dc04b..f1596de7da 100644--- a/test/e2e/vector-candidate-safety-postgres.test.ts+++ b/test/e2e/vector-candidate-safety-postgres.test.ts@@ -121,7 +121,7 @@ import type { SearchOpts } from '../../src/core/types.ts';const hits = await engine.searchVector(query, { limit: 75, embeddingColumn: candidateColumn });const annMs = performance.now() - annStart;const captured = statements[firstStatement];- const exactSql = captured.sql.replace('ORDER BY cc."embedding_candidate_fixture" <=> $1::vector', 'ORDER BY (cc."embedding_candidate_fixture" <=> $1::vector) + 0');+ const exactSql = captured.sql.replace('ORDER BY cc."embedding_candidate_fixture" <=> $1::text::vector', 'ORDER BY (cc."embedding_candidate_fixture" <=> $1::text::vector) + 0');expect(exactSql).not.toBe(captured.sql);const params = [...captured.params];params[1] = null;diff --git a/test/e2e/vector-statement-describe-postgres.test.ts b/test/e2e/vector-statement-describe-postgres.test.tsnew file mode 100644index 0000000000..7b26a22d93--- /dev/null+++ b/test/e2e/vector-statement-describe-postgres.test.ts@@ -0,0 +1,93 @@+/**+ * GBRA-156: the per-search vector statements (the ANN candidate statement,+ * the SQL cosine re-score) bind the query vector as text and cast it in SQL+ * (\`$1::text::vector\`). The vendored driver shares a described statement's+ * parameter types across runs and connections only for built-in types+ * (vendor/README.md, \`shared_types\`), so a \`$1::vector\` parameter (an+ * extension type) paid a describe round trip on every run under a+ * transaction-mode pooler (\`prepare=false\`): two of the serial steps of a+ * warm search at 66 ms RTT.+ *+ * Contract: on one connection with prepare=false, the second run of each+ * statement is executed without a describe, with the same results; the+ * cosine values equal the JavaScript cosine of the stored vectors. The plan+ * (HNSW index kept) is pinned by test/e2e/vector-plan-real-column-postgres.test.ts.+ * Regression that fails it on the base branch: every run describes first.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { cosineByChunkIdsStatement } from '../../src/core/engine-sql/chunks.ts';+import { cosineSimilarity } from '../../src/core/search/cosine-rescore.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { readSqlTrace } from '../helpers/statement-counter.ts';+import { seedPage } from '../helpers/keyword-paging-fixture.ts';+import { withEnv } from '../helpers/with-env.ts';++const run = process.env.DATABASE_URL ? describe : describe.skip;+let databaseUrl = '';+let dims = 0;+let close: () => Promise<void> = async () => {};+const dir = mkdtempSync(join(tmpdir(), 'gbrain-vector-describe-'));+const vector = (seed: number) => new Float32Array(dims).map((_, i) => Math.sin(i * 0.37 + seed));+const stored = new Map<number, Float32Array>();++run('vector statements skip the describe round trip', () => {+ beforeAll(async () => {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ close = isolated.close;+ databaseUrl = isolated.databaseUrl;+ const [column] = await isolated.engine.executeRaw<{ type: string }>(+ "SELECT format_type(atttypid, atttypmod) AS type FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'");+ dims = Number(/\((\d+)\)/.exec(column!.type)![1]);+ for (let i = 0; i < 6; i++) await seedPage(isolated.engine, 'notes/vector-describe-' + i, 'Vector describe fixture note ' + i + ' about the acme-example rollout.');+ const chunks = await isolated.engine.executeRaw<{ id: number }>('SELECT id FROM content_chunks ORDER BY id');+ for (const [i, chunk] of chunks.entries()) {+ const v = vector(i + 1);+ stored.set(Number(chunk.id), v);+ await isolated.engine.executeRaw('UPDATE content_chunks SET embedding = $1::vector, embedded_text_hash = md5(chunk_text) WHERE id = $2', ['[' + Array.from(v).join(',') + ']', chunk.id]);+ }+ await isolated.engine.disconnect();+ }, 300_000);++ afterAll(async () => {+ await close();+ rmSync(dir, { recursive: true, force: true });+ });++ test('the second run of the ANN statement and of the cosine re-score is executed without a describe, with the same results', async () => {+ const trace = join(dir, 'trace.jsonl');+ const query = vector(0.5);+ const ids = [...stored.keys()];+ const results: Array<{ hits: unknown[]; cosines: Array<{ id: number; cosine: number }> }> = [];+ await withEnv({ GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'vector-describe' }, async () => {+ const engine = new PostgresEngine();+ await engine.connect({ database_url: databaseUrl + '?prepare=false', poolSize: 1 });+ try {+ for (let i = 0; i < 2; i++) {+ const hits = (await engine.searchVector(query, { limit: 5 })).map(h => [h.slug, h.chunk_id, h.score]);+ const { text, params } = cosineByChunkIdsStatement(ids, 'embedding', query);+ const cosines = (await engine.executeRaw<{ id: number; cosine: number }>(text, params)).map(r => ({ id: Number(r.id), cosine: Number(r.cosine) })).sort((a, b) => a.id - b.id);+ results.push({ hits, cosines });+ }+ } finally {+ await engine.disconnect();+ }+ });+ await Bun.sleep(1200);+ const records = readSqlTrace(trace).filter(r => r.kind === 'describe' || r.kind === 'execute');+ const kinds = (match: (sql: string) => boolean) => records.filter(r => match(r.sql)).map(r => r.kind);+ const annTexts = [...new Set(records.filter(r => r.sql.includes('<=> $1::')).map(r => r.sql))];+ const cosine = kinds(sql => sql.includes('vector_norm('));++ expect(results[0]!.hits.length).toBeGreaterThan(0);+ expect(results[1]).toEqual(results[0]!);+ expect(results[0]!.cosines.map(r => r.id)).toEqual(ids);+ for (const row of results[0]!.cosines) expect(row.cosine).toBeCloseTo(cosineSimilarity(query, stored.get(row.id)!), 5);+ expect(annTexts.length).toBeGreaterThan(0);+ for (const text of annTexts) expect(kinds(sql => sql === text)).toEqual(['describe', 'execute', 'execute']);+ expect(cosine).toEqual(['describe', 'execute', 'execute']);+ }, 120_000);+});diff --git a/test/fixtures/goldens/postgres-engine-gauge/sequence.json b/test/fixtures/goldens/postgres-engine-gauge/sequence.jsonindex dac693314b..af4fbac24f 100644--- a/test/fixtures/goldens/postgres-engine-gauge/sequence.json+++ b/test/fixtures/goldens/postgres-engine-gauge/sequence.json@@ -195,7 +195,7 @@"direct": 1,"raw": 2,"reserved": 1,- "tx": 1+ "tx": 2}},"step": "getBacklinkCounts released"diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex 4e2763fa49..315b72b8ab 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -3736,6 +3736,7 @@"readPageSnapshot": "direct","readPageSnapshotsBatch": "direct","readSegmentTexts": "none",+ "readTransaction": "none","reconnect": "none","refreshPageBody": "none","registerBeforeDisconnect": "none",diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.jsonindex 1870de2914..c5bd652877 100644--- a/test/fixtures/goldens/sql-text/_classification.json+++ b/test/fixtures/goldens/sql-text/_classification.json@@ -11,7 +11,7 @@"out-of-scope:dream-verdicts": 3,"out-of-scope:eval-capture": 5,"out-of-scope:ingest-log": 2,- "out-of-scope:internal-helper (private; exercised through public callers)": 19,+ "out-of-scope:internal-helper (private; exercised through public callers)": 20,"out-of-scope:lifecycle (connection, pool, transaction, raw seams)": 17,"out-of-scope:no-sql-stub": 1,"out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)": 11,@@ -176,6 +176,7 @@"readPageSnapshot": "pages","readPageSnapshotsBatch": "pages","readSegmentTexts": "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)",+ "readTransaction": "out-of-scope:internal-helper (private; exercised through public callers)","reconnect": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)","refreshPageBody": "pages","registerBeforeDisconnect": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",diff --git a/test/fixtures/mcp-stdio-round-trip-driver.ts b/test/fixtures/mcp-stdio-round-trip-driver.tsnew file mode 100644index 0000000000..209aa662a6--- /dev/null+++ b/test/fixtures/mcp-stdio-round-trip-driver.ts@@ -0,0 +1,21 @@+// Real stdio MCP server on an in-memory PGLite brain whose statements are held and depth-recorded+// (test/helpers/statement-depth.ts), for test/serve-request-round-trips.test.ts. Each statement is+// appended to ROUND_TRIP_LOG as one JSON line. One registered non-default source (source-a, under the cwd's+// child directory) with an empty 'default', so an unbound call resolves through tier 5.5 like the trace.+import { appendFileSync, mkdirSync } from 'node:fs';+import { join } from 'node:path';++const { configureGateway } = await import('../../src/core/ai/gateway.ts');+configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+const { startMcpServer } = await import('../../src/mcp/server.ts');+const { recordStatementDepth } = await import('../helpers/statement-depth.ts');+const engine = new PGLiteEngine();+await engine.connect({});+await engine.initSchema();+const side = join(process.cwd(), 'source-a-example');+mkdirSync(side, { recursive: true });+await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('source-a', 'source-a', $1, '{"federated": true}'::jsonb)`, [side]);+const log = process.env.ROUND_TRIP_LOG!;+recordStatementDepth(engine, { onRecord: record => appendFileSync(log, JSON.stringify(record) + '\n') });+await startMcpServer(engine, {});diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.tsindex e5a79b4e2f..b8e1df4088 100644--- a/test/helpers/postgres-engine-sql-cases.ts+++ b/test/helpers/postgres-engine-sql-cases.ts@@ -54,6 +54,7 @@ export const DOMAIN_OF: Record<string, string> = {'rlsScopeBindingEnabled': OOS.helper,'withScopedReadTransaction': OOS.helper,'jitOffRead': OOS.helper,+ 'readTransaction': OOS.helper,'connect': OOS.lifecycle,'connectedDatabaseUrl': OOS.lifecycle,'disconnect': OOS.lifecycle,diff --git a/test/helpers/statement-depth.ts b/test/helpers/statement-depth.tsnew file mode 100644index 0000000000..67399e33d3--- /dev/null+++ b/test/helpers/statement-depth.ts@@ -0,0 +1,25 @@+/**+ * GBRA-156: serial round trips of PGLite statements.+ *+ * Every statement is held `delayMs` (a stand-in for the network round trip) and records its depth: one more than the+ * deepest statement already answered when it was sent. Statements sent together share a depth, so the deepest depth of+ * a request is the number of serial round trips it pays, whatever the machine's speed.+ */+import type { PGLiteEngine } from '../../src/core/pglite-engine.ts';++export interface DepthRecord { sql: string; depth: number }++export function recordStatementDepth(engine: PGLiteEngine, opts: { delayMs?: number; onRecord?: (record: DepthRecord) => void } = {}): { records: DepthRecord[]; reset(): void } {+ const db = engine.db as unknown as { query: (sql: string, ...rest: unknown[]) => Promise<unknown> };+ const query = db.query.bind(db);+ const records: DepthRecord[] = [];+ let answered = 0;+ db.query = async (sql: string, ...rest: unknown[]) => {+ const record = { sql: sql.replace(/\s+/g, ' ').trim(), depth: answered + 1 };+ records.push(record);+ opts.onRecord?.(record);+ await Bun.sleep(opts.delayMs ?? 5);+ try { return await query(sql, ...rest); } finally { answered = Math.max(answered, record.depth); }+ };+ return { records, reset: () => { records.length = 0; answered = 0; } };+}diff --git a/test/postgres-engine-gauge-golden.test.ts b/test/postgres-engine-gauge-golden.test.tsindex 4028ccb57b..e94348f6d5 100644--- a/test/postgres-engine-gauge-golden.test.ts+++ b/test/postgres-engine-gauge-golden.test.ts@@ -12,7 +12,8 @@* domain calls that must not count at all;* - `acquiresByCase`: per EO8 SQL-text case (12 W1 domains), how many times* each gauge kind was acquired, plus the invariant that every acquire was- * released when the method settled.+ * released when the method settled (a read transaction's tx count when+ * its COMMIT, which the method does not wait for, settles: GBRA-156).*/import { describe, expect, test } from 'bun:test';@@ -97,6 +98,8 @@ async function captureAcquiresByCase(): Promise<Record<string, Record<string, nuconst gauge = new RecordingGauge();engine.checkoutGauge = gauge;await c.run(engine);+ // GBRA-156: a top-level read transaction returns before its COMMIT; its tx count is released when COMMIT settles.+ await new Promise((r) => setTimeout(r, 0));const leaked = Object.entries(gauge.snapshot()).filter(([, n]) => n !== 0);if (leaked.length) throw new Error(`${c.method}#${c.variant} leaked gauge counts: ${JSON.stringify(leaked)}`);out[`${c.method}#${c.variant}`] = gauge.acquired;diff --git a/test/read-transaction-early-result.test.ts b/test/read-transaction-early-result.test.tsnew file mode 100644index 0000000000..68afad5736--- /dev/null+++ b/test/read-transaction-early-result.test.ts@@ -0,0 +1,224 @@+/**+ * GBRA-156: a top-level search read transaction (withScopedReadTransaction with+ * alwaysTransaction, jitOffRead) hands its rows to the caller when its read+ * returns, without waiting for COMMIT's round trip (66 ms to a remote pooler,+ * once per search transaction). COMMIT still runs on the transaction's+ * connection, and the pool cannot give that connection to another statement+ * until COMMIT's answer. A failed COMMIT never surfaces as a read error. A+ * caller's own transaction still waits for its COMMIT.+ *+ * The real engine and vendored driver against a scripted server that holds+ * COMMIT's answer until the test releases it. Regression that fails it on the+ * base branch: the read stays pending until COMMIT is answered.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { createServer, type Server, type Socket } from 'node:net';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { withEnv } from './helpers/with-env.ts';++const frame = (type: string, body: Buffer = Buffer.alloc(0)): Buffer => {+ const header = Buffer.alloc(5);+ header.write(type, 0, 'ascii'); header.writeInt32BE(body.length + 4, 1);+ return Buffer.concat([header, body]);+};+const cstr = (s: string): Buffer => Buffer.from(s + '\0', 'utf8');+const int16 = (n: number) => { const b = Buffer.alloc(2); b.writeInt16BE(n); return b; };+const int32 = (n: number) => { const b = Buffer.alloc(4); b.writeInt32BE(n); return b; };+const ready = (inTx: boolean) => frame('Z', Buffer.from(inTx ? 'T' : 'I'));+const startupReply = Buffer.concat([+ frame('R', int32(0)),+ frame('S', Buffer.concat([cstr('server_version'), cstr('16.0')])),+ frame('K', Buffer.concat([int32(7), int32(9)])),+ ready(false),+]);++/** This statement answers one int4 row; every other statement answers no rows. */+const ANSWER = 'SELECT 41 + 1 AS answer';+const rowDescription = frame('T', Buffer.concat([int16(1), cstr('answer'), int32(0), int16(0), int32(23), int16(4), int32(-1), int16(0)]));+const dataRow = frame('D', Buffer.concat([int16(1), int32(2), Buffer.from('42')]));+const isCommit = (text: string) => /^\s*commit/i.test(text);+const tag = (text: string) => /^\s*begin/i.test(text) ? 'BEGIN' : isCommit(text) ? 'COMMIT' : /^\s*rollback/i.test(text) ? 'ROLLBACK' : text.includes(ANSWER) ? 'SELECT 1' : 'SELECT 0';++type Sent = { conn: number; text: string };++/** Answers the simple and extended protocol, tracks each connection's transaction status, and can hold one COMMIT. */+function scriptedServer() {+ const sent: Sent[] = [];+ let holdCommit = false, commitFails = false, connections = 0;+ let release: (() => void) | null = null;+ let arrived = Promise.withResolvers<void>();+ const server: Server = createServer((socket: Socket) => {+ const conn = ++connections;+ let buffered: Buffer = Buffer.alloc(0), started = false, inTx = false, skipping = false, portal = '';+ const statements = new Map<string, { text: string; params: number }>();+ const execute = (text: string): Buffer[] => {+ if (/^\s*begin/i.test(text)) inTx = true;+ if (/^\s*(commit|rollback)/i.test(text)) inTx = false;+ if (commitFails && isCommit(text)) {+ commitFails = false;+ return [frame('E', Buffer.concat([cstr('SERROR'), cstr('C08006'), cstr('Msynthetic commit failure'), Buffer.from([0])]))];+ }+ return [...(text.includes(ANSWER) ? [dataRow] : []), frame('C', cstr(tag(text)))];+ };+ const drain = () => {+ while (!release && buffered.length >= 5) {+ const type = String.fromCharCode(buffered[0]!), length = buffered.readInt32BE(1);+ if (buffered.length < length + 1) return;+ const body = buffered.subarray(5, length + 1);+ const first = body.indexOf(0);+ const text = type === 'Q' ? body.toString('utf8', 0, first)+ : type === 'P' ? body.toString('utf8', first + 1, body.indexOf(0, first + 1)) : '';+ if (holdCommit && isCommit(text)) {+ holdCommit = false;+ release = () => { release = null; drain(); };+ arrived.resolve();+ return;+ }+ buffered = buffered.subarray(length + 1);+ if (type === 'S') { skipping = false; socket.write(ready(inTx)); continue; }+ if (skipping) continue;+ if (type === 'P') {+ statements.set(body.toString('utf8', 0, first), { text, params: body.readInt16BE(body.indexOf(0, first + 1) + 1) });+ sent.push({ conn, text });+ socket.write(frame('1'));+ } else if (type === 'B') {+ portal = statements.get(body.toString('utf8', first + 1, body.indexOf(0, first + 1)))?.text ?? '';+ socket.write(frame('2'));+ } else if (type === 'D') {+ const statement = body[0] === 0x53 ? statements.get(body.toString('utf8', 1, body.indexOf(0, 1))) : undefined;+ const params = statement ? [frame('t', Buffer.concat([int16(statement.params), ...Array.from({ length: statement.params }, () => int32(25))]))] : [];+ socket.write(Buffer.concat([...params, (statement?.text ?? portal).includes(ANSWER) ? rowDescription : frame('n')]));+ } else if (type === 'E') {+ const out = execute(portal);+ if (out[0]![0] === 0x45) skipping = true;+ socket.write(Buffer.concat(out));+ } else if (type === 'C') {+ socket.write(frame('3'));+ } else if (type === 'Q') {+ sent.push({ conn, text });+ socket.write(Buffer.concat([...(text.includes(ANSWER) ? [rowDescription] : []), ...execute(text), ready(inTx)]));+ } else if (type === 'X') {+ socket.end();+ }+ }+ };+ socket.on('data', (chunk: Buffer) => {+ buffered = Buffer.concat([buffered, chunk]);+ if (!started) {+ if (buffered.length < 8 || buffered.length < buffered.readInt32BE(0)) return;+ buffered = buffered.subarray(buffered.readInt32BE(0)); started = true;+ socket.write(startupReply);+ }+ drain();+ });+ socket.on('error', () => undefined);+ });+ return {+ server, sent,+ /** Hold the next COMMIT's answer (an error when \`fails\`); \`commitArrived\` resolves once the server has it. */+ holdNextCommit(fails = false) { holdCommit = true; commitFails = fails; arrived = Promise.withResolvers<void>(); },+ get commitArrived() { return arrived.promise; },+ releaseCommit() { release?.(); },+ async listen(): Promise<number> {+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()));+ return (server.address() as { port: number }).port;+ },+ };+}++let teardown: Array<() => Promise<void>> = [];+afterEach(async () => {+ for (const step of teardown.reverse()) await step().catch(() => undefined);+ teardown = [];+});++const ENV = { GBRAIN_DISABLE_DIRECT_POOL: '1', GBRAIN_RLS_SCOPE_BINDING: undefined, GBRAIN_SQL_TRACE: undefined, GBRAIN_PREPARE: undefined, PGMAX_PIPELINE: undefined };++/** An engine whose pool has one connection (one server connection, as a pool at its cap) on a scripted server. */+async function fixture() {+ const srv = scriptedServer();+ const port = await srv.listen();+ teardown.push(() => new Promise<void>(resolve => srv.server.close(() => resolve())));+ const engine = new PostgresEngine();+ await engine.connect({ engine: 'postgres', database_url: 'postgresql://u:[email protected]:' + port + '/d?prepare=false', poolSize: 1, keyword_statement_timeout_ms: 8000 } as never);+ teardown.push(() => { srv.releaseCommit(); return engine.disconnect(); });+ return { srv, engine };+}++const settledWithin = <T>(promise: Promise<T>, ms: number) => Promise.race([promise, Bun.sleep(ms).then(() => 'pending' as const)]);+const textsAfter = (sent: Sent[], from: number) => sent.slice(from).map(s => s.conn + ':' + s.text.trim().split(/\s+/).slice(0, 2).join(' ').toLowerCase());++describe('search read transactions answer before COMMIT', () => {+ test('a search read resolves with its rows while COMMIT is unanswered; the pool cannot reuse the connection until COMMIT completes', () => withEnv(ENV, async () => {+ const { srv, engine } = await fixture();+ const from = srv.sent.length;+ srv.holdNextCommit();+ const read = engine.keywordBoundedRead(db => db.executeRaw(ANSWER));+ await srv.commitArrived;+ expect(await settledWithin(read, 1_000)).toEqual([{ answer: 42 }]);+ expect(engine.getPoolDiagnostics()!.tracked.tx).toBe(1);++ const next = engine.executeRaw('SELECT 2 AS next');+ expect(await settledWithin(next, 200)).toBe('pending');+ expect(srv.sent.some(s => s.text.includes('SELECT 2 AS next'))).toBe(false);++ srv.releaseCommit();+ expect(await settledWithin(next, 1_000)).toEqual([]);+ expect(textsAfter(srv.sent, from)).toEqual(['1:begin', "1:select set_config('statement_timeout',", '1:select 41', '1:commit', '1:select 2']);+ expect(engine.getPoolDiagnostics()!.tracked.tx).toBe(0);+ }));++ test('a jit-off read (backlink counts) resolves while COMMIT is unanswered', () => withEnv(ENV, async () => {+ const { srv, engine } = await fixture();+ srv.holdNextCommit();+ const read = engine.getBacklinkCounts([1]);+ await srv.commitArrived;+ expect(await settledWithin(read, 1_000)).toEqual(new Map([[1, 0]]));+ srv.releaseCommit();+ }));++ test('a failed COMMIT does not surface as a read error, and the pool keeps serving', () => withEnv(ENV, async () => {+ const { srv, engine } = await fixture();+ const unhandled: unknown[] = [];+ const onUnhandled = (reason: unknown) => { unhandled.push(reason); };+ process.on('unhandledRejection', onUnhandled);+ try {+ srv.holdNextCommit(true);+ const read = engine.keywordBoundedRead(db => db.executeRaw(ANSWER));+ await srv.commitArrived;+ expect(await settledWithin(read, 1_000)).toEqual([{ answer: 42 }]);+ srv.releaseCommit();+ expect(await settledWithin(engine.executeRaw(ANSWER), 1_000)).toEqual([{ answer: 42 }]);+ await Bun.sleep(20);+ expect(unhandled).toEqual([]);+ expect(engine.getPoolDiagnostics()!.tracked.tx).toBe(0);+ } finally {+ process.off('unhandledRejection', onUnhandled);+ }+ }));++ test('an error in the read still rejects the read and rolls back', () => withEnv(ENV, async () => {+ const { srv, engine } = await fixture();+ const from = srv.sent.length;+ await expect(engine.keywordBoundedRead(async () => { throw new Error('read sentinel'); })).rejects.toThrow('read sentinel');+ expect(await engine.executeRaw(ANSWER)).toEqual([{ answer: 42 }]);+ expect(textsAfter(srv.sent, from)).toEqual(['1:begin', "1:select set_config('statement_timeout',", '1:rollback', '1:select 41']);+ }));++ test("a caller's transaction still waits for its COMMIT", () => withEnv(ENV, async () => {+ const { srv, engine } = await fixture();+ srv.holdNextCommit();+ const write = engine.transaction(tx => tx.executeRaw(ANSWER));+ await srv.commitArrived;+ expect(await settledWithin(write, 200)).toBe('pending');+ srv.releaseCommit();+ expect(await settledWithin(write, 1_000)).toEqual([{ answer: 42 }]);+ }));++ test("inside a caller's transaction the search read is a savepoint that ends before the caller's COMMIT", () => withEnv(ENV, async () => {+ const { srv, engine } = await fixture();+ const from = srv.sent.length;+ expect(await engine.transaction(tx => tx.keywordBoundedRead(db => db.executeRaw(ANSWER)))).toEqual([{ answer: 42 }]);+ expect(textsAfter(srv.sent, from).filter(s => !/current_setting|set_config/.test(s))).toEqual(['1:begin', '1:savepoint "s0"', '1:select 41', '1:commit']);+ }));+});diff --git a/test/search-post-rerank-concurrency.test.ts b/test/search-post-rerank-concurrency.test.tsnew file mode 100644index 0000000000..f6468e13a5--- /dev/null+++ b/test/search-post-rerank-concurrency.test.ts@@ -0,0 +1,149 @@+/**+ * GBRA-156: a warm search's post-rerank reads that do not depend on each+ * other run at once. Each serial read costs one database round trip of wall+ * time on a pooled Postgres (66 ms through a remote PgBouncer).+ *+ * 1. Protects: the generated-page read overlaps the post-fusion boosts, the+ * alias hop's table read overlaps the reranker and feedback stage, the+ * alias fan-out's entity reads overlap the hybrid search, the page-trust+ * read overlaps evidence delivery, and the saved-fact match is one+ * statement (its existence probe gates the scan inside it).+ * 2. Fails when: any of those reads is awaited after the stage it overlaps+ * again, or the saved-fact probe becomes its own statement again.+ * 3. Existing coverage: test/search-provenance-demotion.test.ts,+ * test/search-alias-fanout.test.ts, test/search-other-names.test.ts and+ * test/search-response-meta-concurrency.test.ts pin what those reads find,+ * not when they are issued.+ * 4. Seam: none. Statement start and finish are observed on the PGLite handle+ * the engine uses (one connection, so a read issued before another one+ * answered was issued concurrently).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { basisEmbedding } from '../src/eval/deterministic-embed.ts';+import { installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';+import { hybridSearch } from '../src/core/search/hybrid.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';++let engine: PGLiteEngine;+const events: Array<{ at: 'start' | 'end'; sql: string; params: unknown[] }> = [];++async function seed(slug: string, type: string, text: string, title: string, frontmatter: Record<string, unknown> = {}) {+ await engine.putPage(slug, { type, title, compiled_truth: text, timeline: '', frontmatter } as never);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, [{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: basisEmbedding(7, 1536), token_count: 10 }] as never, { seal: true });+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await seed('companies/widget-co', 'company', 'Widget Co makes widgets. Widget renewal terms are net 30.', 'Widget Co');+ await seed('notes/widget-renewal', 'note', 'Widget renewal terms were agreed in March.', 'Widget renewal');+ await seed('notes/gadget-digest', 'note', 'Digest: gadget orders shipped on time.', 'Gadget digest', { dream_generated: true });+ await engine.setConfig('feedback.enabled', 'true');+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source) VALUES+ ('default', 'widget-co', 'Widget-co renewal terms moved to net 45.', 'fact', 'world', 'user update')`);+ const db = engine.db as unknown as { query: (sql: string, ...rest: unknown[]) => Promise<unknown> };+ const query = db.query.bind(db);+ db.query = (sql: string, ...rest: unknown[]) => {+ const text = sql.replace(/\s+/g, ' ').trim();+ const params = Array.isArray(rest[0]) ? rest[0] as unknown[] : [];+ events.push({ at: 'start', sql: text, params });+ return query(sql, ...rest).finally(() => events.push({ at: 'end', sql: text, params }));+ };+}, 120_000);++afterAll(async () => {+ await engine?.disconnect();+});++const first = (at: 'start' | 'end', match: (e: { sql: string; params: unknown[] }) => boolean) => events.findIndex(e => e.at === at && match(e));+const has = (needle: string) => (e: { sql: string }) => e.sql.includes(needle);++describe('hybrid search (fused path)', () => {+ const noRerank = { enabled: false, topNIn: 0, topNOut: null } as never;++ test('the generated-page read is issued before the post-fusion backlink read answers', async () => {+ events.length = 0;+ const rows = await hybridSearch(engine, 'gadget orders', { queryEmbedFn: () => basisEmbedding(7, 1536), reranker: noRerank });+ expect(rows.find(r => r.slug === 'notes/gadget-digest')?.provenance).toBe('generated');+ const generatedStart = first('start', has("frontmatter->>'dream_generated' = 'true'"));+ const backlinkEnd = first('end', has('COUNT(DISTINCT l.from_page_id)::int AS cnt'));+ expect(generatedStart).toBeGreaterThan(-1);+ expect(backlinkEnd).toBeGreaterThan(-1);+ expect(generatedStart).toBeLessThan(backlinkEnd);+ }, 60_000);++ test("the alias hop's table read is issued before the feedback stage's read answers", async () => {+ events.length = 0;+ const rows = await hybridSearch(engine, 'Widget Co renewal terms', { queryEmbedFn: () => basisEmbedding(7, 1536), reranker: noRerank });+ expect(rows.map(r => r.slug)).toContain('companies/widget-co');+ const aliasHop = (e: { sql: string; params: unknown[] }) => e.sql.startsWith('WITH a AS MATERIALIZED')+ && JSON.stringify(e.params[0]) === JSON.stringify(['widget co renewal terms']);+ const aliasHopStart = first('start', aliasHop);+ const feedbackEnd = first('end', has('p.content_hash, CASE WHEN w.weight IS NULL'));+ expect(aliasHopStart).toBeGreaterThan(-1);+ expect(feedbackEnd).toBeGreaterThan(-1);+ expect(aliasHopStart).toBeLessThan(feedbackEnd);+ }, 60_000);+});++describe('search op (remote)', () => {+ const search = (args: Record<string, unknown>) => dispatchToolCall(engine, 'search', args, { remote: true, transport: 'http', sourceId: 'default' });+ const text = (r: Awaited<ReturnType<typeof search>>) => r.content.map(c => c.text ?? '').join('\n');++ test('without an embedding provider the generated-page read is issued before the post-fusion backlink read answers', async () => {+ events.length = 0;+ const r = await search({ query: 'gadget orders' });+ expect(r.isError).toBeFalsy();+ expect(text(r)).toContain('notes/gadget-digest');+ const generatedStart = first('start', has("frontmatter->>'dream_generated' = 'true'"));+ const backlinkEnd = first('end', has('COUNT(DISTINCT l.from_page_id)::int AS cnt'));+ expect(generatedStart).toBeGreaterThan(-1);+ expect(backlinkEnd).toBeGreaterThan(-1);+ expect(generatedStart).toBeLessThan(backlinkEnd);+ }, 60_000);++ test("the alias fan-out's entity reads are issued before the hybrid search's content-flag read", async () => {+ events.length = 0;+ const r = await search({ query: 'Widget Co renewal terms' });+ expect(r.isError).toBeFalsy();+ expect(text(r)).toContain('companies/widget-co');+ const titleReadStart = first('start', has('lower(title) AS t FROM pages'));+ const contentFlagStart = first('start', has("frontmatter->'content_flag'->>'reason'"));+ expect(titleReadStart).toBeGreaterThan(-1);+ expect(contentFlagStart).toBeGreaterThan(-1);+ expect(titleReadStart).toBeLessThan(contentFlagStart);+ }, 60_000);++ test('the page-trust read is issued before the evidence read answers', async () => {+ events.length = 0;+ const r = await search({ query: 'widget renewal terms', return_unit: 'page' });+ expect(r.isError).toBeFalsy();+ expect(text(r)).toContain('"trust_tier"');+ const trustStart = first('start', has('trust_tier, write_origin'));+ const evidenceEnd = first('end', e => e.sql.startsWith('WITH req AS'));+ expect(trustStart).toBeGreaterThan(-1);+ expect(evidenceEnd).toBeGreaterThan(-1);+ expect(trustStart).toBeLessThan(evidenceEnd);+ }, 60_000);++ test('the saved-fact match is one statement and still finds the fact', async () => {+ events.length = 0;+ const r = await search({ query: 'widget renewal terms' });+ expect(r.isError).toBeFalsy();+ expect(text(r)).toContain('Widget-co renewal terms moved to net 45.');+ const factReads = events.filter(e => e.at === 'start' && /\bFROM facts f WHERE f\.source_id = ANY\(\$1::text\[\]\)/.test(e.sql));+ expect(factReads).toHaveLength(1);+ }, 60_000);++ test('a query no saved fact matches still costs one statement and reports none', async () => {+ events.length = 0;+ const r = await search({ query: 'gadget orders shipped' });+ expect(r.isError).toBeFalsy();+ expect(text(r)).not.toContain('Saved facts');+ const factReads = events.filter(e => e.at === 'start' && /\bFROM facts f WHERE f\.source_id = ANY\(\$1::text\[\]\)/.test(e.sql));+ expect(factReads).toHaveLength(1);+ }, 60_000);+});diff --git a/test/search/embedding-column.test.ts b/test/search/embedding-column.test.tsindex 433370072d..0135d3b725 100644--- a/test/search/embedding-column.test.ts+++ b/test/search/embedding-column.test.ts@@ -273,18 +273,18 @@ describe('D12 — defense-in-depth validation', () => {});describe('D3 — buildVectorCastFragment + quoteIdentifier', () => {- test('vector type emits $1::vector cast', () => {+ test('vector type emits $1::text::vector cast', () => {const r: ResolvedColumn = { name: 'embedding', type: 'vector', dimensions: 1536, embeddingModel: '' };const { col, castSql } = buildVectorCastFragment(r);expect(col).toBe('"embedding"');- expect(castSql).toBe('$1::vector');+ expect(castSql).toBe('$1::text::vector');});- test('halfvec type emits $1::halfvec(N) cast', () => {+ test('halfvec type emits $1::text::halfvec(N) cast', () => {const r: ResolvedColumn = { name: 'embedding_fixture', type: 'halfvec', dimensions: 2560, embeddingModel: 'fixture-provider:embedding-v1' };const { col, castSql } = buildVectorCastFragment(r);expect(col).toBe('"embedding_fixture"');- expect(castSql).toBe('$1::halfvec(2560)');+ expect(castSql).toBe('$1::text::halfvec(2560)');});test('quoteIdentifier wraps in double quotes', () => {diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex 3bf0ae20b7..656e674bff 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -239,7 +239,7 @@ describe('source scope strategy: walk overfetch, walk skip and scope scan', () =expect(cte).toContain('AND cc.language = $4');expect(cte).toContain('AND (cc.model=$6 OR');expect(cte).not.toContain(MD5);- expect(cte).toContain('ORDER BY (cc."embedding" <=> $1::vector) + 0, cc.id');+ expect(cte).toContain('ORDER BY (cc."embedding" <=> $1::text::vector) + 0, cc.id');expect(cte).toContain(`LIMIT $${stmt.innerLimitIdx + 1}\n`);expect(scan).toContain('JOIN content_chunks cc ON cc.id = scope_scan.id');expect(scoredCte(scan)).toContain('WHERE $6::text IS NULL OR hash_current');diff --git a/test/serve-request-round-trips.test.ts b/test/serve-request-round-trips.test.tsnew file mode 100644index 0000000000..0821f61150--- /dev/null+++ b/test/serve-request-round-trips.test.ts@@ -0,0 +1,213 @@+/**+ * GBRA-156: serial database round trips a warm serve request pays around its operation.+ *+ * 1. Protects: a warm request resolves its source and reads the config table in one round trip, on the warm CLI socket+ * and on MCP stdio, with the same resolved source; the MCP hot-memory hook runs beside a read op's handler, and+ * reads its two cache revalidation keys (withdrawal watermark, trust generation) together.+ * 2. Fails when: a source-resolution or config read waits on another one (the merged config before the resolution,+ * tier 5's config key behind the tier-4 listing, the tier-5.5 emptiness probe behind the listing, the federated+ * set's own sources read, stdio resolving outside the request's config snapshot), or the hook starts only after a+ * read op settles, or it reads the watermark and the generation one after the other again.+ * 3. Existing coverage: test/cold-read-folded-statements.test.ts counts the sources reads of one snapshot, not their+ * order; test/facts-context-injection.serial.test.ts pins the hook's payload, not when it runs.+ * 4. Seam: none. test/helpers/statement-depth.ts holds every PGLite statement and records its serial depth; the stdio+ * arm runs the real `startMcpServer` (test/fixtures/mcp-stdio-round-trip-driver.ts).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { executeCliSocketRequest } from '../src/core/cli-socket/execute.ts';+import { cliSocketIdentity } from '../src/core/cli-socket/identity.ts';+import { withRequestConfigSnapshot } from '../src/core/config-snapshot.ts';+import { explicitReadBinding, localFederatedSourceIds, resolveSourceWithTier } from '../src/core/source-resolver.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { __resetHotMemoryCacheForTests, getBrainHotMemoryMeta } from '../src/core/facts/meta-hook.ts';+import { recordStatementDepth, type DepthRecord } from './helpers/statement-depth.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++/** The reads a request makes to resolve its source and load its config. */+const RESOLUTION = /^SELECT (key, value|value) FROM config\b|\bFROM sources (ORDER BY id|WHERE)\b|^SELECT 1 AS one FROM pages WHERE source_id = 'default'/;+const WITHDRAWALS = /FROM fact_withdrawals WHERE source_id/;+const GENERATION = /FROM trust_policy_state WHERE id = 1/;+const SEARCH = /^WITH (top_pages|ranked) AS/;++/** Every read before the operation's first statement, and that first statement. */+function resolutionThenOp(records: DepthRecord[]): { resolution: DepthRecord[]; op: DepthRecord } {+ const first = records.findIndex(r => !RESOLUTION.test(r.sql));+ return { resolution: records.slice(0, first), op: records[first]! };+}++let engine: PGLiteEngine;+let depth: ReturnType<typeof recordStatementDepth>;+let root: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ depth = recordStatementDepth(engine);+ root = mkdtempSync(join(tmpdir(), 'gbrain-serve-round-trips-'));+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(root, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ __resetHotMemoryCacheForTests();+ const side = join(root, 'source-a-example');+ mkdirSync(side, { recursive: true });+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('source-a', 'source-a', $1, '{"federated": true}'::jsonb)`, [side]);+});++async function traced(fn: () => Promise<unknown>): Promise<DepthRecord[]> {+ depth.reset();+ await fn();+ return [...depth.records];+}++describe('warm CLI socket request', () => {+ const search = () => executeCliSocketRequest(engine, {+ v: 1, identity: cliSocketIdentity({ config: { engine: 'postgres' }, brainId: 'host', configDir: '/nonexistent', configFile: '/nonexistent/config.json', version: 'x', env: {} }),+ command: 'search', kind: 'op', op: 'search', params: { query: 'alpha' }, routing: { cwd: root, source_env: null }, cli: { quiet: true, timeout_ms: null },+ });++ test('resolves its source (tier 5.5) and reads its config in one round trip, then runs the op', async () => {+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {+ await search();+ let kind: unknown;+ const records = await traced(async () => { kind = (await search()).frame.kind; });+ const { resolution, op } = resolutionThenOp(records);+ expect(kind).toBe('result');+ expect(resolution.length).toBeGreaterThanOrEqual(2);+ expect(resolution.map(r => r.depth)).toEqual(resolution.map(() => 1));+ expect(op.depth).toBe(2);+ });+ });+});++describe('source resolution inside a request snapshot', () => {+ for (const defaultPages of [false, true]) {+ test(`tier 5.5 with ${defaultPages ? 'a non-empty' : 'an empty'} 'default': one round trip, the same answer as live reads`, async () => {+ if (defaultPages) await engine.putPage('notes/default-example', { type: 'note', title: 'Default example', compiled_truth: 'body' });+ const resolveScope = async () => {+ const resolved = await resolveSourceWithTier(engine, null, root);+ return { ...resolved, federated: await localFederatedSourceIds(engine, resolved.source_id, resolved.tier) };+ };+ await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE: '1' }, async () => {+ const live = await resolveScope();+ let snapshot: unknown;+ const records = await traced(async () => { snapshot = await withRequestConfigSnapshot(engine, resolveScope); });+ expect(live.source_id).toBe(defaultPages ? 'default' : 'source-a');+ expect(snapshot).toEqual(live);+ expect(records.map(r => r.depth)).toEqual(records.map(() => 1));+ });+ });+ }++ test('an env-bound source is checked against the request\'s rows, not by its own read', async () => {+ const bind = async () => {+ const resolved = await resolveSourceWithTier(engine, null, root, { env: 'source-a' });+ return { ...resolved, binding: await explicitReadBinding(engine, resolved.source_id, resolved.tier) };+ };+ const live = await bind();+ let snapshot: unknown;+ const records = await traced(async () => { snapshot = await withRequestConfigSnapshot(engine, bind); });+ expect(snapshot).toEqual(live);+ expect(records.map(r => r.depth)).toEqual([1]);+ await expect(withRequestConfigSnapshot(engine, () => resolveSourceWithTier(engine, null, root, { env: 'source-missing' }))).rejects.toThrow(/not found or is archived/);+ });+});++describe('MCP hot-memory hook', () => {+ test('runs beside a read op and reads the withdrawal watermark and the trust generation together', async () => {+ const call = () => dispatchToolCall(engine, 'search', { query: 'alpha' }, { remote: true, sourceId: 'default', transport: 'stdio', metaHook: getBrainHotMemoryMeta });+ await call();+ __resetHotMemoryCacheForTests();+ const records = await traced(call);+ const withdrawals = records.find(r => WITHDRAWALS.test(r.sql))!;+ const generation = records.find(r => GENERATION.test(r.sql))!;+ const search = records.find(r => SEARCH.test(r.sql))!;+ expect(generation.depth).toBe(withdrawals.depth);+ expect(withdrawals.depth).toBeLessThanOrEqual(search.depth);+ });+});++describe('MCP stdio warm search (real startMcpServer)', () => {+ const REPO_ROOT = resolve(import.meta.dir, '..');+ const DRIVER = join(REPO_ROOT, 'test', 'fixtures', 'mcp-stdio-round-trip-driver.ts');+ const CHILD_STRIP = ['GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'GBRAIN_SURFACE', 'GBRAIN_MCP_FORCE_SURFACE', 'GBRAIN_MCP_INSTRUCTIONS'];++ test('resolves its source and reads config in one round trip; the hook runs beside the op', async () => {+ const parent = mkdtempSync(join(tmpdir(), 'gbrain-stdio-round-trips-'));+ const log = join(parent, 'statements.ndjson');+ writeFileSync(log, '');+ mkdirSync(join(parent, '.gbrain'), { recursive: true });+ writeFileSync(join(parent, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(parent, 'db'), embedding_dimensions: 1536 }));+ const env = { ...process.env } as Record<string, string>;+ for (const k of CHILD_STRIP) delete env[k];+ Object.assign(env, { GBRAIN_HOME: parent, HOME: parent, GBRAIN_SWEEP: '0', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SERVE_SYNC_IPC: '0', ROUND_TRIP_LOG: log });+ const proc = Bun.spawn([process.execPath, DRIVER], { cwd: parent, env, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });+ const responses = new Map<number, unknown>();+ const reader = (async () => {+ const decoder = new TextDecoder();+ let buf = '';+ for await (const chunk of proc.stdout) {+ buf += decoder.decode(chunk, { stream: true });+ let nl: number;+ while ((nl = buf.indexOf('\n')) >= 0) {+ const msg = JSON.parse(buf.slice(0, nl));+ buf = buf.slice(nl + 1);+ if (typeof msg.id === 'number') responses.set(msg.id, msg.result ?? msg.error);+ }+ }+ })();+ const send = (msg: unknown) => { proc.stdin.write(JSON.stringify(msg) + '\n'); proc.stdin.flush(); };+ const waitFor = async (id: number) => {+ const deadline = Date.now() + 60_000;+ while (!responses.has(id)) {+ if (proc.exitCode !== null) throw new Error(`driver exited ${proc.exitCode}: ${await new Response(proc.stderr).text()}`);+ if (Date.now() > deadline) throw new Error(`no response ${id}`);+ await Bun.sleep(10);+ }+ return responses.get(id);+ };+ const logged = () => readFileSync(log, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line) as DepthRecord);+ const searchCall = (id: number) => send({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'search', arguments: { query: 'alpha' } } });+ try {+ send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'round-trips', version: '0' } } });+ await waitFor(1);+ send({ jsonrpc: '2.0', method: 'notifications/initialized' });+ searchCall(2);+ await waitFor(2);+ await Bun.sleep(500);+ const before = logged().length;+ searchCall(3);+ const result = await waitFor(3) as { isError?: boolean };+ await Bun.sleep(200);+ const call = logged().slice(before);+ const base = call[0]!.depth - 1;+ const records = call.map(r => ({ ...r, depth: r.depth - base }));+ expect(result.isError).toBeFalsy();+ const { resolution, op } = resolutionThenOp(records);+ expect(resolution.length).toBeGreaterThanOrEqual(2);+ expect(resolution.map(r => r.depth)).toEqual(resolution.map(() => 1));+ expect(op.depth).toBe(2);+ const withdrawals = records.find(r => WITHDRAWALS.test(r.sql));+ const generation = records.find(r => GENERATION.test(r.sql));+ const search = records.find(r => SEARCH.test(r.sql))!;+ expect(withdrawals?.depth).toBe(generation?.depth);+ expect(withdrawals!.depth).toBeLessThanOrEqual(search.depth);+ } finally {+ proc.kill('SIGKILL');+ await proc.exited;+ await reader.catch(() => {});+ rmSync(parent, { recursive: true, force: true });+ }+ }, 120_000);+});