Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): W5 adaptive — search.page_rank_cut: whole_pages stops adding pages once their whole delivered pages fill the caller's budget

garrytan71b6d85bce8b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc7a0c6556..a6a03ef5fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ identifiers and attribution are available in the pre-removal Git revision
### 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. A grade is strong when the top result is a vector match with cosine at least `search.evidence_cosine_floor` and `search.reranker.gate_min_gap` ahead of every other page. There is no skip mode: on the dev sets no question reached the 0.8 floor with voyage-4 embeddings, and the reranker changed about half the delivered tokens, so skipping it is not shipped. The cache key now includes the gate keys and `search.evidence_cosine_floor`.
-- `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.
+- `search.page_rank_cut: whole_pages` (off by default) lets a `return_unit: "page"` call's own budget decide how many pages delivery gets. Today ranking cuts hits by chunk tokens to the mode's `search.tokenBudget` whatever the caller asked for: under tokenmax delivery is handed far more pages than fit and returns them as slivers, and under a mode cut small pages under-fill the budget. With `whole_pages`, `search`, `query` and `recall` lift the mode cut, and delivery keeps ranked pages while their whole delivered size fits the budget (times `search.page_rank_cut_factor`, default 1.0), reporting `delivery.page_rank_cut`. Calls without a budget and other units are unchanged.
- `recall` with `return_unit` and `budget_tokens` fills its budget. Delivery used to be sized to the whole budget, and the facts-first packer then dropped whole delivered blocks. It also re-costed those blocks with a chars/4 estimate while delivery had counted cl100k tokens, so even a call with no facts came back about 7% short. Delivery now gets what the facts leave (except under `query_first`), and delivered blocks cost what delivery counted.
## [0.60.169.0] - 2026-10-11
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 5828f78265..eb51bbcf29 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -6,7 +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`. Pinned by `test/search/rerank-gate-grade.test.ts`, `test/search/rerank-gate-hybrid.test.ts` (both engines), `test/search/rerank-gate-knobs.test.ts`, `test/search/rerank-gate-telemetry.test.ts` (both engines).
- `src/core/search/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/page-rank-cut.ts` — W5 page-unit ranking cut (default off): with `return_unit: page`, a caller budget and `search.page_rank_cut: whole_pages`, `resolveEvidencePlan` stores `rankCut` (`{mode, factor, caller_budget}`, factor from `search.page_rank_cut_factor`, default 1.0) on the plan; `search`/`query`/`recall` pass it as `HybridSearchOpts.pageRankCut`, and `liftModeCut` drops the mode's chunk-token `tokenBudget` in both the inner request and the cache resolver (`tb=` is in the knobs hash). Delivery applies the cut: `cutWholePages` (this file, pure) keeps rank-order pages while their whole delivered cost (evidence-delivery.ts `wholeCost`: floor plus every enrichment piece within the block char cap) fits `factor × the shared budget`, keeps the crossing page only when its floor fits what is left, and drops the rest as `rank_cut`. `delivery.page_rank_cut` reports mode, factor, caller budget, target, applied cost, 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.md
index dbbc71e62c..d894e976ad 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -108,18 +108,23 @@ Per-call params on `search`, `query`, `recall`:
and each delivered block costs what delivery counted (text and title, in
`delivery.tokenizer`), so the facts and blocks together fill
`budget_tokens` and no delivered block is dropped afterwards.
-- 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.
+- Page-unit ranking cut (off by default): ranking cuts its hits by chunk
+ tokens against the search mode's `search.tokenBudget` (4,000 under
+ conservative, none under tokenmax), whatever the caller's budget, so under
+ tokenmax delivery is handed more pages than it can deliver whole (slivers)
+ and under a mode cut small pages under-fill the budget. With
+ `gbrain config set search.page_rank_cut whole_pages`, a `return_unit:
+ "page"` call that passes its own budget on `search`, `query` or `recall`
+ lifts the mode cut and delivery walks the ranked pages, costing each at what
+ it would deliver whole (text, title and date header in
+ `delivery.tokenizer`, within the block char cap). It stops once they fill
+ `search.page_rank_cut_factor` (default 1.0) × the budget the pages share;
+ the page that crosses it stays only if its matching span still fits what
+ the whole pages before it leave. Later pages are dropped as `rank_cut`.
+ `delivery.page_rank_cut` reports `mode`, `factor`, `caller_budget`,
+ `target`, `applied_cost` (the kept pages' whole cost), `candidates` and
+ `kept`. A page call without a budget and every other unit are unchanged.
+ `gbrain config unset search.page_rank_cut` turns it off.
Think reads `think.return_unit` (default `auto`) and never
`search.return_unit`, so changing search's default does not change `think`.
@@ -160,7 +165,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`,
-`search.page_rank_budget_ratio`, `think.return_unit`. Kill switch:
+`search.page_rank_cut`, `search.page_rank_cut_factor`, `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.tsv
index 59893d7bf5..efbaf8d77d 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 baselin
src/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 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/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 (logic in search/page-rank-cut.ts; delivery reports it)
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.tsv
index 9aca456275..abc8555930 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -23,7 +23,7 @@ src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown
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 W13
src/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 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/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/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.0
src/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 refresh
src/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 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/config.ts 1953 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (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 option
src/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 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)
+src/core/search/evidence-delivery.ts 1537 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives 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.ts
index 2c6eed60c5..6b1afad0bf 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1413,7 +1413,8 @@ 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)
+ 'search.page_rank_cut', // W5: off | whole_pages — page unit + caller token_budget stops adding pages once their whole pages fill the budget (default off; search/page-rank-cut.ts)
+ 'search.page_rank_cut_factor', // W5: whole_pages target = factor x the budget (default 1.0)
'think.return_unit',
// Models tier system (v0.31.12)
'models.default',
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 2d51e09314..33a32b520a 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -38,7 +38,6 @@ 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';
@@ -498,10 +497,8 @@ 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; } } : {};
+ const rankCutOpts: Pick<HybridSearchOpts, 'pageRankCut'> = evidencePlan?.rankCut ? { pageRankCut: evidencePlan.rankCut } : {};
if (queryText) {
// #3242 parity (#4707): the page-search arm widens an unqualified
// no-grant caller across the transport-computed federated set, exactly
@@ -633,7 +630,6 @@ const recall: Operation = {
: {}),
...(budgetPacking ? { budget_packing: budgetPacking } : {}),
...(delivery ? { delivery } : {}),
- ...(pageRankCut ? { page_rank_cut: pageRankCut } : {}),
};
},
};
@@ -1342,7 +1338,7 @@ 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'> = {},
+ rankCutOpts: Pick<HybridSearchOpts, 'pageRankCut'> = {},
): Promise<SearchResult[]> {
if (await keylessChainQuestion(ctx, queryText)) {
return hybridSearchCached(ctx.engine, queryText, {
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index d1194c72e4..dc9cebe164 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -474,7 +474,6 @@ 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,
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index a0049cdc28..a412ace5d6 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -36,7 +36,7 @@ import { loadFenceChunkOverlay, markFenceChunk, splitFenceOverlay, type FenceChu
import { 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';
+import { cutWholePages, resolvePageRankCut, type PageRankCut, type PageRankCutMeta } 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';
@@ -113,6 +113,8 @@ export interface DeliveryMeta {
date_header?: true;
/** Present only when an explicit budget engaged the cap: the packing that ran. */
auto_packing?: AutoPacking;
+ /** W5: present when `search.page_rank_cut` cut the page candidates (page-rank-cut.ts). */
+ page_rank_cut?: PageRankCutMeta;
}
export type DeliveredSearchResult = SearchResult & { delivered: DeliveredEvidence };
@@ -131,7 +133,7 @@ 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). */
+ /** W5: page unit + caller budget + `search.page_rank_cut: whole_pages` (page-rank-cut.ts). */
rankCut?: PageRankCut;
}
@@ -799,6 +801,15 @@ function floorOf(b: Block, tokenizer: 'cl100k' | 'heuristic'): { tokens: number;
* Reserve each block's floor in rank order, then enrich. `spill` (auto) takes
* a block whose floor does not fit instead of dropping or cutting it.
*/
+/** What delivery emits for `b` with an unlimited budget: its floor, then every enrichment piece the block char cap allows. */
+function wholeCost(b: Block, tokenizer: 'cl100k' | 'heuristic', omitTok: number): number {
+ const selected = b.selected;
+ b.selected = new Set(b.anchors[0]?.pieces ?? []);
+ const cost = floorOf(b, tokenizer).tokens + Number.MAX_SAFE_INTEGER - enrichBlock(b, Number.MAX_SAFE_INTEGER, tokenizer, omitTok);
+ b.selected = selected;
+ return cost;
+}
+
function allocate(blocks: Block[], budget: number, tokenizer: 'cl100k' | 'heuristic', dropped: Record<string, number>, spill?: (b: Block) => void): Block[] {
const omitTok = pieceTokens(EVIDENCE_OMISSION, tokenizer);
let remaining = budget;
@@ -1120,6 +1131,7 @@ export async function deliverEvidence(
const capped = capEngaged(plan);
let kept: Block[];
+ let rankCutMeta: PageRankCutMeta | undefined;
let chunkItems: ChunkItem[] = [];
if (capped) {
({ kept, chunks: chunkItems } = allocateCapped(planned,
@@ -1128,7 +1140,14 @@ export async function deliverEvidence(
// Unchanged chunks are paid for first; conversations share the rest, and one
// whose matching span no longer fits keeps its ranked chunks instead.
const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(headerFor(p.hit) + (p.hit.chunk_text ?? ''), tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);
- kept = allocate(planned, Math.max(0, plan.budgetTokens - reserved), tokenizer, dropped, auto
+ const shared = Math.max(0, plan.budgetTokens - reserved);
+ let candidates = planned;
+ if (plan.rankCut) {
+ const omitTok = pieceTokens(EVIDENCE_OMISSION, tokenizer);
+ ({ kept: candidates, meta: rankCutMeta } = cutWholePages(planned, shared, plan.rankCut, b => wholeCost(b, tokenizer, omitTok), b => floorOf(b, tokenizer).tokens));
+ if (planned.length > candidates.length) dropped.rank_cut = planned.length - candidates.length;
+ }
+ kept = allocate(candidates, shared, tokenizer, dropped, auto
? b => { for (const h of b.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: 'conversation_over_budget' }); }
: undefined);
}
@@ -1184,6 +1203,7 @@ export async function deliverEvidence(
...(plan.budgetClamped ? { budget_clamped: plan.budgetClamped } : {}),
...(capped ? { auto_packing: plan.packing } : {}),
...(plan.dateHeader ? { date_header: true as const } : {}),
+ ...(rankCutMeta ? { page_rank_cut: rankCutMeta } : {}),
};
return { results: capped ? capEvidenceToBudget(results, delivery) : results, delivery };
}
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 780c36dc25..af2ee4145c 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -910,7 +910,7 @@ 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. */
+ /** W5: page-unit ranking cut (page-rank-cut.ts): lifts the mode's tokenBudget in the inner search and the cache resolver; delivery cuts by whole pages. */
pageRankCut?: import('./page-rank-cut.ts').PageRankCut;
/**
* explain_target (explain-target.ts): when set, each pipeline stage records
diff --git a/src/core/search/hybrid/cache-stages.ts b/src/core/search/hybrid/cache-stages.ts
index f57d709f81..bfc957e50f 100644
--- a/src/core/search/hybrid/cache-stages.ts
+++ b/src/core/search/hybrid/cache-stages.ts
@@ -20,7 +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 { liftModeCut } from '../page-rank-cut.ts';
import { normalizeRelationalRerankPin } from '../relational-rerank-pin.ts';
import { recordSearchTelemetry } from '../telemetry.ts';
import { resolveEffectiveRecency, resolveEffectiveSalience } from './effective-modes.ts';
@@ -44,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 { knobs: resolvedForCache } = applyPageRankCut(resolveSearchMode({
+ const resolvedForCache = liftModeCut(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.
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index 3e717a09ba..8504cc96e6 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -29,7 +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';
+import { liftModeCut } from '../page-rank-cut.ts';
/**
* Everything the stages read, resolved once at hybridSearch entry, plus the
@@ -73,8 +73,6 @@ 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';
@@ -96,7 +94,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 { knobs: resolvedMode, meta: pageRankCut } = applyPageRankCut(resolveSearchMode({
+ const resolvedMode = liftModeCut(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
@@ -313,7 +311,6 @@ export async function resolveHybridRequest(
lastRank1Score: undefined,
};
if (decide) req.decide = decide;
- if (pageRankCut) req.pageRankCut = pageRankCut;
return req;
}
@@ -348,10 +345,7 @@ export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult
// never waits.
export function emitHybridMeta(req: HybridRequest, armMeta: HybridSearchMeta): void {
const { engine, opts } = req;
- 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 rawMeta = req.keywordCandidates ? { ...armMeta, keyword_candidates: req.keywordCandidates } : armMeta;
const decide = decideMetaFor(req.decide);
const answerability = req.decide?.answerability;
const meta: HybridSearchMeta = decide || req.rerankMeta || answerability || req.relationalPlan
diff --git a/src/core/search/page-rank-cut.ts b/src/core/search/page-rank-cut.ts
index 005c697bd5..4ee289e480 100644
--- a/src/core/search/page-rank-cut.ts
+++ b/src/core/search/page-rank-cut.ts
@@ -1,62 +1,84 @@
/**
- * W5 (memory proof wave 2): page-unit ranking cut from the caller's budget.
+ * W5 (memory proof wave 2): the 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.
+ * pages into that budget, but ranking cut its hits by chunk tokens against 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; under a mode cut, small pages under-filled the
+ * budget. `search.page_rank_cut: whole_pages` (default off) instead stops
+ * adding page candidates once their whole delivered pages fill
+ * `factor x caller budget` (`search.page_rank_cut_factor`, default 1.0).
+ *
+ * Ranking lifts the mode's chunk-token cut for such a call (`liftModeCut`), so
+ * a mode cut can never under-fill the budget, and delivery applies the cut
+ * with its own page sizes (`cutWholePages` below, priced by evidence-delivery.ts `wholeCost`). 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';
+export const PAGE_RANK_CUT_KEY = 'search.page_rank_cut';
+export const PAGE_RANK_CUT_FACTOR_KEY = 'search.page_rank_cut_factor';
+export const DEFAULT_PAGE_RANK_CUT_FACTOR = 1;
-/** The cut a page-unit plan asks ranking to apply (resolved once per call). */
+/** The cut a page-unit plan asks for (resolved once per call). */
export interface PageRankCut {
- ratio: number;
+ mode: 'whole_pages';
+ factor: 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;
+/** `delivery.page_rank_cut`: the target, the whole-page cost kept, and the page candidates before and after the cut. */
+export interface PageRankCutMeta extends PageRankCut {
+ /** floor(factor x the budget the pages share: the caller budget less saved-fact rows). */
+ target: number;
+ /** Whole delivered cost (text, title, date header) of the kept pages. */
+ applied_cost: 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> {
+async function readConfig(engine: BrainEngine, key: string): Promise<string | 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;
+ return await engine.getConfig(key);
} catch {
return null;
}
}
+/** Undefined unless `search.page_rank_cut` is `whole_pages`; a factor that is not a positive finite number reads as 1.0. */
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)) };
+ if ((await readConfig(engine, PAGE_RANK_CUT_KEY))?.trim().toLowerCase() !== 'whole_pages') return undefined;
+ const raw = await readConfig(engine, PAGE_RANK_CUT_FACTOR_KEY);
+ const n = raw == null || raw === '' ? NaN : Number(raw);
+ return { mode: 'whole_pages', factor: Number.isFinite(n) && n > 0 ? n : DEFAULT_PAGE_RANK_CUT_FACTOR, caller_budget: callerBudget };
+}
+
+/** With a cut, ranking returns its full `limit`: delivery's whole-page cut replaces the mode's chunk-token cut. */
+export function liftModeCut(knobs: ResolvedSearchKnobs, cut: PageRankCut | undefined): ResolvedSearchKnobs {
+ return cut && knobs.tokenBudget !== undefined ? { ...knobs, tokenBudget: undefined } : knobs;
}
-/** 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 },
- };
+/**
+ * `whole_pages`: keep rank-order pages while their whole delivered cost fits
+ * `factor x budget`. The page that crosses it stays only when its floor (what
+ * allocation reserves first) still fits what the whole pages before it leave
+ * of the budget, so delivery would deliver part of it; rank one always stays.
+ */
+export function cutWholePages<T>(pages: T[], budget: number, cut: PageRankCut, whole: (p: T) => number, floor: (p: T) => number): { kept: T[]; meta: PageRankCutMeta } {
+ const target = Math.max(1, Math.floor(cut.factor * budget));
+ const kept: T[] = [];
+ let cost = 0;
+ for (const p of pages) {
+ if (cost >= target) break;
+ const w = whole(p);
+ const fits = cost + w <= target;
+ if (fits || kept.length === 0 || floor(p) <= budget - cost) {
+ kept.push(p);
+ cost += w;
+ }
+ if (!fits) break;
+ }
+ return { kept, meta: { ...cut, target, applied_cost: cost, candidates: pages.length, kept: kept.length } };
}
diff --git a/src/core/types.ts b/src/core/types.ts
index 1e07ed41ea..2b746a2961 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -2185,8 +2185,6 @@ 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-lite
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index 355b741fa0..640f86e53e 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -14,7 +14,7 @@ import { describe, expect, test } from 'bun:test';
import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
import { KNOB_CONFIG_KEY, SEARCH_MODE_CONFIG_KEYS, SEARCH_MODE_KEY } from '../src/core/search/mode.ts';
import { REMOTE_PRIVATE_PAGES_KEY } from '../src/core/search/private-visibility.ts';
-import { PAGE_RANK_BUDGET_RATIO_KEY } from '../src/core/search/page-rank-cut.ts';
+import { PAGE_RANK_CUT_FACTOR_KEY, PAGE_RANK_CUT_KEY } from '../src/core/search/page-rank-cut.ts';
/** search.* keys read directly via engine.getConfig (not mode-bundle knobs). */
const DIRECTLY_READ_SINGLETONS = [
@@ -48,7 +48,8 @@ const DIRECTLY_READ_SINGLETONS = [
'search.entity_anchoring', // search/entity-anchor.ts (ops/search.ts)
'search.query_facts_arm', // search/facts-arm.ts (search/query-arms.ts)
'search.temporal_fact_reserve', // search/facts-arm.ts (search/query-arms.ts)
- PAGE_RANK_BUDGET_RATIO_KEY, // search/page-rank-cut.ts via evidence-delivery.ts (W5)
+ PAGE_RANK_CUT_KEY, // search/page-rank-cut.ts via evidence-delivery.ts (W5)
+ PAGE_RANK_CUT_FACTOR_KEY,
];
describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 4f888c1205..24b2341056 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -730,7 +730,6 @@
"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",
@@ -6890,6 +6889,7 @@
"dropped: number",
"dropped_reasons: Record<string, number>",
"fallbacks: string[]",
+ "page_rank_cut?: PageRankCutMeta | undefined",
"requested_unit: \"auto\" | \"window\" | \"chunk\" | \"section\" | \"page\"",
"return_window: number",
"tokenizer: \"cl100k\" | \"heuristic\"",
@@ -8415,7 +8415,6 @@
"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/search/page-rank-cut.test.ts b/test/search/page-rank-cut.test.ts
index c0fb214eb5..dd54f1cd38 100644
--- a/test/search/page-rank-cut.test.ts
+++ b/test/search/page-rank-cut.test.ts
@@ -1,18 +1,20 @@
/**
- * 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.
+ * W5 — `search.page_rank_cut: whole_pages`: with `return_unit: "page"` and a
+ * caller budget, delivery stops adding page candidates once their whole
+ * delivered pages fill `factor x budget`, and ranking lifts the mode's
+ * chunk-token cut so it cannot stop earlier.
*
- * 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.
+ * Protects: off (unset, `off`, anything else) leaves query/search/recall
+ * exactly as before; on, small pages fill at least 95% of the budget (even
+ * under conservative's 4000-token mode cut) and large pages are delivered
+ * whole, a few of them, like the old 0.40 ratio; a page call without a budget
+ * and a chunk-unit call never engage it; `delivery.page_rank_cut` reports
+ * mode, factor, caller budget, target, applied cost, candidates and kept.
+ * Forced probe: the fixed-ratio path (a 0.40 x budget chunk-token cut, which
+ * is what `search.page_rank_budget_ratio` folded into `search.tokenBudget`)
+ * under-fills the small-page fixture.
* 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).
+ * recall's hybrid page arm runs on a fixture embed transport.
* PGLite always, Postgres when DATABASE_URL is set.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
@@ -21,7 +23,7 @@ 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 { cutWholePages, liftModeCut, PAGE_RANK_CUT_FACTOR_KEY, PAGE_RANK_CUT_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';
@@ -29,26 +31,33 @@ 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';
+const SMALL = 'orchard apple picking';
+const LARGE = 'garden tomato harvest';
+const BUDGET = 8000;
-describe('page rank cut: min() with the mode cut', () => {
- test('applyPageRankCut takes the smaller cut and reports both', () => {
+describe('page rank cut: the mode cut is lifted only for a cut', () => {
+ test('liftModeCut', () => {
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);
+ expect(liftModeCut(conservative, undefined)).toBe(conservative);
+ expect(liftModeCut(conservative, { mode: 'whole_pages', factor: 1, caller_budget: BUDGET }).tokenBudget).toBeUndefined();
});
+ test('cutWholePages: whole pages up to the target; the crossing page only if its floor fits what is left', () => {
+ const cut = { mode: 'whole_pages' as const, factor: 1, caller_budget: 1000 };
+ const pages = (...ws: Array<[number, number]>) => ws.map(([w, f], i) => ({ i, w, f }));
+ const run = (ps: Array<{ i: number; w: number; f: number }>, budget = 1000, c = cut) =>
+ cutWholePages(ps, budget, c, p => p.w, p => p.f);
+ expect(run(pages([400, 50], [400, 50], [400, 150], [100, 10])).kept.map(p => p.i)).toEqual([0, 1, 2]);
+ expect(run(pages([400, 50], [400, 50], [400, 250], [100, 10])).kept.map(p => p.i)).toEqual([0, 1]);
+ expect(run(pages([500, 50], [500, 50], [100, 10])).meta).toEqual({ ...cut, target: 1000, applied_cost: 1000, candidates: 3, kept: 2 });
+ expect(run(pages([3000, 400], [100, 10])).kept.map(p => p.i)).toEqual([0]);
+ expect(run(pages([400, 50], [400, 50], [400, 250]), 1000, { ...cut, factor: 1.5 }).meta).toMatchObject({ target: 1500, applied_cost: 1200, kept: 3 });
+ });
});
for (const backend of testBackends()) {
- describe(`${backend}: page rank cut through query, search and recall`, () => {
+ describe(`${backend}: whole-page cut through query, search and recall`, () => {
let engine: BrainEngine;
let close: () => Promise<void> = async () => {};
let meta: Record<string, any> | null = null;
@@ -61,11 +70,14 @@ for (const backend of testBackends()) {
const out = await op(name).handler(ctx(), { expand: false, ...params });
return { out: out as any, meta: meta as Record<string, any> | null };
};
+ const page = (query: string, extra: Record<string, unknown> = {}) =>
+ call('query', { query, return_unit: 'page', token_budget: BUDGET, limit: 50, mode: 'tokenmax', ...extra });
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);
+ const set = async (key: string, value: string | null) => {
+ if (value === null) await engine.unsetConfig(key);
+ else await engine.setConfig(key, value);
};
+ const cutMode = (value: string | null) => set(PAGE_RANK_CUT_KEY, value);
beforeAll(async () => {
if (backend === 'pglite') {
@@ -79,11 +91,18 @@ for (const backend of testBackends()) {
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) } });
+ // Small pages (BEAM-like): about 250 tokens, one chunk each.
+ for (let i = 0; i < 48; i++) {
+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug: `notes/orchard-${i}`,
+ content: `---\ntype: note\ntitle: Orchard note ${i}\n---\nThe orchard apple picking note ${i}. ` + 'We walked the rows and filled crates with ripe fruit before noon. '.repeat(14) } });
+ }
+ // Large pages (sessions): about 3,000 tokens, many chunks each.
+ for (let i = 0; i < 12; i++) {
+ const paras = Array.from({ length: 12 }, (_, k) => `Day ${k} of session ${i}: the garden tomato harvest went on. ` + 'We picked, sorted and stored the vines while talking through the plan. '.repeat(16));
+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug: `sessions/garden-${i}`,
+ content: `---\ntype: note\ntitle: Garden session ${i}\n---\n` + paras.join('\n\n') } });
}
- }, 180_000);
+ }, 300_000);
afterAll(async () => {
resetGateway();
@@ -91,86 +110,123 @@ for (const backend of testBackends()) {
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();
+ test('only whole_pages is on; a factor that is not a positive number reads as 1.0', async () => {
+ for (const v of [null, '', 'off', 'whole-page', 'true']) {
+ await cutMode(v);
+ expect(await resolvePageRankCut(engine, BUDGET)).toBeUndefined();
+ }
+ await cutMode('whole_pages');
+ for (const bad of [null, '', 'big', '0', '-1', 'Infinity']) {
+ await set(PAGE_RANK_CUT_FACTOR_KEY, bad);
+ expect(await resolvePageRankCut(engine, BUDGET)).toEqual({ mode: 'whole_pages', factor: 1, caller_budget: BUDGET });
}
- await ratio('0.5');
- expect(await resolvePageRankCut(engine, 8100)).toEqual({ ratio: 0.5, caller_budget: 8100, tokens: 4050 });
+ await set(PAGE_RANK_CUT_FACTOR_KEY, '1.25');
+ expect(await resolvePageRankCut(engine, BUDGET)).toEqual({ mode: 'whole_pages', factor: 1.25, caller_budget: BUDGET });
+ await set(PAGE_RANK_CUT_FACTOR_KEY, null);
});
- 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('off: unset, `off` or an unknown value leaves rows and delivery identical', async () => {
+ await cutMode(null);
+ const base = await page(SMALL);
+ expect(base.meta!.delivery.page_rank_cut).toBeUndefined();
+ for (const v of ['off', 'nonsense']) {
+ await cutMode(v);
+ const again = await page(SMALL);
+ expect(slugs(again.out)).toEqual(slugs(base.out));
+ expect(again.meta!.delivery).toEqual(base.meta!.delivery);
+ expect(again.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);
+ test('small pages fill at least 95% of the budget; the fixed 0.40 ratio under-fills (forced probe)', async () => {
+ await cutMode(null);
+ // The old ratio folded min(mode cut, 0.40 x budget) into search.tokenBudget, a chunk-token cut.
+ await set('search.tokenBudget', String(0.4 * BUDGET));
+ const ratio = await page(SMALL);
+ await set('search.tokenBudget', null);
+ expect(ratio.meta!.delivery.budget_used).toBeLessThan(0.6 * BUDGET);
+
+ await cutMode('whole_pages');
+ const on = await page(SMALL);
+ const cut = on.meta!.delivery.page_rank_cut;
+ expect(cut).toMatchObject({ mode: 'whole_pages', factor: 1, caller_budget: BUDGET, target: BUDGET });
+ expect(on.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.95 * BUDGET);
+ expect(on.meta!.delivery.budget_used).toBeLessThanOrEqual(BUDGET);
+ expect(cut.kept).toBe(on.meta!.delivery.blocks);
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));
+ expect(cut.applied_cost).toBeGreaterThanOrEqual(0.95 * BUDGET);
+ expect(on.out.every((r: any) => r.delivered.truncated === false)).toBe(true);
+ });
+
+ test('the mode cut never under-fills: conservative (4000) still fills small pages', async () => {
+ await cutMode(null);
+ const off = await page(SMALL, { mode: 'conservative' });
+ expect(off.meta!.token_budget.budget).toBe(4000);
+ expect(off.meta!.delivery.budget_used).toBeLessThan(0.6 * BUDGET);
+ await cutMode('whole_pages');
+ const on = await page(SMALL, { mode: 'conservative' });
+ expect(on.meta!.token_budget).toBeUndefined();
+ expect(on.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.95 * BUDGET);
+ });
+
+ test('large pages: the same whole pages the 0.40 ratio delivered, without its slivers', async () => {
+ await cutMode(null);
+ await set('search.tokenBudget', String(0.4 * BUDGET));
+ const ratio = await page(LARGE);
+ await set('search.tokenBudget', null);
+ await cutMode('whole_pages');
+ const on = await page(LARGE);
+ const cut = on.meta!.delivery.page_rank_cut;
+ expect(cut.kept).toBeLessThanOrEqual(4);
+ const whole = (rows: any[]) => rows.filter((r) => r.delivered.truncated === false).map((r) => r.slug);
+ expect(whole(on.out)).toEqual(whole(ratio.out));
+ expect(cut.kept).toBeLessThanOrEqual(ratio.meta!.delivery.blocks);
+ expect(on.out.slice(0, -1).every((r: any) => r.delivered.truncated === false)).toBe(true);
+ expect(on.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.9 * BUDGET);
+ expect(slugs(on.out)).toEqual(slugs(ratio.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('factor scales the target', async () => {
+ await cutMode('whole_pages');
+ await set(PAGE_RANK_CUT_FACTOR_KEY, '0.5');
+ const half = await page(SMALL);
+ await set(PAGE_RANK_CUT_FACTOR_KEY, null);
+ const full = await page(SMALL);
+ expect(half.meta!.delivery.page_rank_cut).toMatchObject({ factor: 0.5, target: BUDGET / 2 });
+ expect(half.meta!.delivery.page_rank_cut.kept).toBeLessThan(full.meta!.delivery.page_rank_cut.kept);
});
- 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();
+ test('no caller budget, or the chunk unit, is unchanged', async () => {
+ await cutMode(null);
+ const pageOff = await call('query', { query: SMALL, return_unit: 'page', limit: 50, mode: 'conservative' });
+ const chunkOff = await call('query', { query: SMALL, token_budget: 3000, limit: 50, mode: 'conservative' });
+ await cutMode('whole_pages');
+ const pageOn = await call('query', { query: SMALL, return_unit: 'page', limit: 50, mode: 'conservative' });
+ const chunkOn = await call('query', { query: SMALL, token_budget: 3000, limit: 50, mode: 'conservative' });
+ expect(pageOn.meta!.delivery.page_rank_cut).toBeUndefined();
expect(slugs(pageOn.out)).toEqual(slugs(pageOff.out));
+ expect(pageOn.meta!.token_budget).toEqual(pageOff.meta!.token_budget);
expect(slugs(chunkOn.out)).toEqual(slugs(chunkOff.out));
expect(chunkOn.meta!.token_budget).toEqual(chunkOff.meta!.token_budget);
+ expect(chunkOn.meta!.delivery?.page_rank_cut).toBeUndefined();
});
- 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 });
+ test('search and recall page paths take the same cut', async () => {
+ await cutMode('whole_pages');
+ const s = await call('search', { query: SMALL, return_unit: 'page', token_budget: BUDGET, limit: 50, mode: 'tokenmax' });
+ expect(s.meta!.delivery.page_rank_cut).toMatchObject({ mode: 'whole_pages', caller_budget: BUDGET });
+ expect(s.meta!.delivery.budget_used).toBeGreaterThanOrEqual(0.95 * BUDGET);
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 });
+ const r = await call('recall', { query: SMALL, return_unit: 'page', budget_tokens: 2000, limit: 50 });
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();
+ expect(r.out.delivery.page_rank_cut).toMatchObject({ mode: 'whole_pages', caller_budget: 2000 });
+ await cutMode(null);
+ const rOff = await call('recall', { query: SMALL, return_unit: 'page', budget_tokens: 2000, limit: 50 });
+ expect(rOff.out.delivery.page_rank_cut).toBeUndefined();
} finally {
embeddingDisabled = true;
__setEmbedTransportForTests(null);