Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): 8k conversion flags, all default off: query budget as the delivery cap, titled date headers, a dated facts block, fact source pages (GBRA-205)

garrytan6f82a94e00d2
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index a83e0932e5..583d443631 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -345,6 +345,12 @@ Two cross-cutting seams sit around the pipeline rather than inside it:
budget and 30% of the rows. They render with their date header, oldest first
after the pages, in place of the facts arm. No model call. Gates:
`docs/eval/decisions/temporal-fact-reserve/`.
+- **Facts block and fact source pages (default off, GBRA-205).** With
+ `search.query_facts_block=true`, every `query` with a token budget gets the
+ reserve's dated facts, up to 22% of the budget and 40 rows, oldest first
+ ahead of the pages. With `search.fact_source_pages=true`, the conversations
+ the best-matching facts came from join the hits after the top three rows.
+ Both wait on a held-out gate before any default change.
### Use-attributed feedback
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 4e74cd4de0..6c30fbb550 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -15,9 +15,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- Evidence date headers (`search/evidence-date.ts`) and the tail trim (`search/evidence-tail-trim.ts`): [Core Search (evidence blocks)](core-search-evidence.md).
- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it by a ranking link type 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/`.
-- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Temporal fact reserve: `applyTemporalFactReserve` behind `search.temporal_fact_reserve` (default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored and ordered by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`.
+- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. The temporal fact reserve, the facts block and fact source pages: [Core Search (evidence blocks)](core-search-evidence.md).
- `src/core/search/fact-relevance.ts` — question relevance for saved facts, shared by recall's `question` (`facts/question-recall.ts`), the temporal fact reserve and (pool only) the facts arm. `collectFactCandidates`: one bounded pool under recall's read policy (source scope, active and not superseded, audit rows excluded, quarantine and rederive hiding through `projectionEligibleSql`, the trust floor, remote world-only, `privateProvenanceFilterFragment` when `excludePrivate`) plus recall's filters inside every arm before its LIMIT (`(source_id, entity_slug)` pairs, `source_session`, event-time since, escaped `ILIKE` grep); arms, run concurrently and merged in a fixed order, are keyword FTS (`factsFtsDocument`, served by `idx_facts_fts`), cosine (cast to the facts column type, filtered on model only so the HNSW index serves it, a stale hash or other dimensions yielding no similarity; `ef_search` sized to the depth and pgvector's iterative scan when `hnswIterativeScan` is set) and the named entity page's facts in its own source; depths are bound parameters; `cosineForAll` scores every candidate's cosine whichever arm found it. A missing embedding column or other dimensions skips the cosine arm; any other DB error throws. `scoreFactCandidates`: cosine + whole-word term share + 0.1 when dated, the share's denominator growing past `TERM_STUFFING_RATIO` times the question's terms for a long fact; order score, newest valid_from, id. `admitted`: the `reserve` rule (cosine >= 0.5 or share >= 0.34) or the `facts_arm` rule (cosine >= 0.6, half the terms, or the named entity). `countUncomparableFacts` counts the pool's facts the cosine arm cannot compare, per source: candidates from `idx_facts_unembedded` and `idx_facts_embedding_model` first, the read policy on those rows only. The keyword arm and the count run under `customPlan` (`plan_cache_mode = force_custom_plan` in a transaction): a cached generic plan cannot see the source arrays and nests the policy anti-joins over every match. p95 at 100k facts: Postgres 51 ms local / 65 ms remote, PGLite 152 / 139 ms. Tests: `test/fact-relevance.test.ts`, `test/recall-question.test.ts`.
-- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, then the facts arm), each behind its own key (entity anchoring default off, the facts arm default on); a temporal-cue query with a token budget takes the temporal fact reserve instead of the facts arm when `search.temporal_fact_reserve` is on; with all off it returns the rows untouched.
+- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, fact source pages, then the facts arm), each behind its own key (the facts arm default on, the rest off); a query with a token budget takes the facts block (`search.query_facts_block`) or, with a temporal cue, the temporal fact reserve (`search.temporal_fact_reserve`) instead of the facts arm; with all off it returns the rows untouched.
- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.
- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns; a segmented page's row says `segmented` and carries no body) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction. Chunk rows carry `projected_byte_start/end` when recorded, and on a segmented page their `occurrence_id` (the span is relative to that occurrence's projection), the references `search/segmented-evidence.ts` reads windows around.
@@ -53,7 +53,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.
-- `src/core/search/evidence-packing.ts` — the explicit-budget packing surface of evidence delivery: `AUTO_PACKINGS` (`off`, `cap_only` default, `breadth_capped`, `depth_first`) for `search.auto_packing`, `MIN_EXPLICIT_AUTO_BUDGET` (32; an explicit `auto` budget below it, or non-finite, is refused with `invalid_params` naming it), `parseAutoPacking` (the library override, unknown values refused), `configPacking` (unknown stored values read as the default) and `autoPackingValueProblem` (the `config set` refusal wired through `search/config-values.ts`). Tests: `test/evidence-delivery.test.ts`.
+- `src/core/search/evidence-packing.ts` — the explicit-budget packing surface of evidence delivery: `AUTO_PACKINGS` (`off`, `cap_only` default, `breadth_capped`, `depth_first`) for `search.auto_packing`, `MIN_EXPLICIT_AUTO_BUDGET` (32; an explicit `auto` budget below it, or non-finite, is refused with `invalid_params` naming it), `parseAutoPacking` (the library override, unknown values refused), `configPacking` (unknown stored values read as the default) and `autoPackingValueProblem` (the `config set` refusal wired through `search/config-values.ts`); `queryBudgetUsesAuto` (`search.query_budget_unit`, GBRA-205: `auto` makes `query`'s `token_budget` the hard cap, default `chunk`). Tests: `test/evidence-delivery.test.ts`, `test/search-8k-conversion.test.ts`.
- `src/core/search/hnsw-iterative-scan.ts` — the pgvector `hnsw.iterative_scan` mode for filtered vector search (#6132 idea): `relaxed_order` by default, `strict_order` or `off` through `GBRAIN_HNSW_ITERATIVE_SCAN` (wins) or `search.hnsw_iterative_scan` (file > DB via loadConfigWithEngine). `resolveHnswIterativeScan(cfg)` latches once per process (hybrid `request.ts` passes it as `SearchOpts.hnswIterativeScan`; engines hand it to `withVectorSettings`), logging once when an override is active. `hnswIterativeScanValueProblem` backs the `config set` refusal through `search/config-values.ts` (`searchConfigValueRefusal`: enum/range rules for `search.*` keys, exit 2 `invalid_params`, nothing written). Pinned by `test/search/hnsw-iterative-scan.test.ts` and the Postgres recall fixture `test/e2e/hnsw-iterative-scan-recall-postgres.test.ts`; bench `scripts/bench/hnsw-iterative-scan.ts` (its `--corpus latent` mode, with `scripts/bench/hnsw-latent-corpus.ts` and the VM bootstrap `scripts/bench/hnsw-scale-vm-setup.sh`, is the E5.4 scale and index-build bench; results in `docs/eval/hnsw-scale-bench.md`).
- `src/core/search/internal-breadth.ts` — `INTERNAL_BREADTH_SEARCH_OPTS` (`autocut: false, adaptiveReturn: false`), the one option object internal callers spread into `hybridSearch` when they need the full ranked set rather than a reader-trimmed one (#5890): think gather (both legs), brainstorm close-set, grade-takes evidence, whoknows and enrich. Pinned by `test/internal-breadth-callers.serial.test.ts`; `eval-contradictions/runner.ts` still inherits both trims.
diff --git a/docs/architecture/key-files/core-search-evidence.md b/docs/architecture/key-files/core-search-evidence.md
index 63a810d935..fa56b8f3a0 100644
--- a/docs/architecture/key-files/core-search-evidence.md
+++ b/docs/architecture/key-files/core-search-evidence.md
@@ -3,5 +3,6 @@
[Subsystem index](../KEY_FILES.md) · [Core Search (2/2)](core-search-2.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `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/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) `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off) and `evidenceTitlesEnabled` (`search.evidence_titles`, GBRA-205, default off: with the header on, `blockDateHeaders` ends a page block's line with its title via `titledPageHeader`, fact headers unchanged; think's `<page>` tag gets a `title` attribute). Tests: `test/evidence-date-header.test.ts`, `test/search-8k-conversion.test.ts`.
- `src/core/search/evidence-tail-trim.ts` — the protected tail trim (`search.evidence_tail_trim`, default off, GBRA-156). `resolveEvidencePlan` sets `EvidencePlan.tailTrim` only for `unit: auto` with the key on; `deliverEvidence` calls `trimEvidenceTail(results, opts.query)` on the rank-order delivered rows after redaction and before the token totals, and only when `DeliverOptions.query` is set (`search`/`query` pass `p.query`; the library `assembleEvidenceForHits` passes `input.query` and frozen hits may carry `score`; the `assemble_evidence` op passes neither, so the trim never runs there). Rows past `TAIL_TRIM_PROTECTED` = 3 that are whole-conversation blocks (`delivered.reason` `conversation_type`/`conversation_slug`) and score under `TAIL_TRIM_SCORE_FRACTION` = 0.5 of rank one are dropped, unless their `chunk_text` holds at least `TAIL_TRIM_TERM_FRACTION` = 0.8 of rank one's share of the query's terms (`queryTerms`: letter/digit runs, stopwords and single characters dropped, cut to six characters). Rank one's score must be a positive finite number and every row's finite, or nothing changes. `delivery.tail_trim` is `{ dropped, kept_by_query_terms }`; `dropped_reasons.tail_trim` counts drops. Pinned by `test/evidence-tail-trim.test.ts` (the knowledge-update regression case).
+- `src/core/search/facts-arm.ts` (fact reserves) — `applyFactReserve` serves two policies. The temporal fact reserve (`applyTemporalFactReserve`, `search.temporal_fact_reserve`, default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`. The facts block (`applyFactsBlock`, `search.query_facts_block`, GBRA-205, default off): the same facts for every budgeted query, up to 22% of the budget and 40 rows, oldest first ahead of the pages, adding rows. Fact source pages (`applyFactSourcePages`, `search.fact_source_pages`, GBRA-205, default off): the conversations (`facts.source_markdown_slug`, never the entity page) of the best-matching admitted facts, at most 2 not already present, read through `getChunkWindows` under the caller's read scope and placed after the top 3 rows; the row count never grows. Tests: `test/search-8k-conversion.test.ts`.
diff --git a/docs/evidence-delivery.md b/docs/evidence-delivery.md
index 87adce4b58..0e0e5d6ccf 100644
--- a/docs/evidence-delivery.md
+++ b/docs/evidence-delivery.md
@@ -142,6 +142,15 @@ Think reads `think.return_unit` (default `auto`) and never
Under `auto`, think renders conversation pages whole and keeps its usual
excerpts for every other page.
+### Query budgets (GBRA-205)
+
+`query`'s `token_budget` without a `return_unit` keeps its chunk-mode
+meaning by default. `gbrain config set search.query_budget_unit auto` makes
+it the same hard cap `search` uses: conversations come back whole or cut,
+packed by `search.auto_packing`. A budget below 32 is then refused.
+`search.evidence_titles` (default off) appends each page block's title to
+its date header line when date headers are on.
+
### Date headers
With `search.evidence_date_header` on (default off), every delivered block,
@@ -192,7 +201,7 @@ each hit's `score`.
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.evidence_tail_trim`, `search.auto_packing`,
+`search.return_budget_max_remote`, `search.evidence_date_header`, `search.evidence_titles`, `search.evidence_tail_trim`, `search.auto_packing`, `search.query_budget_unit`,
`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"`
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index b7ae9f7c73..6a532dc58a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ 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 1932 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); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.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 2012 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); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +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); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)
+src/core/config.ts 2014 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); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +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); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts)
src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)
src/core/bootstrap/harness.ts 2592 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); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
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
@@ -44,6 +44,6 @@ src/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave:
src/core/search/mode.ts 1704 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); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured)
src/commands/eval-longmemeval.ts 1544 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); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +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); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")
-src/core/search/evidence-delivery.ts 1733 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); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)
+src/core/search/evidence-delivery.ts 1740 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); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts)
src/commands/config.ts 1523 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/src/core/config.ts b/src/core/config.ts
index 0a95052dce..ce82cb7d92 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1434,10 +1434,12 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.auto_packing',
'search.long_page_unit', 'search.long_page_min_chars', // F2: delivery unit for long (rendered body >= min_chars, default 20000) non-conversation hits under an implied auto: off (default) | window | section | page (search/evidence-delivery.ts)
'search.evidence_date_header', // C1: one-line date header per delivered block (default off; search/evidence-date.ts)
+ 'search.evidence_titles', 'search.query_budget_unit', // GBRA-205, default off: titles on page date headers and think <page> tags (search/evidence-date.ts); query token_budget as the delivery hard cap, chunk | auto (search/evidence-packing.ts)
'search.evidence_tail_trim', // GBRA-156: protected top-3 tail trim of auto conversation blocks (default off; search/evidence-tail-trim.ts)
'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.query_facts_block', 'search.fact_source_pages', // GBRA-205, default off: a dated facts block (up to 22% of a query budget) ahead of the pages; matched facts' source conversations join the hits (search/facts-arm.ts)
'search.page_rank_cut', // W5: whole_pages (default) | off — page unit + caller token_budget stops adding pages once their whole pages fill factor x the budget (search/page-rank-cut.ts)
'search.page_rank_cut_factor', // W5: whole_pages target = factor x the budget (default 1.5)
'think.return_unit',
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 6f11a42d0b..6db5ee8b69 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -43,7 +43,7 @@ import { keepFrontmatterMatches } from '../search/frontmatter-where.ts';
import { WHERE_PARAM, whereOpParam } from './where-param.ts';
import { searchFilterHint } from '../search/filter-hint.ts';
import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';
-import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, pagePlanHits, resolveEvidencePlan, selectLongPages, unsupportedDelivery, withLongPagePolicy, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
+import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, pagePlanHits, queryBudgetUsesAuto, resolveEvidencePlan, selectLongPages, unsupportedDelivery, withLongPagePolicy, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { SAFE_FENCE_CHUNKER_VERSION, chunkManifestReads } from '../search/safe-chunks.ts';
@@ -171,12 +171,13 @@ const RETURN_WINDOW_PARAM = {
/**
* With a plan, `token_budget` budgets the delivered evidence, so query's
* chunk-level budget stays off; query's token_budget without a return_unit
- * keeps its chunk-mode meaning. The long-page policy (`search.long_page_unit`)
+ * keeps its chunk-mode meaning unless `search.query_budget_unit` is `auto`
+ * (GBRA-205, default off). The long-page policy (`search.long_page_unit`)
* is resolved here, at the search/query caller, and nowhere else.
*/
async function evidencePlanFor(ctx: OperationContext, p: Record<string, unknown>, snippetCap: number, op: 'search' | 'query'): Promise<EvidencePlan | null> {
return withLongPagePolicy(ctx.engine, await resolveEvidencePlan(ctx.engine, {
- legacyBudget: op === 'query' && typeof p.token_budget === 'number',
+ legacyBudget: op === 'query' && typeof p.token_budget === 'number' && !await queryBudgetUsesAuto(ctx.engine),
remote: ctx.remote,
viaSubagent: ctx.viaSubagent,
returnUnit: p.return_unit,
diff --git a/src/core/search/evidence-date.ts b/src/core/search/evidence-date.ts
index bafaa8d19f..c4f1c78dd4 100644
--- a/src/core/search/evidence-date.ts
+++ b/src/core/search/evidence-date.ts
@@ -28,6 +28,8 @@
import { computeEffectiveDate, formatBrainDay } from '../effective-date.ts';
export const EVIDENCE_DATE_HEADER_KEY = 'search.evidence_date_header';
+/** GBRA-205: with the date header on, a page block's header line also carries its title (default off). */
+export const EVIDENCE_TITLES_KEY = 'search.evidence_titles';
export const UNKNOWN_DATE = 'unknown';
const OBSERVATION_SOURCES = new Set(['filename', 'date', 'published', 'created']);
@@ -146,25 +148,50 @@ async function factObservationDates(
return out;
}
+/** A page header line with the page's title after the bracket, on one line; an empty title adds nothing. */
+export function titledPageHeader(header: string, title: string | null | undefined): string {
+ const clean = (title ?? '').replace(/\s+/g, ' ').trim();
+ return clean ? `${header} ${clean}` : header;
+}
+
+type HeaderHit = { page_id: number; title?: string | null; chunk_text?: string | null; fact_row?: { valid_from: string; valid_until: string | null } };
+
/**
* The date header line (with its newline) for each delivered block, read for
* every hit page in one query. A failed read renders `unknown` for every page
* and calls `onUnavailable` once. A facts-arm row gets its fact header unless
- * its text already starts with one.
+ * its text already starts with one. With `titles`, a page block's line ends
+ * with its title (`search.evidence_titles`); fact headers never change.
*/
export async function blockDateHeaders(engine: Parameters<typeof loadPageDateHeaders>[0],
- hits: Array<{ page_id: number; chunk_text?: string | null; fact_row?: { valid_from: string; valid_until: string | null } }>,
- onUnavailable: () => void): Promise<(hit: { page_id: number; chunk_text?: string | null; fact_row?: { valid_from: string; valid_until: string | null } }) => string> {
+ hits: HeaderHit[], onUnavailable: () => void, opts: { titles?: boolean } = {}): Promise<(hit: HeaderHit) => string> {
let headers: Map<number, string>;
try { headers = await loadPageDateHeaders(engine, hits.map(h => h.page_id)); } catch { headers = new Map(); onUnavailable(); }
- return hit => hit.fact_row ? (hit.chunk_text?.startsWith('[observed ') ? '' : `${factDateHeader(hit.fact_row)}\n`) : `${headers.get(hit.page_id) ?? pageDateHeader(null)}\n`;
+ return hit => {
+ if (hit.fact_row) return hit.chunk_text?.startsWith('[observed ') ? '' : `${factDateHeader(hit.fact_row)}\n`;
+ const header = headers.get(hit.page_id) ?? pageDateHeader(null);
+ return `${opts.titles ? titledPageHeader(header, hit.title) : header}\n`;
+ };
+}
+
+function configFlagOn(raw: string | null | undefined): boolean {
+ const v = raw?.trim().toLowerCase();
+ return v === 'true' || v === 'on' || v === '1' || v === 'yes';
}
/** `search.evidence_date_header` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
export async function evidenceDateHeaderEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
try {
- const raw = (await engine.getConfig(EVIDENCE_DATE_HEADER_KEY))?.trim().toLowerCase();
- return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';
+ return configFlagOn(await engine.getConfig(EVIDENCE_DATE_HEADER_KEY));
+ } catch {
+ return false;
+ }
+}
+
+/** `search.evidence_titles` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
+export async function evidenceTitlesEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ try {
+ return configFlagOn(await engine.getConfig(EVIDENCE_TITLES_KEY));
} catch {
return false;
}
diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.ts
index d7f7f1addf..c95051000a 100644
--- a/src/core/search/evidence-delivery.ts
+++ b/src/core/search/evidence-delivery.ts
@@ -37,14 +37,14 @@ import { DEFAULT_INLINE_BODY_BYTES, locateChunksByStoredSpans, projectPageText,
import { readSegmentedWindows } from './segmented-evidence.ts';
import { stripChunkHeader } from '../chunkers/code.ts';
import { OperationError } from '../ops/contract.ts';
-import { blockDateHeaders, evidenceDateHeaderEnabled } from './evidence-date.ts';
+import { blockDateHeaders, evidenceDateHeaderEnabled, evidenceTitlesEnabled } from './evidence-date.ts';
import { cutWholePages, resolvePageRankCut, type PageRankCut, type PageRankCutMeta } from './page-rank-cut.ts';
import { evidenceTailTrimEnabled, trimEvidenceTail, type TailTrimMeta } from './evidence-tail-trim.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';
-export { AUTO_PACKINGS, AUTO_PACKING_CONFIG_KEY, DEFAULT_AUTO_PACKING, MIN_EXPLICIT_AUTO_BUDGET, autoPackingValueProblem, parseAutoPacking, type AutoPacking } from './evidence-packing.ts';
+export { AUTO_PACKINGS, AUTO_PACKING_CONFIG_KEY, DEFAULT_AUTO_PACKING, MIN_EXPLICIT_AUTO_BUDGET, QUERY_BUDGET_UNIT_CONFIG_KEY, autoPackingValueProblem, parseAutoPacking, queryBudgetUsesAuto, type AutoPacking } from './evidence-packing.ts';
export const RETURN_UNITS = ['chunk', 'window', 'section', 'page', 'auto'] as const;
export type ReturnUnit = typeof RETURN_UNITS[number];
@@ -116,6 +116,8 @@ export interface DeliveryMeta {
budget_clamped?: { requested: number; max: number };
/** Present (true) when every block starts with its one-line date header (`search.evidence_date_header`). */
date_header?: true;
+ /** Present (true) when page block headers also carry the page title (`search.evidence_titles`). */
+ title_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). */
@@ -140,6 +142,8 @@ export interface EvidencePlan {
budgetClamped?: { requested: number; max: number };
/** `search.evidence_date_header` is on: each block starts with its date header line. */
dateHeader?: true;
+ /** `search.evidence_titles` is on with the date header: page block header lines end with the page title. */
+ titleHeader?: true;
/** F2: set only by the search/query caller (withLongPagePolicy); recall, think and assemble_evidence never carry it. */
longPage?: LongPagePolicy;
/** W5: page unit + caller budget + `search.page_rank_cut: whole_pages` (page-rank-cut.ts). */
@@ -280,6 +284,7 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePla
}
}
const rankCut = unit === 'page' && budgetExplicit ? await resolvePageRankCut(engine, budget) : undefined;
+ const dateHeader = await evidenceDateHeaderEnabled(engine);
return {
requestedUnit: unit,
unit,
@@ -289,7 +294,8 @@ export async function resolveEvidencePlan(engine: BrainEngine, input: ResolvePla
budgetExplicit,
packing,
...(budgetClamped ? { budgetClamped } : {}),
- ...(await evidenceDateHeaderEnabled(engine) ? { dateHeader: true as const } : {}),
+ ...(dateHeader ? { dateHeader: true as const } : {}),
+ ...(dateHeader && await evidenceTitlesEnabled(engine) ? { titleHeader: true as const } : {}),
...(rankCut ? { rankCut } : {}),
...(unit === 'auto' && await evidenceTailTrimEnabled(engine) ? { tailTrim: true as const } : {}),
};
@@ -1277,7 +1283,7 @@ export async function deliverEvidence(
return page?.segmented ? [[g, planSegmentedBlock(engine, page, g.hits, unit, plan.window, scope.detail !== 'low').catch(() => null)] as const] : [];
}));
// C1 date headers: one line per block (passthrough rows included), paid for inside the budget like the title.
- const headerFor = plan.dateHeader ? await blockDateHeaders(engine, hits, () => fallbacks.add('date_header_unavailable')) : () => '';
+ const headerFor = plan.dateHeader ? await blockDateHeaders(engine, hits, () => fallbacks.add('date_header_unavailable'), { titles: plan.titleHeader === true }) : () => '';
const planned: Block[] = [];
for (const g of groups) {
@@ -1392,6 +1398,7 @@ export async function deliverEvidence(
...(plan.budgetClamped ? { budget_clamped: plan.budgetClamped } : {}),
...(capped ? { auto_packing: plan.packing } : {}),
...(plan.dateHeader ? { date_header: true as const } : {}),
+ ...(plan.titleHeader ? { title_header: true as const } : {}),
...(rankCutMeta ? { page_rank_cut: rankCutMeta } : {}),
...(tailTrim ? { tail_trim: tailTrim } : {}),
};
diff --git a/src/core/search/evidence-packing.ts b/src/core/search/evidence-packing.ts
index 59096780a5..47ff6c0a27 100644
--- a/src/core/search/evidence-packing.ts
+++ b/src/core/search/evidence-packing.ts
@@ -48,3 +48,19 @@ export async function configPacking(engine: BrainEngine): Promise<AutoPacking> {
} catch { /* config unreadable: stay on the default */ }
return DEFAULT_AUTO_PACKING;
}
+
+/**
+ * GBRA-205: what `query`'s token_budget means when the call names no return_unit.
+ * `chunk` (default): the legacy chunk trim. `auto`: the budget is evidence
+ * delivery's hard cap, as for `search` (whole conversations, packed by search.auto_packing).
+ */
+export const QUERY_BUDGET_UNIT_CONFIG_KEY = 'search.query_budget_unit';
+
+/** `search.query_budget_unit` is `auto`; `chunk`, unset or unreadable keeps query's legacy chunk budget. */
+export async function queryBudgetUsesAuto(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
+ try {
+ return (await engine.getConfig(QUERY_BUDGET_UNIT_CONFIG_KEY))?.trim().toLowerCase() === 'auto';
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.ts
index 1b6ba694b2..52ecd90a57 100644
--- a/src/core/search/facts-arm.ts
+++ b/src/core/search/facts-arm.ts
@@ -25,6 +25,7 @@ import { pageReadFilter } from './read-policy-sql.ts';
import { enforceTokenBudget, resultTokens } from './token-budget.ts';
import { factDateHeader } from './evidence-date.ts';
import type { TrustTier } from '../trust/tier.ts';
+import { conversationSignal } from './evidence-delivery.ts';
export { queryTerms } from './fact-relevance.ts';
@@ -43,6 +44,19 @@ export const TEMPORAL_RESERVE_SHARE = 0.15;
export const MAX_RESERVE_ROWS = 20;
/** Share of the caller's row count reserved facts may take (at least one row). */
export const TEMPORAL_RESERVE_ROW_SHARE = 0.3;
+
+/** GBRA-205 facts block (`search.query_facts_block`, default off): every budgeted query, ahead of the pages. */
+export const QUERY_FACTS_BLOCK_KEY = 'search.query_facts_block';
+/** Share of the caller's token budget the facts block may take (about 1,800 of 8,100, as the measured combined lane). */
+export const QUERY_FACTS_BLOCK_SHARE = 0.22;
+export const MAX_FACTS_BLOCK_ROWS = 40;
+
+/** GBRA-205 (`search.fact_source_pages`, default off): the conversations matched facts came from join the hits. */
+export const FACT_SOURCE_PAGES_KEY = 'search.fact_source_pages';
+export const MAX_FACT_SOURCE_PAGES = 2;
+/** Source pages go in after this many organic rows. */
+export const FACT_SOURCE_PAGE_RANK = 3;
+
const MONTHS = 'january|february|march|april|may|june|july|august|september|october|november|december';
const TEMPORAL_CUE = new RegExp(`\\b(when|before|after|since|until|till|during|ago|earlier|later|earliest|latest|first|last|previous|next|dates?|day|week|month|year|order|sequence|${MONTHS})\\b`
+ `|\\bhow (long|many (days|weeks|months|years))\\b|\\bwhat time\\b|\\b\\d{4}-\\d{2}-\\d{2}\\b`, 'i');
@@ -174,6 +188,18 @@ export async function applyFactsArm(engine: BrainEngine, query: string, results:
}
}
+interface ReservePolicy {
+ share: number;
+ maxRows: number;
+ /** Share of the caller's row count the facts may take (they replace the lowest page rows); null: they add rows. */
+ rowShare: number | null;
+ /** Where the facts go: after the pages (temporal reserve) or ahead of them (facts block). */
+ position: 'after' | 'before';
+}
+
+const TEMPORAL_RESERVE: ReservePolicy = { share: TEMPORAL_RESERVE_SHARE, maxRows: MAX_RESERVE_ROWS, rowShare: TEMPORAL_RESERVE_ROW_SHARE, position: 'after' };
+const FACTS_BLOCK: ReservePolicy = { share: QUERY_FACTS_BLOCK_SHARE, maxRows: MAX_FACTS_BLOCK_ROWS, rowShare: null, position: 'before' };
+
/**
* Temporal fact reserve: for a query with a temporal cue and a token budget,
* the facts that best match the question (the shared scorer in
@@ -184,19 +210,34 @@ export async function applyFactsArm(engine: BrainEngine, query: string, results:
* else the lowest page row) and pages fill the rest of the budget. No match or
* any error: the results unchanged.
*/
-export async function applyTemporalFactReserve(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }): Promise<SearchResult[]> {
+export function applyTemporalFactReserve(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }): Promise<SearchResult[]> {
+ return applyFactReserve(engine, query, results, opts, TEMPORAL_RESERVE);
+}
+
+/**
+ * Facts block (GBRA-205): the same question-ranked, dated facts as the
+ * temporal reserve, for every budgeted query, up to QUERY_FACTS_BLOCK_SHARE
+ * of the budget and MAX_FACTS_BLOCK_ROWS rows, oldest first ahead of the
+ * pages. The facts add rows (every page row stays) and pages fill the rest of
+ * the budget. No match or any error: the results unchanged.
+ */
+export function applyFactsBlock(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }): Promise<SearchResult[]> {
+ return applyFactReserve(engine, query, results, opts, FACTS_BLOCK);
+}
+
+async function applyFactReserve(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }, policy: ReservePolicy): Promise<SearchResult[]> {
try {
const { candidates } = await collectFactCandidates(engine, query, await poolScope(engine, opts), opts.queryEmbedding,
- { depth: { keyword: 50, cosine: 50, entity: MAX_RESERVE_ROWS }, cosineForAll: true });
+ { depth: { keyword: 50, cosine: 50, entity: policy.maxRows }, cosineForAll: true });
const scored = scoreFactCandidates(query, candidates).filter(s => admitted(s, 'reserve')).map(s => ({ c: s.candidate }));
if (!scored.length) return results;
const rowCap = Math.max(results.length, (await opts.rowCap?.().catch(() => 0)) ?? 0);
+ const maxRows = policy.rowShare === null ? policy.maxRows : Math.min(policy.maxRows, Math.max(1, Math.floor(rowCap * policy.rowShare)));
const pageSlugs = await readableEntityPages(engine, scored.map(x => x.c), opts.readScope).catch(() => new Set<string>());
- const pagesFloor = results.reduce((m, r) => (Number.isFinite(r.score) && r.score < m ? r.score : m), results[0]?.score ?? 1);
- let left = Math.floor(opts.budget * TEMPORAL_RESERVE_SHARE);
+ let left = Math.floor(opts.budget * policy.share);
const chosen: Array<{ c: FactCandidate; row: SearchResult }> = [];
for (const { c } of scored) {
- if (chosen.length >= Math.min(MAX_RESERVE_ROWS, Math.max(1, Math.floor(rowCap * TEMPORAL_RESERVE_ROW_SHARE)))) break;
+ if (chosen.length >= maxRows) break;
const row = factRow(c, 0, c.entity_slug && pageSlugs.has(`${c.source_id}\u0000${c.entity_slug}`) ? c.entity_slug : undefined);
row.chunk_text = `${factDateHeader(c)}\n${c.fact}`;
const cost = resultTokens(row);
@@ -206,10 +247,14 @@ export async function applyTemporalFactReserve(engine: BrainEngine, query: strin
}
if (!chosen.length) return results;
chosen.sort((a, b) => new Date(a.c.valid_from).getTime() - new Date(b.c.valid_from).getTime() || Number(a.c.id) - Number(b.c.id));
- const rows = chosen.map(({ row }, i) => ({ ...row, score: pagesFloor - (i + 1) * 1e-6 }));
- let pages = results.slice(0, Math.max(0, Math.min(results.length, rowCap - rows.length))).map(r => ({ ...r }));
+ const pagesFloor = results.reduce((m, r) => (Number.isFinite(r.score) && r.score < m ? r.score : m), results[0]?.score ?? 1);
+ const pagesTop = results.reduce((m, r) => (Number.isFinite(r.score) && r.score > m ? r.score : m), results[0]?.score ?? 1);
+ const rows = policy.position === 'after'
+ ? chosen.map(({ row }, i) => ({ ...row, score: pagesFloor - (i + 1) * 1e-6 }))
+ : chosen.map(({ row }, i) => ({ ...row, score: pagesTop + (chosen.length - i) * 1e-6 }));
+ let pages = (policy.rowShare === null ? results : results.slice(0, Math.max(0, Math.min(results.length, rowCap - rows.length)))).map(r => ({ ...r }));
if (opts.tokenBudget) pages = enforceTokenBudget(pages, Math.max(1, opts.tokenBudget - rows.reduce((n, r) => n + resultTokens(r), 0))).results;
- const merged = [...pages, ...rows];
+ const merged = policy.position === 'after' ? [...pages, ...rows] : [...rows, ...pages];
await stampSupersededClaims(engine, merged, chosen.map(x => x.c)).catch(() => undefined);
return merged;
} catch {
@@ -217,6 +262,61 @@ export async function applyTemporalFactReserve(engine: BrainEngine, query: strin
}
}
+/**
+ * Fact source pages (GBRA-205): the conversations the question's best-matching
+ * facts were extracted from (`facts.source_markdown_slug`, never the fact's
+ * own entity page), up to MAX_FACT_SOURCE_PAGES not already in the results,
+ * go in after the top FACT_SOURCE_PAGE_RANK rows, so evidence delivery can
+ * hand over the whole session. Each page is read through `getChunkWindows`
+ * under the caller's read scope, so an unreadable page is absent. The row
+ * count never grows (the lowest rows give way). No match or any error: the
+ * results unchanged.
+ */
+export async function applyFactSourcePages(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts): Promise<SearchResult[]> {
+ try {
+ const { candidates } = await collectFactCandidates(engine, query, await poolScope(engine, opts), opts.queryEmbedding,
+ { depth: { keyword: 50, cosine: 50, entity: MAX_RESERVE_ROWS }, cosineForAll: true });
+ const ranked = scoreFactCandidates(query, candidates).filter(s => admitted(s, 'reserve')).map(s => Number(s.candidate.id));
+ if (!ranked.length) return results;
+ const sources = await engine.executeRaw<{ id: number; page_id: number; slug: string; title: string | null; type: string | null }>(
+ `SELECT f.id, p.id AS page_id, p.slug, p.title, p.type FROM facts f
+ JOIN pages p ON p.source_id = f.source_id AND p.slug = f.source_markdown_slug AND p.deleted_at IS NULL
+ WHERE f.id = ANY($1::bigint[]) AND f.source_markdown_slug IS DISTINCT FROM f.entity_slug`, [ranked]);
+ const rank = new Map(ranked.map((id, i) => [id, i]));
+ const present = new Set(results.map(r => r.page_id));
+ const wanted: typeof sources = [];
+ for (const s of [...sources].sort((a, b) => rank.get(Number(a.id))! - rank.get(Number(b.id))!)) {
+ if (wanted.length >= MAX_FACT_SOURCE_PAGES) break;
+ if (present.has(Number(s.page_id)) || !conversationSignal({ type: s.type, slug: s.slug })) continue;
+ present.add(Number(s.page_id));
+ wanted.push(s);
+ }
+ if (!wanted.length) return results;
+ const windows = await engine.getChunkWindows(wanted.map((w, i) => ({ page_id: Number(w.page_id), from_index: 0, to_index: 0, priority: i })),
+ { sourceId: opts.readScope?.sourceId, sourceIds: opts.readScope?.sourceIds, excludePrivate: opts.readScope?.excludePrivate, requireSafeChunks: opts.readScope?.requireSafeChunks,
+ minTrust: opts.readScope?.minTrust, suppressFlagged: opts.readScope?.suppressFlagged, chunkSources: ['compiled_truth'], maxRows: wanted.length });
+ const byId = new Map(windows.map(w => [w.page_id, w]));
+ const at = Math.min(FACT_SOURCE_PAGE_RANK, results.length);
+ const above = results[at - 1]?.score ?? 1;
+ const added: SearchResult[] = [];
+ for (const w of wanted) {
+ const window = byId.get(Number(w.page_id));
+ const chunk = window?.chunks[0];
+ if (!window || !chunk) continue;
+ added.push({
+ page_id: Number(w.page_id), slug: window.slug, title: w.title ?? window.slug, type: window.type as SearchResult['type'], source_id: window.source_id,
+ chunk_text: chunk.chunk_text, chunk_index: chunk.chunk_index, chunk_id: chunk.id, chunk_source: chunk.chunk_source as SearchResult['chunk_source'],
+ score: above - (added.length + 1) * 1e-9, stale: false,
+ } as SearchResult);
+ }
+ if (!added.length) return results;
+ const rowCap = Math.max(results.length, (await opts.rowCap?.().catch(() => 0)) ?? 0);
+ return [...results.slice(0, at), ...added, ...results.slice(at)].slice(0, rowCap);
+ } catch {
+ return results;
+ }
+}
+
/** `search.temporal_fact_reserve` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
export async function temporalFactReserveEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
try {
@@ -227,6 +327,26 @@ export async function temporalFactReserveEnabled(engine: { getConfig(key: string
}
}
+/** `search.query_facts_block` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
+export async function queryFactsBlockEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ try {
+ const raw = (await engine.getConfig(QUERY_FACTS_BLOCK_KEY))?.trim().toLowerCase();
+ return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';
+ } catch {
+ return false;
+ }
+}
+
+/** `search.fact_source_pages` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */
+export async function factSourcePagesEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ try {
+ const raw = (await engine.getConfig(FACT_SOURCE_PAGES_KEY))?.trim().toLowerCase();
+ return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';
+ } catch {
+ return false;
+ }
+}
+
/**
* `search.query_facts_arm`: on by default (gates 1b and 2 passed,
* docs/eval/decisions/query-facts-arm/); 'false' | 'off' | '0' | 'no' turns it
diff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.ts
index 0dfab9fb3e..e00fa25f0e 100644
--- a/src/core/search/query-arms.ts
+++ b/src/core/search/query-arms.ts
@@ -1,16 +1,18 @@
/**
* The `query` op's post-retrieval arms, applied after hybrid search and the
* declared-name fan-out, before the CRAG grade: entity anchoring
- * (`search.entity_anchoring`, default off, search/entity-anchor.ts) and then
- * the facts arm (`search.query_facts_arm`, default on, search/facts-arm.ts),
- * or in its place, for a query with a temporal cue and a token budget, the
+ * (`search.entity_anchoring`, default off, search/entity-anchor.ts), fact
+ * source pages (`search.fact_source_pages`, default off) and then the facts
+ * arm (`search.query_facts_arm`, default on, search/facts-arm.ts), or in its
+ * place, for a query with a token budget, the facts block
+ * (`search.query_facts_block`, default off) or, with a temporal cue, the
* temporal fact reserve (`search.temporal_fact_reserve`, default off). With
* all off the rows pass through unchanged.
*/
import type { BrainEngine } from '../engine.ts';
import type { PageReadScope, SearchResult } from '../types.ts';
import { anchorOpResults } from './entity-anchor.ts';
-import { applyFactsArm, applyTemporalFactReserve, hasTemporalCue, queryFactsArmEnabled, temporalFactReserveEnabled } from './facts-arm.ts';
+import { applyFactsArm, applyFactsBlock, applyFactSourcePages, applyTemporalFactReserve, factSourcePagesEnabled, hasTemporalCue, queryFactsArmEnabled, queryFactsBlockEnabled, temporalFactReserveEnabled } from './facts-arm.ts';
import { type StageTimer, UNTIMED } from './stage-timings.ts';
export async function applyQueryArms(engine: BrainEngine, p: Record<string, unknown>, query: string, results: SearchResult[],
@@ -25,8 +27,10 @@ async function applyFactsStage(engine: BrainEngine, p: Record<string, unknown>,
if (p.offset || scope.filtered || p.since || p.until || p.lang || p.symbol_kind || p.near_symbol) return anchored;
const tokenBudget = !scope.evidencePlan && typeof p.token_budget === 'number' ? p.token_budget : undefined;
const opts = { sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, minTrust: scope.minTrust, suppressFlagged: scope.suppressFlagged, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope, tokenBudget };
+ const pages = await factSourcePagesEnabled(engine) ? await applyFactSourcePages(engine, query, anchored, opts) : anchored;
const budget = scope.evidencePlan ? scope.evidenceBudget : tokenBudget;
- if (budget && hasTemporalCue(query) && await temporalFactReserveEnabled(engine)) return applyTemporalFactReserve(engine, query, anchored, { ...opts, budget });
- if (!await queryFactsArmEnabled(engine)) return anchored;
- return applyFactsArm(engine, query, anchored, opts);
+ if (budget && await queryFactsBlockEnabled(engine)) return applyFactsBlock(engine, query, pages, { ...opts, budget });
+ if (budget && hasTemporalCue(query) && await temporalFactReserveEnabled(engine)) return applyTemporalFactReserve(engine, query, pages, { ...opts, budget });
+ if (!await queryFactsArmEnabled(engine)) return pages;
+ return applyFactsArm(engine, query, pages, opts);
}
diff --git a/src/core/think/gather.ts b/src/core/think/gather.ts
index ca1081a076..549791965b 100644
--- a/src/core/think/gather.ts
+++ b/src/core/think/gather.ts
@@ -647,7 +647,7 @@ export function renderPagesBlockDetailed(
pages: SearchResult[],
excerptLen = 600,
query = '',
- opts: { verbatim?: boolean | ((p: SearchResult) => boolean); verbatimLen?: number; timeZone?: string } = {},
+ opts: { verbatim?: boolean | ((p: SearchResult) => boolean); verbatimLen?: number; timeZone?: string; titles?: boolean } = {},
): { text: string; truncated: boolean } {
let truncated = false;
const text = pages.map((p, idx) => {
@@ -667,12 +667,14 @@ export function renderPagesBlockDetailed(
const flag = (p.injection_suspected ? `${INJECTION_SUSPECTED_LINE}\n` : '')
+ (p.trust_tier && needsDataEnvelope(p.trust_tier) ? `${EXTERNAL_DATA_RULE}\n` : '') + graphEvidenceLine(p);
const trustAttr = p.trust_tier ? ` ${trustAttributes({ trust_tier: p.trust_tier, origin: p.origin ?? 'legacy' })}` : '';
+ const cleanTitle = opts.titles ? title.replace(/[\r\n<>]/g, ' ').replace(/"/g, "'").replace(/\s+/g, ' ').trim() : '';
+ const titleAttr = cleanTitle ? ` title="${cleanTitle}"` : '';
// Evidence delivery: the block was already budgeted and cut around its
// hits; render it whole (capped only by excerptLen).
if (typeof opts.verbatim === 'function' ? opts.verbatim(p) : opts.verbatim) {
const cap = opts.verbatimLen ?? excerptLen;
if (content.length > cap || (p as { delivered?: { truncated?: boolean } }).delivered?.truncated === true) truncated = true;
- return `<page slug="${slug}" rank="${idx + 1}"${dateAttr}${trustAttr}>\n${flag}${content.slice(0, cap)}\n</page>`;
+ return `<page slug="${slug}" rank="${idx + 1}"${titleAttr}${dateAttr}${trustAttr}>\n${flag}${content.slice(0, cap)}\n</page>`;
}
const excerpt = selectRelevantExcerptDetailed(
content,
@@ -685,7 +687,7 @@ export function renderPagesBlockDetailed(
(excerpt.truncatedStart ? `${EXCERPT_CUT_START_MARKER}\n` : '') +
excerpt.text +
(excerpt.truncatedEnd ? `\n${EXCERPT_CUT_END_MARKER}` : '');
- return `<page slug="${slug}" rank="${idx + 1}"${dateAttr}${trustAttr}>\n${flag}${body}\n</page>`;
+ return `<page slug="${slug}" rank="${idx + 1}"${titleAttr}${dateAttr}${trustAttr}>\n${flag}${body}\n</page>`;
}).join('\n\n');
return { text, truncated };
}
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 9f275a8e70..9117c6842c 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -38,6 +38,7 @@ import { resolveThinkWindow } from './temporal-window.ts';
import { resolveThinkTemporalContext } from './temporal-context.ts';
import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { deliverEvidence, effectivePlan, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';
+import { evidenceTitlesEnabled } from '../search/evidence-date.ts';
import { startThinkDecide, thinkAbstainResult, type ThinkAbstention } from './decide.ts';
import { classifyIntent } from './intent.ts';
import { deriveTrust, type TaintRef } from '../trust/taint.ts';
@@ -555,17 +556,18 @@ function stampCitationSources(citations: ParsedCitation[], pages: SearchResult[]
}
async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[], timeZone: string, warnings: string[]): Promise<{ pagesBlock: string; evidenceTruncated: boolean; evidenceDelivery?: DeliveryMeta }> {
- const [plan, budget] = await Promise.all([
+ const [plan, budget, titles] = await Promise.all([
resolveEvidencePlan(engine, {
remote: opts.remote, returnUnit: undefined, returnWindow: undefined, budget: undefined,
snippetChars: undefined, snippetCap: 0, configKey: THINK_RETURN_UNIT_CONFIG_KEY, op: 'think',
}),
readThinkPagesBudget(engine, warnings), // #5461
+ evidenceTitlesEnabled(engine), // GBRA-205
]);
const excerptLen = pagesBlockExcerptLen(pages.length, undefined, budget);
const applied = effectivePlan(plan, pages);
if (!applied) {
- const rendered = renderPagesBlockDetailed(pages, excerptLen, opts.question, { timeZone });
+ const rendered = renderPagesBlockDetailed(pages, excerptLen, opts.question, { timeZone, titles });
return { pagesBlock: rendered.text, evidenceTruncated: rendered.truncated };
}
const delivered = await deliverEvidence(engine, pages, applied, {
@@ -575,8 +577,8 @@ async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages:
});
const rendered = applied.unit === 'auto'
? renderPagesBlockDetailed(delivered.results, excerptLen, opts.question,
- { verbatim: r => r.delivered?.reason !== 'not_conversation' && r.delivered?.reason !== 'conversation_over_budget', verbatimLen: EVIDENCE_BLOCK_CHAR_CAP, timeZone })
- : renderPagesBlockDetailed(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true, timeZone });
+ { verbatim: r => r.delivered?.reason !== 'not_conversation' && r.delivered?.reason !== 'conversation_over_budget', verbatimLen: EVIDENCE_BLOCK_CHAR_CAP, timeZone, titles })
+ : renderPagesBlockDetailed(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true, timeZone, titles });
return { pagesBlock: rendered.text, evidenceTruncated: rendered.truncated, evidenceDelivery: delivered.delivery };
}
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index b63b563e9f..665115d8a4 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -56,6 +56,10 @@ 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)
+ 'search.query_facts_block', // search/facts-arm.ts (search/query-arms.ts, GBRA-205)
+ 'search.fact_source_pages', // search/facts-arm.ts (search/query-arms.ts, GBRA-205)
+ 'search.evidence_titles', // search/evidence-date.ts (GBRA-205)
+ 'search.query_budget_unit', // search/evidence-delivery.ts via ops/search.ts (GBRA-205)
PAGE_RANK_CUT_KEY, // search/page-rank-cut.ts via evidence-delivery.ts (W5)
PAGE_RANK_CUT_FACTOR_KEY,
];
diff --git a/test/search-8k-conversion.test.ts b/test/search-8k-conversion.test.ts
new file mode 100644
index 0000000000..bd8efbca74
--- /dev/null
+++ b/test/search-8k-conversion.test.ts
@@ -0,0 +1,168 @@
+/**
+ * GBRA-205 8k conversion flags, each default off: what an answer model reads
+ * from `query` under an explicit token budget.
+ *
+ * - `search.query_budget_unit` (chunk | auto): `auto` lets query's
+ * token_budget engage evidence delivery's hard cap (whole conversations,
+ * date headers when on) instead of the legacy chunk trim.
+ * - `search.evidence_titles`: each page block's date header line carries the
+ * page title, and think's <page> tag a title attribute.
+ * - `search.query_facts_block`: every budgeted query (no temporal cue needed)
+ * gives question-ranked dated facts up to QUERY_FACTS_BLOCK_SHARE of the
+ * budget, ahead of the pages.
+ * - `search.fact_source_pages`: the conversation a matched fact came from
+ * joins the hits after the top FACT_SOURCE_PAGE_RANK rows; the row count
+ * never grows.
+ *
+ * With every key unset, results are byte-identical to the build without them.
+ * PGLite, keyword-only, no network.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { handleToolCall } from '../src/mcp/server.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { FACT_SOURCE_PAGE_RANK, FACT_SOURCE_PAGES_KEY, MAX_FACT_SOURCE_PAGES, MAX_FACTS_BLOCK_ROWS, QUERY_FACTS_BLOCK_KEY, QUERY_FACTS_BLOCK_SHARE } from '../src/core/search/facts-arm.ts';
+import { QUERY_BUDGET_UNIT_CONFIG_KEY } from '../src/core/search/evidence-delivery.ts';
+import { EVIDENCE_DATE_HEADER_KEY, EVIDENCE_TITLES_KEY } from '../src/core/search/evidence-date.ts';
+import { renderPagesBlockDetailed } from '../src/core/think/gather.ts';
+import { resultTokens } from '../src/core/search/token-budget.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { newSource, page, putPage } from './helpers/pinned-questions-fixture.ts';
+
+type Row = SearchResult & { delivered?: { unit?: string; reason?: string; tokens: number } };
+
+let engine: PGLiteEngine;
+let sourceId: string;
+const KEYS = [QUERY_BUDGET_UNIT_CONFIG_KEY, EVIDENCE_TITLES_KEY, EVIDENCE_DATE_HEADER_KEY, QUERY_FACTS_BLOCK_KEY, FACT_SOURCE_PAGES_KEY];
+const PLAIN = 'Where is the Forge offsite venue booked?';
+const query = async (q: string, params: Record<string, unknown> = {}) =>
+ await handleToolCall(engine, 'query', { query: q, expand: false, use_cache: false, source_id: sourceId, limit: 6, ...params }) as Row[];
+const withKeys = async <T>(values: Record<string, string>, run: () => Promise<T>): Promise<T> => {
+ for (const [k, v] of Object.entries(values)) await engine.setConfig(k, v);
+ try { return await run(); } finally { await engine.executeRaw('DELETE FROM config WHERE key = ANY($1::text[])', [KEYS]); }
+};
+/** Recency boosts read the wall clock, so scores move between calls; every other byte must match. */
+const stable = (v: unknown) => JSON.stringify(v, (k, x) => (k === 'score' || k === 'recency_boost' ? undefined : x));
+const turns = (i: number) => Array.from({ length: 12 }, (_, t) => `**${t % 2 ? 'Assistant' : 'User'}:** Forge offsite planning, part ${i}, turn ${t}. The Forge offsite venue was booked and the venue changed once.`).join('\n\n');
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ sourceId = await newSource(engine);
+ for (let i = 0; i < 6; i++) await putPage(engine, sourceId, `conversations/chat-${i}`, page('conversation', `Forge planning chat ${i}`, turns(i), `date: 2025-07-0${i + 1}\n`));
+ await putPage(engine, sourceId, 'conversations/kestrel-call', page('conversation', 'Kestrel call', '**User:** We talked about the projector order.\n\n**Assistant:** Logged it.', 'date: 2025-05-03\n'));
+ await putPage(engine, sourceId, 'conversations/private-call', page('conversation', 'Private call', '**User:** Unrelated chatter.', 'date: 2025-05-04\nvisibility: private\n'));
+ const fact = (text: string, from: string | null, slug: string | null) => engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence, valid_from, source_markdown_slug)
+ VALUES ($1, 'forge', $2, 'event', 'conversation', 'world', 1, COALESCE($3::timestamptz, now()), $4)`, [sourceId, text, from, slug]);
+ await fact('The Forge offsite venue was booked in Santa Fe.', '2025-06-02T00:00:00Z', 'conversations/kestrel-call');
+ await fact('The Forge offsite venue changed to Missoula.', '2025-07-12T00:00:00Z', null);
+ await fact('The Forge offsite venue booking needs a deposit.', null, 'conversations/private-call');
+}, 120_000);
+afterAll(async () => { await engine?.disconnect(); }, 60_000);
+
+describe('every key unset or off', () => {
+ test('byte-identical to the build without the keys', async () => {
+ const calls = async () => [await query(PLAIN, { token_budget: 4000 }), await query(PLAIN), await query(PLAIN, { token_budget: 4000, return_unit: 'auto' })];
+ const unset = await calls();
+ const off = await withKeys({ [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'chunk', [EVIDENCE_TITLES_KEY]: 'false', [QUERY_FACTS_BLOCK_KEY]: 'false', [FACT_SOURCE_PAGES_KEY]: 'false' }, calls);
+ expect(stable(off)).toBe(stable(unset));
+ });
+});
+
+describe('search.query_budget_unit', () => {
+ test('unset: query token_budget keeps the legacy chunk trim (no delivered blocks)', async () => {
+ const rows = await query(PLAIN, { token_budget: 4000 });
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.some(r => r.delivered)).toBe(false);
+ });
+
+ test('auto: query token_budget is the delivery hard cap, conversations delivered whole within it', async () => {
+ const rows = await withKeys({ [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'auto' }, () => query(PLAIN, { token_budget: 4000 }));
+ const pages = rows.filter(r => r.delivered?.unit === 'page');
+ expect(pages.length).toBeGreaterThan(0);
+ expect(rows.reduce((n, r) => n + (r.delivered?.tokens ?? 0), 0)).toBeLessThanOrEqual(4000);
+ });
+
+ test('auto with the date header on: every delivered page block starts with its date line', async () => {
+ const rows = await withKeys({ [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'auto', [EVIDENCE_DATE_HEADER_KEY]: 'true' }, () => query(PLAIN, { token_budget: 4000 }));
+ const pages = rows.filter(r => r.delivered?.unit === 'page');
+ expect(pages.length).toBeGreaterThan(0);
+ for (const p of pages) expect(p.chunk_text.split('\n')[0]).toMatch(/^\[observed 2025-07-0\d\]$/);
+ });
+});
+
+describe('search.evidence_titles', () => {
+ test('with the date header on, a page block header line carries its title; facts keep their grammar', async () => {
+ const rows = await withKeys({ [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'auto', [EVIDENCE_DATE_HEADER_KEY]: 'true', [EVIDENCE_TITLES_KEY]: 'true' }, () => query(PLAIN, { token_budget: 4000 }));
+ const pages = rows.filter(r => r.delivered?.unit === 'page');
+ expect(pages.length).toBeGreaterThan(0);
+ for (const p of pages) expect(p.chunk_text.split('\n')[0]).toBe(`[observed ${p.slug.endsWith('kestrel-call') ? '2025-05-03' : `2025-07-0${Number(p.slug.slice(-1)) + 1}`}] ${p.title}`);
+ });
+
+ test('with the date header off, titles change nothing', async () => {
+ const base = await withKeys({ [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'auto' }, () => query(PLAIN, { token_budget: 4000 }));
+ const titled = await withKeys({ [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'auto', [EVIDENCE_TITLES_KEY]: 'true' }, () => query(PLAIN, { token_budget: 4000 }));
+ expect(stable(titled)).toBe(stable(base));
+ });
+
+ test('think renders a title attribute only when asked', () => {
+ const p = { slug: 'conversations/chat-0', title: 'Forge "planning" <chat>', chunk_text: 'body', page_id: 1, score: 1 } as unknown as SearchResult;
+ expect(renderPagesBlockDetailed([p], 600, 'forge', { verbatim: true }).text).not.toContain('title=');
+ expect(renderPagesBlockDetailed([p], 600, 'forge', { verbatim: true, titles: true }).text).toContain('title="Forge \'planning\' chat"');
+ });
+});
+
+describe('search.query_facts_block', () => {
+ test('on, no temporal cue, with a budget: dated question-ranked facts first, inside the block share', async () => {
+ const budget = 4000;
+ const rows = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: 'true' }, () => query(PLAIN, { token_budget: budget, limit: 10 }));
+ const facts = rows.filter(r => r.result_type === 'fact');
+ expect(facts.length).toBeGreaterThanOrEqual(2);
+ expect(facts.length).toBeLessThanOrEqual(MAX_FACTS_BLOCK_ROWS);
+ expect(rows.slice(0, facts.length).every(r => r.result_type === 'fact')).toBe(true);
+ expect(facts[0]!.chunk_text.split('\n')[0]).toBe('[observed unknown; valid 2025-06-02 to unknown]');
+ expect(facts.reduce((n, r) => n + resultTokens(r), 0)).toBeLessThanOrEqual(Math.floor(budget * QUERY_FACTS_BLOCK_SHARE));
+ });
+
+ test('on, under the delivery cap: facts are delivered as saved facts within the budget', async () => {
+ const rows = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: 'true', [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'auto' }, () => query(PLAIN, { token_budget: 4000, limit: 10 }));
+ const facts = rows.filter(r => r.result_type === 'fact');
+ expect(facts.length).toBeGreaterThanOrEqual(2);
+ for (const f of facts) expect(f.delivered?.reason).toBe('saved_fact');
+ expect(rows.reduce((n, r) => n + (r.delivered?.tokens ?? 0), 0)).toBeLessThanOrEqual(4000);
+ });
+
+ test('on without a budget (chunk unit): unchanged', async () => {
+ const base = await query(PLAIN, { return_unit: 'chunk' });
+ const on = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: 'true' }, () => query(PLAIN, { return_unit: 'chunk' }));
+ expect(stable(on)).toBe(stable(base));
+ });
+});
+
+describe('search.fact_source_pages', () => {
+ test('on: the conversation a matched fact came from joins after the top rows; the row count never grows', async () => {
+ const base = await query(PLAIN, { limit: 6, return_unit: 'chunk' });
+ expect(base.some(r => r.slug === 'conversations/kestrel-call')).toBe(false);
+ const rows = await withKeys({ [FACT_SOURCE_PAGES_KEY]: 'true' }, () => query(PLAIN, { limit: 6, return_unit: 'chunk' }));
+ const pages = rows.filter(r => r.result_type !== 'fact');
+ expect(pages.length).toBeLessThanOrEqual(base.filter(r => r.result_type !== 'fact').length);
+ const at = pages.findIndex(r => r.slug === 'conversations/kestrel-call');
+ expect(at).toBe(Math.min(FACT_SOURCE_PAGE_RANK, pages.length - 1));
+ expect(pages.filter(r => !base.some(b => b.page_id === r.page_id)).length).toBeLessThanOrEqual(MAX_FACT_SOURCE_PAGES);
+ });
+
+ test('a local caller may get a private source page; a remote caller never does', async () => {
+ const params = { query: 'Forge offsite venue booking deposit', expand: false, use_cache: false, limit: 6, return_unit: 'chunk' };
+ const local = await withKeys({ [FACT_SOURCE_PAGES_KEY]: 'true' }, () => query(params.query, params));
+ expect(local.some(r => r.slug === 'conversations/private-call')).toBe(true);
+ const auth = { token: 't', clientId: 'gbra205-probe', scopes: ['read'], sourceId, allowedSources: [sourceId] };
+ const remote = await withKeys({ [FACT_SOURCE_PAGES_KEY]: 'true' }, () => dispatchToolCall(engine, 'query', params,
+ { remote: true, transport: 'stdio', sourceId, auth, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} } }));
+ const text = remote.content.map(c => (c as { text?: string }).text ?? '').join('\n');
+ expect(text).toContain('Forge');
+ expect(text).not.toContain('private-call');
+ expect(text).not.toContain('Unrelated chatter');
+ });
+});