Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): W5 page-unit ranking cut from the caller's budget (search.page_rank_budget_ratio, default off)
garrytanfe9e0397b7e5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e622f1940d..d5010b056a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,14 +10,15 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).-## [Unreleased] - memory proof wave 2 W3, confidence-gated reranking (#6445)+## [Unreleased] - memory proof wave 2 W3 + W5, confidence-gated reranking and the page-unit ranking cut (#6445)-**Search can skip the cross-encoder when retrieval already found the answer. It is off by default; `shadow` measures how often that happens without changing results.**+**Search can skip the cross-encoder when retrieval already found the answer, and a page-unit call's own budget can size its ranked hits. Both are off by default; `shadow` measures how often the skip would happen without changing results.**### Itemized changes- `search.reranker.gate` (off by default) grades search candidates before the cross-encoder. `shadow` records how often the reranker was paying for an answer retrieval already found, in the response's `rerank_gate` metadata, on `--explain` and in a new `rerank_gate` section of `gbrain search stats`, and leaves results unchanged. `on` skips the cross-encoder when the top result is a strong vector match (cosine at least `search.evidence_cosine_floor` and `search.reranker.gate_min_gap` ahead of every other page); that skip is reported as `rerank_gate.skipped`, not as a degradation. The cache key now includes the gate keys and `search.evidence_cosine_floor`.- `scripts/bench-rerank-gate-latency.ts` measures the gate's latency: recall plus query per question with the gate off and on, warm-up, alternating arm order and fixed concurrency, reporting the mean saving per skipped query and the p95 change.+- `search.page_rank_budget_ratio` (off by default) lets a `return_unit: "page"` call's own budget size the ranked hit list. Today ranking cuts hits to the mode's `search.tokenBudget` whatever the caller asked for, so under tokenmax delivery is handed far more pages than fit and returns them as slivers. With a ratio set, `search`, `query` and `recall` cut to `min(mode cut, ratio × caller budget)` and report it as `page_rank_cut`. Calls without a budget and other units are unchanged.## [0.60.169.0] - 2026-10-11diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 3a061d4b73..62427dfc88 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -6,6 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`. Under `on` `rerankAndPin` awaits the grade first: `would_skip` skips the provider call, keeps fused order through the reranker's own `topNOut` slice (`sliceTopNOut`, shared with `applyReranker`), runs the feedback stage on fused scores, does not fire the relational rerank pin, and stamps `skipped: true` with `provider_called: false`; nothing goes into `degraded[]` (a deliberate skip, not `reranker_skipped`), and `--explain` prints `rerank skipped (gate: <reason>)`. 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), `test/search/rerank-gate-skip.test.ts` (`on`, both engines; fixture in `test/helpers/rerank-gate-fixture.ts`) and the gate case in `test/search/relational-rerank-pin-hybrid.serial.test.ts` (no pin, no autocut under a skip).- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.+- `src/core/search/page-rank-cut.ts` — W5 page-unit ranking cut (default off): with `return_unit: page`, a caller budget and `search.page_rank_budget_ratio` set, `resolveEvidencePlan` stores `rankCut` (ratio × budget) on the plan; `search`/`query`/`recall` pass it as `HybridSearchOpts.pageRankCut`, and `applyPageRankCut` folds `min(mode tokenBudget, cut)` into the resolved knobs in both the inner request and the cache resolver. `meta.page_rank_cut` reports ratio, caller budget, mode cut, applied cut, candidates and kept. Tests: `test/search/page-rank-cut.test.ts` (both engines).- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.mdindex cd23b04f24..aba60adec2 100644--- a/docs/evidence-delivery.md+++ b/docs/evidence-delivery.md@@ -103,6 +103,18 @@ Per-call params on `search`, `query`, `recall`:`query`'s `token_budget` still prunes chunks (chunk mode), and `recall`'s`budget_tokens` / `budget_policy` still pack chunks (facts first), so any ofthem keeps an implied `auto` on `chunk`.+- Page-unit ranking cut (off by default): ranking cuts its hits to the search+ mode's `search.tokenBudget` (4,000 under conservative, none under tokenmax)+ before delivery packs whole pages, whatever the caller's budget. With+ `gbrain config set search.page_rank_budget_ratio <ratio>` (a positive+ number, for example `0.5`), a `return_unit: "page"` call that passes its own+ budget on `search`, `query` or `recall` cuts ranked hits to+ `min(mode cut, ratio × budget)` instead, so delivery is not handed more pages+ than it can deliver whole. The response reports it as `page_rank_cut`+ (`ratio`, `caller_budget`, `mode_cut` (null under tokenmax), `applied_cut`,+ `candidates`, `kept`). A page call without a budget, every other unit, and+ recall's keyword-only arm are unchanged. `gbrain config unset+ search.page_rank_budget_ratio` turns it off.Think reads `think.return_unit` (default `auto`) and never`search.return_unit`, so changing search's default does not change `think`.@@ -143,7 +155,7 @@ applies to `search`, `query`, `recall`, `think` and `assemble_evidence`.Config keys: `search.return_unit`, `search.return_window`,`search.return_budget_default`, `search.return_budget_conversation`,`search.return_budget_max_remote`, `search.evidence_date_header`, `search.auto_packing`,-`think.return_unit`. Kill switch:+`search.page_rank_budget_ratio`, `think.return_unit`. Kill switch:`gbrain config set search.return_unit chunk` and`gbrain config set think.return_unit chunk` (or pass `return_unit: "chunk"`per call).diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex a62336ad6e..59893d7bf5 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -46,7 +46,7 @@ src/core/minions/handlers/subagent.ts runSubagentViaGateway 329 seed: W5 baselinsrc/core/minions/queue.ts MinionQueue.add 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/minions/worker.ts MinionWorker.start 470 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/ops/facts.ts recall.handler 351 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4830 (W14 PR3): every hit names its source_id, falling back to the scope's single source (the federated case stays absent)+src/core/ops/facts.ts recall.handler 354 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #4830 (W14 PR3): every hit names its source_id, falling back to the scope's single source (the federated case stays absent); +3 W5: recall threads the page-unit ranking cut into its hybrid page arm and reports page_rank_cut (logic in search/page-rank-cut.ts)src/core/ops/search.ts query.handler 332 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 GBRA-49 explain_target: one TargetTrace prep line and its HybridSearchOpts thread (diagnosis/meta live in prepareExplainTarget/finishExplainTarget)src/core/progressive-batch/orchestrator.ts runProgressiveBatch 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/remediation/run.ts runRemediation 428 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 4cc63dcd9c..9aca456275 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -22,8 +22,8 @@ src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live insrc/core/operations.ts 240 ratchet 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)src/core/pglite-engine.ts 3012 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 W13src/core/postgres-engine.ts 3015 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)-src/core/search/hybrid.ts 1641 ratchet +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); +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); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured)-src/core/types.ts 2279 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); +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); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured)+src/core/search/hybrid.ts 1643 ratchet +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); +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); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured)+src/core/types.ts 2281 ratchet +2 W5 page-unit ranking cut: HybridSearchMeta.page_rank_cut (PageRankCutMeta in search/page-rank-cut.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); +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); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured)src/core/minions/queue.ts 2528 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)src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,11 +36,11 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1931 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1951 ratchet +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured)+src/core/config.ts 1952 ratchet +1 W5: search.page_rank_budget_ratio KNOWN_CONFIG_KEYS row (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured)src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)src/core/search/mode.ts 1647 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)src/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)src/commands/doctor/checks/extraction-sync.ts 1512 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import)-src/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)+src/core/search/evidence-delivery.ts 1517 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)diff --git a/src/core/config.ts b/src/core/config.tsindex 80c2cae511..2c6eed60c5 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1413,6 +1413,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.entity_anchoring', // entity-anchored retrieval for entity-scoped current-state query/search (default off; search/entity-anchor.ts)'search.query_facts_arm', // query adds matching active facts as rows in spare capacity (default on; search/facts-arm.ts)'search.temporal_fact_reserve', // temporal-cue queries reserve up to 15% of the token budget for question-ranked dated facts (default off; search/facts-arm.ts)+ 'search.page_rank_budget_ratio', // W5: page unit + caller token_budget cuts ranked hits to min(mode cut, ratio x budget) (default off; search/page-rank-cut.ts)'think.return_unit',// Models tier system (v0.31.12)'models.default',diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 441ab328ea..97b2763203 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -26,7 +26,7 @@ import { OperationError, opError, verbError } from './contract.ts';import { invalidParam, paramUse } from './op-fix.ts';import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam, sourceScopeOpts, stampEvidenceSafe } from './context.ts';import { markKeywordHits } from '../search/evidence.ts';-import { hybridSearchCached, stampContentFlags } from '../search/hybrid.ts';+import { hybridSearchCached, stampContentFlags, type HybridSearchOpts } from '../search/hybrid.ts';import { dedupResults } from '../search/dedup.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';import { packToBudget, estimateTokens, resultTokens } from '../search/token-budget.ts';@@ -38,6 +38,7 @@ import { ENTITY_HINTS_CAP } from '../facts/extract.ts';import { parseTtlShorthand } from '../facts/ttl-parse.ts';import { MEMORY_VERBS_VERSION } from '../verbs.ts';import type { SearchResult } from '../types.ts';+import type { PageRankCutMeta } from '../search/page-rank-cut.ts';import type { BrainEngine, FactRow } from '../engine.ts';import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';import { hasScope } from '../scope.ts';@@ -477,7 +478,10 @@ const recall: Operation = {let searchResults: SearchResult[] = [];let searchDegraded: string | undefined;let delivery: DeliveryMeta | undefined;+ let pageRankCut: PageRankCutMeta | undefined;const evidencePlan = queryText ? await recallEvidencePlan(ctx, p) : null;+ const rankCutOpts: Pick<HybridSearchOpts, 'pageRankCut' | 'onMeta'> = evidencePlan?.rankCut+ ? { pageRankCut: evidencePlan.rankCut, onMeta: (m) => { pageRankCut = m.page_rank_cut; } } : {};if (queryText) {// #3242 parity (#4707): the page-search arm widens an unqualified// no-grant caller across the transport-computed federated set, exactly@@ -489,7 +493,7 @@ const recall: Operation = {// untrusted callers with the excludePrivate resolved above.const keywordOnly = await recallKeywordOnlyReason(ctx);if (keywordOnly) {- searchResults = await keylessRecallRows(ctx, queryText, limit, excludePrivate, searchScope);+ searchResults = await keylessRecallRows(ctx, queryText, limit, excludePrivate, searchScope, rankCutOpts);searchDegraded = keywordOnly;} else {searchResults = await hybridSearchCached(ctx.engine, queryText, {@@ -499,6 +503,7 @@ const recall: Operation = {requireSafeChunks: ctx.remote !== false,takesHoldersAllowList: readHolders(ctx),...searchScope,+ ...rankCutOpts,});}bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));@@ -608,6 +613,7 @@ const recall: Operation = {: {}),...(budgetPacking ? { budget_packing: budgetPacking } : {}),...(delivery ? { delivery } : {}),+ ...(pageRankCut ? { page_rank_cut: pageRankCut } : {}),};},};@@ -1316,11 +1322,12 @@ async function recallKeywordOnlyReason(ctx: OperationContext): Promise<string |async function keylessRecallRows(ctx: OperationContext, queryText: string, limit: number, excludePrivate: boolean,searchScope: { sourceId?: string; sourceIds?: string[]; minTrust?: TrustTier },+ rankCutOpts: Pick<HybridSearchOpts, 'pageRankCut' | 'onMeta'> = {},): Promise<SearchResult[]> {if (await keylessChainQuestion(ctx, queryText)) {return hybridSearchCached(ctx.engine, queryText, {limit, expansion: false, excludePrivate, requireSafeChunks: ctx.remote !== false,- takesHoldersAllowList: readHolders(ctx), ...searchScope,+ takesHoldersAllowList: readHolders(ctx), ...searchScope, ...rankCutOpts,});}const rows = dedupResults(await ctx.engine.searchKeyword(queryText, { limit, excludePrivate, requireSafeChunks: ctx.remote !== false, ...searchScope }));diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 46a032a492..f6c02018f1 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -474,6 +474,7 @@ async function buildRetrievalResponseMeta(...(m.answerability ? { answerability: m.answerability } : {}),...(m.relational_plan ? { relational_plan: m.relational_plan } : {}),...(m.rerank_gate ? { rerank_gate: m.rerank_gate } : {}),+ ...(m.page_rank_cut ? { page_rank_cut: m.page_rank_cut } : {}),} : {}),...((m?.degraded !== undefined || degraded.length > 0) ? { degraded } : {}),projection_readiness: readiness,@@ -751,6 +752,7 @@ const search: Operation = {salience: p.salience as 'off' | 'on' | 'strong' | undefined,recency: p.recency as 'off' | 'on' | 'strong' | undefined,decide: { remote: ctx.remote !== false },+ ...(plan?.rankCut ? { pageRankCut: plan.rankCut } : {}),};const primary = await hybridSearchCached(ctx.engine, queryText, {...searchOpts, onMeta: (m) => { capturedMeta = m; }, explain: p.explain === true, explainTarget: explainPrep?.trace,@@ -979,6 +981,7 @@ const query: Operation = {until: typeof p.until === 'string' ? p.until : undefined,// v0.32.x search-lite: token budget + cache opt-outs.tokenBudget: !plan && typeof p.token_budget === 'number' ? (p.token_budget as number) : undefined,+ ...(plan?.rankCut ? { pageRankCut: plan.rankCut } : {}),useCache: typeof p.use_cache === 'boolean' ? (p.use_cache as boolean) : undefined,intentWeighting: typeof p.intent_weighting === 'boolean' ? (p.intent_weighting as boolean) : undefined,// v0.36 cross-modal routing param.diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 64ceda6077..a0049cdc28 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -36,6 +36,7 @@ import { loadFenceChunkOverlay, markFenceChunk, splitFenceOverlay, type FenceChuimport { stripChunkHeader } from '../chunkers/code.ts';import { OperationError } from '../ops/contract.ts';import { blockDateHeaders, evidenceDateHeaderEnabled } from './evidence-date.ts';+import { resolvePageRankCut, type PageRankCut } from './page-rank-cut.ts';export { pagePlanHits } from './page-plan-hits.ts';import { applyEffectiveDate } from '../utils.ts';import { configPacking, MIN_EXPLICIT_AUTO_BUDGET, parseAutoPacking, type AutoPacking } from './evidence-packing.ts';@@ -130,6 +131,8 @@ export interface EvidencePlan {budgetClamped?: { requested: number; max: number };/** `search.evidence_date_header` is on: each block starts with its date header line. */dateHeader?: true;+ /** W5: page unit + caller budget + `search.page_rank_budget_ratio` set (page-rank-cut.ts). */+ rankCut?: PageRankCut;}/** The cap runs only under `auto`, with a budget the caller passed and a packing other than `off`. */@@ -263,6 +266,7 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePlabudget = max;}}+ const rankCut = unit === 'page' && budgetExplicit ? await resolvePageRankCut(engine, budget) : undefined;return {requestedUnit: unit,unit,@@ -273,6 +277,7 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePlapacking,...(budgetClamped ? { budgetClamped } : {}),...(await evidenceDateHeaderEnabled(engine) ? { dateHeader: true as const } : {}),+ ...(rankCut ? { rankCut } : {}),};}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 392bb2a274..780c36dc25 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -910,6 +910,8 @@ export interface HybridSearchOpts extends SearchOpts {* in BOTH the inner search and the cache resolver (knobs hash `rrg=`).*/rerankGate?: import('./crag.ts').RerankGateMode;+ /** W5: page-unit ranking cut (page-rank-cut.ts), min()'d into tokenBudget in the inner search and the cache resolver. */+ pageRankCut?: import('./page-rank-cut.ts').PageRankCut;/*** explain_target (explain-target.ts): when set, each pipeline stage records* whether the target page was present and at what rank. Observation only —diff --git a/src/core/search/hybrid/cache-stages.ts b/src/core/search/hybrid/cache-stages.tsindex a4e5ab25a8..f57d709f81 100644--- a/src/core/search/hybrid/cache-stages.ts+++ b/src/core/search/hybrid/cache-stages.ts@@ -20,6 +20,7 @@ import { normalizeExpansionVariantBudget } from '../fusion-lists.ts';import { normalizeKeywordArmConfidenceFloor } from '../arm-confidence.ts';import { normalizeMetadataBoostGate } from '../metadata-boost-gate.ts';import { normalizeRerankGate } from '../crag.ts';+import { applyPageRankCut } from '../page-rank-cut.ts';import { normalizeRelationalRerankPin } from '../relational-rerank-pin.ts';import { recordSearchTelemetry } from '../telemetry.ts';import { resolveEffectiveRecency, resolveEffectiveSalience } from './effective-modes.ts';@@ -43,7 +44,7 @@ export async function resolveCacheSearchMode(engine: BrainEngine, opts: HybridSe// conservative read. See [CDX-4] in the plan.const { loadSearchModeConfig, resolveSearchMode, knobsHash } = await import('../mode.ts');const modeInputForCache = await loadSearchModeConfig(engine);- const resolvedForCache = resolveSearchMode({+ const { knobs: resolvedForCache } = applyPageRankCut(resolveSearchMode({// T4/D5 — per-call mode folds into the cache key (resolved_mode is part// of knobsHash) so a per-call `--mode tokenmax` read can't be served a// server-default-mode cache row.@@ -94,7 +95,7 @@ export async function resolveCacheSearchMode(engine: BrainEngine, opts: HybridSe// W3 — rerank gate per-call thread-through (eval A/B; knobsHash `rrg=`).reranker_gate: normalizeRerankGate(opts?.rerankGate),},- });+ }), opts?.pageRankCut);return { modeInputForCache, resolvedForCache, knobsHash };}diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex bfeb342d9f..3e717a09ba 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -29,6 +29,7 @@ import { resolveCjkKeywordDeadlineMs } from '../cjk-keyword-deadline.ts';import { resolveSearchDateBounds } from '../date-bounds.ts';import { type DecideSearchContext, decideMetaFor, resolveAndLaunchDecide } from '../decide-stage.ts';import { applySearchIntent } from '../decide-retrieval.ts';+import { applyPageRankCut, type PageRankCutMeta } from '../page-rank-cut.ts';/*** Everything the stages read, resolved once at hybridSearch entry, plus the@@ -72,6 +73,8 @@ export interface HybridRequest {rerankMeta?: { model_resolved: string };/** Set by the relational arm when the multi-hop planner ran (meta.relational_plan). */relationalPlan?: import('../relational-recall.ts').RelationalPlanMeta;+ /** W5: the page-unit ranking cut folded into resolvedMode.tokenBudget (meta.page_rank_cut). */+ pageRankCut?: PageRankCutMeta;}const DEBUG = process.env.GBRAIN_SEARCH_DEBUG === '1';@@ -93,7 +96,7 @@ export async function resolveHybridRequest(// (#4359) hybridSearchCached threads its already-loaded snapshot; reuse it.const { loadSearchModeConfig, resolveSearchMode } = await import('../mode.ts');const modeInput = opts?._searchModeInput ?? await loadSearchModeConfig(engine);- const resolvedMode = resolveSearchMode({+ const { knobs: resolvedMode, meta: pageRankCut } = applyPageRankCut(resolveSearchMode({// T4/D5 — per-call mode selector (e.g. `--mode tokenmax`). The op layer// only passes this for trusted/local callers; remote callers leave it// undefined and fall through to the server-configured mode (no cost@@ -143,7 +146,7 @@ export async function resolveHybridRequest(// W3 — rerank gate per-call thread-through (eval A/B; knobsHash `rrg=`).reranker_gate: normalizeRerankGate(opts?.rerankGate),},- });+ }), opts?.pageRankCut);// System One: resolve the decide context and launch S2 now, alongside the// regex classifier (undefined when every slot is off: no decide work).@@ -310,6 +313,7 @@ export async function resolveHybridRequest(lastRank1Score: undefined,};if (decide) req.decide = decide;+ if (pageRankCut) req.pageRankCut = pageRankCut;return req;}@@ -344,7 +348,10 @@ export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult// never waits.export function emitHybridMeta(req: HybridRequest, armMeta: HybridSearchMeta): void {const { engine, opts } = req;- const rawMeta = req.keywordCandidates ? { ...armMeta, keyword_candidates: req.keywordCandidates } : armMeta;+ const cutMeta: HybridSearchMeta = req.pageRankCut+ ? { ...armMeta, page_rank_cut: { ...req.pageRankCut, candidates: armMeta.retrieved_count, ...(armMeta.token_budget ? { kept: armMeta.token_budget.kept } : {}) } }+ : armMeta;+ const rawMeta = req.keywordCandidates ? { ...cutMeta, keyword_candidates: req.keywordCandidates } : cutMeta;const decide = decideMetaFor(req.decide);const answerability = req.decide?.answerability;const meta: HybridSearchMeta = decide || req.rerankMeta || answerability || req.relationalPlandiff --git a/src/core/search/page-rank-cut.ts b/src/core/search/page-rank-cut.tsnew file mode 100644index 0000000000..005c697bd5--- /dev/null+++ b/src/core/search/page-rank-cut.ts@@ -0,0 +1,62 @@+/**+ * W5 (memory proof wave 2): page-unit ranking cut from the caller's budget.+ *+ * With `return_unit: "page"` and a caller `token_budget`, delivery packs whole+ * pages into that budget, but ranking still cut its hits to the mode's+ * `search.tokenBudget` (4000 conservative, none under tokenmax). Under tokenmax+ * delivery was handed far more pages than it could deliver whole, and each+ * arrived as a sliver. `search.page_rank_budget_ratio` (default off) cuts the+ * ranked hits to `ratio x caller budget`, or to the mode's cut when that is+ * smaller. Chunk-unit calls and calls without a caller budget never engage it.+ */+import type { BrainEngine } from '../engine.ts';+import type { ResolvedSearchKnobs } from './mode.ts';++export const PAGE_RANK_BUDGET_RATIO_KEY = 'search.page_rank_budget_ratio';++/** The cut a page-unit plan asks ranking to apply (resolved once per call). */+export interface PageRankCut {+ ratio: number;+ caller_budget: number;+ tokens: number;+}++/** `meta.page_rank_cut`: the applied cut, plus the hits before and after it. */+export interface PageRankCutMeta {+ ratio: number;+ caller_budget: number;+ /** The mode's `search.tokenBudget`; null when the mode has none (tokenmax). */+ mode_cut: number | null;+ applied_cut: number;+ candidates?: number;+ kept?: number;+}++/** Null when the key is unset, not a positive finite number, or unreadable (off). */+export async function readPageRankBudgetRatio(engine: BrainEngine): Promise<number | null> {+ try {+ const raw = await engine.getConfig(PAGE_RANK_BUDGET_RATIO_KEY);+ if (raw == null || raw === '') return null;+ const n = Number(raw);+ return Number.isFinite(n) && n > 0 ? n : null;+ } catch {+ return null;+ }+}++export async function resolvePageRankCut(engine: BrainEngine, callerBudget: number): Promise<PageRankCut | undefined> {+ const ratio = await readPageRankBudgetRatio(engine);+ if (ratio === null) return undefined;+ return { ratio, caller_budget: callerBudget, tokens: Math.max(1, Math.floor(ratio * callerBudget)) };+}++/** min(mode cut, ratio x caller budget) folded into the resolved knobs' tokenBudget. */+export function applyPageRankCut(knobs: ResolvedSearchKnobs, cut: PageRankCut | undefined): { knobs: ResolvedSearchKnobs; meta?: PageRankCutMeta } {+ if (!cut) return { knobs };+ const modeCut = typeof knobs.tokenBudget === 'number' && knobs.tokenBudget > 0 ? knobs.tokenBudget : null;+ const applied = modeCut === null ? cut.tokens : Math.min(modeCut, cut.tokens);+ return {+ knobs: { ...knobs, tokenBudget: applied },+ meta: { ratio: cut.ratio, caller_budget: cut.caller_budget, mode_cut: modeCut, applied_cut: applied },+ };+}diff --git a/src/core/types.ts b/src/core/types.tsindex 2b746a2961..1e07ed41ea 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2185,6 +2185,8 @@ export interface HybridSearchMeta {* only when `search.reranker.gate` is not `off`.*/rerank_gate?: import('./search/hybrid/rerank-gate.ts').RerankGateMeta;+ /** W5: the page-unit ranking cut that replaced the mode's tokenBudget, with the hits before and after it. */+ page_rank_cut?: import('./search/page-rank-cut.ts').PageRankCutMeta;/*** v0.32.x (search-lite): token budget enforcement metadata. Omitted when* no budget was applied (backward-compatible with pre-search-litediff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 78c4c598bb..4f888c1205 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -730,6 +730,7 @@"keyword_candidates?: CjkKeywordMeta | undefined","metadata_boost_gate?: MetadataBoostGateDecision | undefined","mode?: \"conservative\" | \"balanced\" | \"tokenmax\" | undefined",+ "page_rank_cut?: PageRankCutMeta | undefined","relational_evidence_slot?: RelationalEvidenceSlotDecision | undefined","relational_plan?: RelationalPlanMeta | undefined","relational_rerank_pin?: RelationalRerankPinDecision | undefined",@@ -6953,6 +6954,7 @@"dateHeader?: true | undefined","explicitUnit: boolean","packing: \"off\" | \"cap_only\" | \"breadth_capped\" | \"depth_first\"",+ "rankCut?: PageRankCut | undefined","requestedUnit: \"auto\" | \"window\" | \"chunk\" | \"section\" | \"page\"","unit: \"auto\" | \"window\" | \"section\" | \"page\"","window: number"@@ -7326,6 +7328,7 @@"onRerankPool?: ((pool: readonly SearchResult[], preRerank: readonly SearchResult[]) => void) | undefined","onVectorPoolMeta?: ((m: VectorPoolMeta) => void) | undefined","orFallback?: boolean | undefined",+ "pageRankCut?: PageRankCut | undefined","queryEmbedFn?: ((text: string) => Float32Array | Promise<Float32Array>) | undefined","recency?: \"on\" | \"off\" | \"strong\" | undefined","recencyBoost?: 0 | 1 | 2 | undefined",@@ -8412,6 +8415,7 @@"keyword_candidates?: CjkKeywordMeta | undefined","metadata_boost_gate?: MetadataBoostGateDecision | undefined","mode?: \"conservative\" | \"balanced\" | \"tokenmax\" | undefined",+ "page_rank_cut?: PageRankCutMeta | undefined","relational_evidence_slot?: RelationalEvidenceSlotDecision | undefined","relational_plan?: RelationalPlanMeta | undefined","relational_rerank_pin?: RelationalRerankPinDecision | undefined",diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex e685d0aca8..745eec610f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -113,6 +113,7 @@ test/repair-failed-writes-drift-w411.test.tstest/repair-fences.test.tstest/repair-frontmatter.test.tstest/scripts/test-stress-postgres.test.ts+test/search/page-rank-cut.test.tstest/search/rerank-gate-hybrid.test.tstest/search/rerank-gate-skip.test.tstest/search/rerank-gate-telemetry.test.tsdiff --git a/test/search/page-rank-cut.test.ts b/test/search/page-rank-cut.test.tsnew file mode 100644index 0000000000..c0fb214eb5--- /dev/null+++ b/test/search/page-rank-cut.test.ts@@ -0,0 +1,181 @@+/**+ * W5 — `search.page_rank_budget_ratio`: with `return_unit: "page"` and a+ * caller budget, ranking cuts its hits to min(mode cut, ratio x budget)+ * instead of the mode's `search.tokenBudget` alone.+ *+ * Protects: the key unset (or invalid) leaves query/search/recall exactly as+ * before; on, the cut is ratio x caller budget under tokenmax (no mode cut)+ * and the smaller of the two under conservative; a page call without a+ * budget and a chunk-unit call never engage it; `page_rank_cut` reports+ * ratio, caller budget, mode cut, applied cut, candidates and kept.+ * Forced probe: with the key off, two caller budgets give the same ranking+ * cut (the old path ignored the caller); on, the cut follows the budget.+ * Seams: query/search run keyword-only (embeddings off), so no model call;+ * recall's hybrid page arm runs on a fixture embed transport (the keyword-only+ * recall arm is a direct keyword read with no ranking cut to replace).+ * PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../../src/core/operations.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { applyPageRankCut, PAGE_RANK_BUDGET_RATIO_KEY, resolvePageRankCut } from '../../src/core/search/page-rank-cut.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';+import { resolveSearchMode } from '../../src/core/search/mode.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const op = (name: string) => operations.find(o => o.name === name)!;+const QUERY = 'garden tomato harvest';++describe('page rank cut: min() with the mode cut', () => {+ test('applyPageRankCut takes the smaller cut and reports both', () => {+ const conservative = resolveSearchMode({ mode: 'conservative' });+ const tokenmax = resolveSearchMode({ mode: 'tokenmax' });+ expect(conservative.tokenBudget).toBe(4000);+ expect(tokenmax.tokenBudget).toBeUndefined();+ expect(applyPageRankCut(conservative, undefined)).toEqual({ knobs: conservative });+ const cut = { ratio: 0.5, caller_budget: 8100, tokens: 4050 };+ expect(applyPageRankCut(tokenmax, cut).knobs.tokenBudget).toBe(4050);+ expect(applyPageRankCut(tokenmax, cut).meta).toEqual({ ratio: 0.5, caller_budget: 8100, mode_cut: null, applied_cut: 4050 });+ expect(applyPageRankCut(conservative, cut).meta).toEqual({ ratio: 0.5, caller_budget: 8100, mode_cut: 4000, applied_cut: 4000 });+ expect(applyPageRankCut(conservative, { ratio: 0.5, caller_budget: 2000, tokens: 1000 }).knobs.tokenBudget).toBe(1000);+ });++});++for (const backend of testBackends()) {+ describe(`${backend}: page rank cut through query, search and recall`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void> = async () => {};+ let meta: Record<string, any> | null = null;+ let embeddingDisabled = true;+ const ctx = () => ({ engine, config: { engine: backend, embedding_disabled: embeddingDisabled }, remote: false, sourceId: 'default', dryRun: false,+ logger: { info() {}, warn() {}, error() {} },+ emitResponseMeta: (k: string, v: unknown) => { if (k === 'retrieval') meta = v as Record<string, any>; } }) as unknown as OperationContext;+ const call = async (name: string, params: Record<string, unknown>) => {+ meta = null;+ const out = await op(name).handler(ctx(), { expand: false, ...params });+ return { out: out as any, meta: meta as Record<string, any> | null };+ };+ const slugs = (rows: Array<{ slug: string }>) => rows.map(r => r.slug);+ const ratio = async (value: string | null) => {+ if (value === null) await engine.unsetConfig(PAGE_RANK_BUDGET_RATIO_KEY);+ else await engine.setConfig(PAGE_RANK_BUDGET_RATIO_KEY, value);+ };++ beforeAll(async () => {+ if (backend === 'pglite') {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ } else {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ }+ for (let i = 0; i < 40; i++) {+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug: `notes/garden-${i}`,+ content: `---\ntype: note\ntitle: Garden note ${i}\n---\nThe garden tomato harvest note ${i}. ` + 'We planted tomatoes and basil in the garden beds this season. '.repeat(20) } });+ }+ }, 180_000);++ afterAll(async () => {+ resetGateway();+ await disposePersistenceConsumer(engine);+ await close();+ });++ test('an unset, non-numeric, zero or negative ratio is off', async () => {+ await ratio(null);+ expect(await resolvePageRankCut(engine, 8100)).toBeUndefined();+ for (const bad of ['', 'half', '0', '-0.5', 'Infinity']) {+ await ratio(bad);+ expect(await resolvePageRankCut(engine, 8100)).toBeUndefined();+ }+ await ratio('0.5');+ expect(await resolvePageRankCut(engine, 8100)).toEqual({ ratio: 0.5, caller_budget: 8100, tokens: 4050 });+ });++ test('off: the key unset or invalid changes nothing, and the caller budget never reaches ranking (forced probe)', async () => {+ await ratio(null);+ const base = await call('query', { query: QUERY, return_unit: 'page', token_budget: 8100, mode: 'conservative' });+ expect(base.meta!.page_rank_cut).toBeUndefined();+ expect(base.meta!.token_budget.budget).toBe(4000);+ const small = await call('query', { query: QUERY, return_unit: 'page', token_budget: 2000, mode: 'conservative' });+ expect(small.meta!.token_budget.budget).toBe(4000);+ const tm = await call('query', { query: QUERY, return_unit: 'page', token_budget: 8100, mode: 'tokenmax' });+ expect(tm.meta!.token_budget).toBeUndefined();+ expect(tm.meta!.page_rank_cut).toBeUndefined();+ await ratio('not-a-number');+ const invalid = await call('query', { query: QUERY, return_unit: 'page', token_budget: 8100, mode: 'conservative' });+ expect(slugs(invalid.out)).toEqual(slugs(base.out));+ expect(invalid.meta!.page_rank_cut).toBeUndefined();+ expect(invalid.meta!.token_budget).toEqual(base.meta!.token_budget);+ });++ test('on: tokenmax cuts to ratio x caller budget and reports candidates and kept', async () => {+ await ratio(null);+ const off = await call('query', { query: QUERY, return_unit: 'page', token_budget: 8100, mode: 'tokenmax' });+ await ratio('0.5');+ const on = await call('query', { query: QUERY, return_unit: 'page', token_budget: 8100, mode: 'tokenmax' });+ const cut = on.meta!.page_rank_cut;+ expect(cut).toMatchObject({ ratio: 0.5, caller_budget: 8100, mode_cut: null, applied_cut: 4050 });+ expect(on.meta!.token_budget.budget).toBe(4050);+ expect(cut.kept).toBe(on.meta!.token_budget.kept);+ expect(cut.candidates).toBeGreaterThan(cut.kept);+ expect(on.out.length).toBeLessThan(off.out.length);+ expect(slugs(on.out)).toEqual(slugs(off.out).slice(0, on.out.length));+ });++ test('on: conservative keeps the smaller of its own cut and ratio x budget', async () => {+ await ratio('0.5');+ const big = await call('query', { query: QUERY, return_unit: 'page', token_budget: 8100, mode: 'conservative' });+ expect(big.meta!.page_rank_cut).toMatchObject({ mode_cut: 4000, applied_cut: 4000 });+ const small = await call('query', { query: QUERY, return_unit: 'page', token_budget: 2000, mode: 'conservative' });+ expect(small.meta!.page_rank_cut).toMatchObject({ caller_budget: 2000, mode_cut: 4000, applied_cut: 1000 });+ expect(small.meta!.token_budget.budget).toBe(1000);+ });++ test('on: no caller budget, or the chunk unit, is unchanged', async () => {+ await ratio(null);+ const pageOff = await call('query', { query: QUERY, return_unit: 'page', mode: 'conservative' });+ const chunkOff = await call('query', { query: QUERY, token_budget: 3000, mode: 'conservative' });+ await ratio('0.5');+ const pageOn = await call('query', { query: QUERY, return_unit: 'page', mode: 'conservative' });+ const chunkOn = await call('query', { query: QUERY, token_budget: 3000, mode: 'conservative' });+ expect(pageOn.meta!.page_rank_cut).toBeUndefined();+ expect(chunkOn.meta!.page_rank_cut).toBeUndefined();+ expect(slugs(pageOn.out)).toEqual(slugs(pageOff.out));+ expect(slugs(chunkOn.out)).toEqual(slugs(chunkOff.out));+ expect(chunkOn.meta!.token_budget).toEqual(chunkOff.meta!.token_budget);+ });++ test('on: search and recall page paths take the same cut', async () => {+ await ratio('0.5');+ const s = await call('search', { query: QUERY, return_unit: 'page', token_budget: 2000, mode: 'conservative' });+ expect(s.meta!.page_rank_cut).toMatchObject({ caller_budget: 2000, mode_cut: 4000, applied_cut: 1000 });+ embeddingDisabled = false;+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { OPENAI_API_KEY: 'fixture-key' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) =>+ ({ embeddings: values.map(() => [1, ...Array(LEGACY_EMBEDDING_CONFIG.embedding_dimensions - 1).fill(0)]) })) as never);+ try {+ const r = await call('recall', { query: QUERY, return_unit: 'page', budget_tokens: 2000 });+ expect(r.out.search_degraded).toBeUndefined();+ expect(r.out.page_rank_cut).toMatchObject({ ratio: 0.5, caller_budget: 2000, applied_cut: 1000 });+ await ratio(null);+ const rOff = await call('recall', { query: QUERY, return_unit: 'page', budget_tokens: 2000 });+ expect(rOff.out.page_rank_cut).toBeUndefined();+ } finally {+ embeddingDisabled = true;+ __setEmbedTransportForTests(null);+ resetGateway();+ }+ });+ });+}