Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/mpw-integration
garrytan83e5788674fc
diff --cc docs/architecture/key-files/core-search-2.mdindex ddd281717e,2b8d31c9df..e70c1b5b57--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@@ -3,13 -3,7 +3,13 @@@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- - `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.-- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.++- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.++- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.+- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, read-policy filtered; 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 active facts only (not expired, not superseded, `valid_until` not passed, audit rows excluded) under recall's read policy (source scope; remote callers get world facts with private provenance filtered) 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) or a named entity, 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; shared with the facts arm's `matchQueryFacts`), scored cosine + term share + 0.1 when `valid_from` is more than a day from `created_at`, kept at cosine >= 0.5 or term share >= 0.34, 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/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/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) 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.diff --cc docs/evidence-delivery.mdindex e8085cf50a,23b40e5fc6..cd23b04f24--- a/docs/evidence-delivery.md+++ b/docs/evidence-delivery.md@@@ -82,12 -85,10 +90,15 @@@ Per-call params on `search`, `query`, `long sessions were still trimmed) and the other units use`search.return_budget_default` (default 6,000). Remote callers are clamped to`search.return_budget_max_remote` (default 32,000); the clamp is reported in- `delivery.budget_clamped` and `delivery.fallbacks`, never raised.+ `delivery.budget_clamped` and `delivery.fallbacks`, never raised per call.+ A trusted brain that needs more over stdio MCP (an eval cell's hermetic+ brain, for example) raises the ceiling once with+ `gbrain config set search.return_budget_max_remote 200000` and asserts that+ `delivery.budget_clamped` is absent; trusted local CLI calls are never+ clamped.+ - An explicit budget under `auto` (`return_unit: "auto"`, or `auto` from config+ on `search`) is a hard cap, packed by `search.auto_packing` (see+ [Explicit budgets](#explicit-budgets-the-cap)); it must be at least 32 tokens.- Legacy budget knobs keep their meaning: with `return_unit` omitted,`query`'s `token_budget` still prunes chunks (chunk mode), and `recall`'s`budget_tokens` / `budget_policy` still pack chunks (facts first), so any of@@@ -98,40 -99,9 +109,41 @@@ Think reads `think.return_unit` (defaulUnder `auto`, think renders conversation pages whole and keeps its usualexcerpts for every other page.+### Date headers++With `search.evidence_date_header` on (default off), every delivered block,+including `auto`'s unchanged chunks, starts with one fixed line, and+`delivery.date_header` is `true`:++```text+[observed 2026-03-05]+```++`observed` is when the page's text was written or said: its filename or slug+date, frontmatter `date`, `published` or a created key, in effective-date+precedence with `event_date` removed. An event date (when something happened)+and the row's own timestamps are never shown as observed; a page without an+observation date reads `[observed unknown]`. A date stored at midnight UTC+renders as written, any other instant in `brain.timezone`. The header line+and its newline are part of `chunk_text`: they count in `delivered.tokens`,+`tokens_delivered` and the budget, `match_spans` offsets include them, and- `evidenceFingerprint` hashes them. `recall` facts gain++`evidenceFingerprint` hashes them; under an explicit `auto` budget the cap pays for++them first and a cut keeps the header line whole. `recall` facts gain+`date_header: "[observed 2026-02-10; valid 2026-03-01 to unknown]"`. A fact's+`observed` date is the observation date of the page it came from+(`source_markdown_slug`, such as the conversation it was extracted from), and it+reads `unknown` for a fact kept only in its entity page's facts fence. `valid`+starts at the fact's `valid_from`: `remember` sets it from its `valid_from`+parameter (when the fact was said or became true). A `valid_from` that only+records the write time (within a minute of `created_at`) reads `unknown`, so a+header never presents when a fact was written as when it became true. An open+validity end reads `unknown`. The setting+applies to `search`, `query`, `recall`, `think` and `assemble_evidence`.+Config keys: `search.return_unit`, `search.return_window`,`search.return_budget_default`, `search.return_budget_conversation`,- `search.return_budget_max_remote`, `search.evidence_date_header`,-`search.return_budget_max_remote`, `search.auto_packing`, `think.return_unit`. Kill switch:++`search.return_budget_max_remote`, `search.evidence_date_header`, `search.auto_packing`,+`think.return_unit`. Kill switch:`gbrain config set search.return_unit chunk` and`gbrain config set think.return_unit chunk` (or pass `return_unit: "chunk"`per call).@@@ -233,7 -261,7 +303,8 @@@ Response meta (`_meta.retrieval.deliver"dropped_reasons": { "budget_floor": 1 },"fallbacks": ["budget_clamped"], // distinct non-fatal problem codes, never silent"budget_clamped": { "requested": 50000, "max": 32000 },- "date_header": true // only when search.evidence_date_header is on++ "date_header": true, // only when search.evidence_date_header is on+ "auto_packing": "cap_only" // explicit auto budgets only: the packing that ran}```@@@ -256,9 -284,12 +327,13 @@@ delivered text and each result gains `d| `snippet_cap` | An explicit `snippet_chars` cut a block. | Capped block, `truncated: true`. || `budget_clamped` | A remote budget above the max was clamped. | Clamped budget. || `tokenizer_heuristic` | cl100k unavailable; char/4 heuristic used. | Counts from the heuristic. |+| `date_header_unavailable` | Date headers are on but the page dates could not be read. | Every header reads `[observed unknown]`. || drop `not_readable` | The page is no longer readable by this caller (deleted, private, grant revoked, quarantined, archived source, source outside scope). | Result removed. Never falls back to cached text. |- | drop `budget_floor` | Not even the block's matching span fits the remaining budget. | Result removed (rank one is instead cut to fit). Under `auto` nothing is dropped for budget: the conversation keeps its ranked chunks. |+ | `snippet_marker_omitted` | Under an explicit `auto` budget, a row's allocation could not hold the snippet recovery marker. | Capped block without the marker, `truncated: true`. |+ | drop `budget_floor` | Not even the block's matching span fits the remaining budget. | Result removed (rank one is instead cut to fit). Under `auto` without an explicit budget nothing is dropped for budget: the conversation keeps its ranked chunks. |+ | drop `budget_note` | Explicit `auto` budget: a non-conversation chunk after rank one did not fit, or came after one that did not. | Result removed. |+ | drop `breadth_cap` | `breadth_capped`: the conversation is past the prefix whose target windows fit. | Result removed. |+ | drop `budget_recount` | Explicit `auto` budget: the final recount (after redaction and snippet markers) left no room for the row's title and a body. | Result removed. |## Errorsdiff --cc scripts/module-size-limits.tsvindex 265b20c5f2,ed3df6ed94..e6d7c6b821--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -35,8 -35,8 +35,8 @@@ src/core/link-extraction.ts 2358 ratchesrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1926 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-src/core/chunkers/code.ts 1588 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)-src/core/config.ts 1924 ratchet +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)+src/core/chunkers/code.ts 1592 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); +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 1930 ratchet +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 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)++src/core/config.ts 1931 ratchet +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 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)src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 675 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts)diff --cc src/core/config.tsindex f91c52e08c,f949e019af..47fa5839df--- a/src/core/config.ts+++ b/src/core/config.ts@@@ -1405,10 -1405,7 +1405,11 @@@ export const KNOWN_CONFIG_KEYS: readonl'search.return_budget_default','search.return_budget_conversation','search.return_budget_max_remote',+ 'search.auto_packing',+ 'search.evidence_date_header', // C1: one-line date header per delivered block (default off; search/evidence-date.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)'think.return_unit',// Models tier system (v0.31.12)'models.default',diff --cc src/core/ops/search.tsindex 7ede2a962d,ca2da3a35c..af973d186c--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@@ -34,7 -31,7 +34,7 @@@ import { redactRetrievalOutput } from 'import { projectRows, resultRowsFor } from '../search/lean-rows.ts';import { buildScoreDetails } from '../search/explain-formatter.ts';import { TargetTrace, diagnoseProbe, diagnoseTrace, probeTarget, type ExplainTargetDiagnosis } from '../search/explain-target.ts';- import { assembleEvidenceForHits, capDeliveredSnippets, deliverEvidence, effectivePlan, pagePlanHits, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';-import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, effectivePlan, resolveEvidencePlan, unsupportedDelivery, type DeliveryMeta, type DeliveryScope, type EvidencePlan, type FrozenHit, type ReturnUnit } from '../search/evidence-delivery.ts';++import { assembleEvidenceForHits, capDeliveredSnippets, capEvidenceToBudget, deliverEvidence, effectivePlan, pagePlanHits, resolveEvidencePlan, unsupportedDelivery, 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 } from '../search/safe-chunks.ts';@@@ -101,9 -98,11 +101,11 @@@ function searchOutput(ctx: OperationCon// otherwise the blocks are returned whole (their budget already bounds// them). The cap runs before the meta is emitted so it can report itself.const output = redactRetrievalOutput(results, { ...meta, delivery: evidence.delivery, ...shown });- const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : output.results;+ // An explicit budget's cap holds at this final boundary too (snippet+ // markers and redaction recounted); without one both are no-ops.+ const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : capEvidenceToBudget(output.results, output.meta.delivery);ctx.emitResponseMeta?.('retrieval', output.meta);- return projectRows(capped, rows);+ return projectRows(capped.map(factRowOutput), rows);}/** C1: the per-call row-shape escape hatch shared by `search` and `query` (`detail` is query's low/medium/high). */diff --cc src/core/search/evidence-delivery.tsindex d817a81703,4c0d02609e..742a6e2d9b--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@@ -34,7 -34,10 +34,11 @@@ import { sanitizeRemoteBody } from '../import { credentialSafeProjection } from '../credential-projection.ts';import { stripChunkHeader } from '../chunkers/code.ts';import { OperationError } from '../ops/contract.ts';+import { evidenceDateHeaderEnabled, factDateHeader, loadPageDateHeaders, pageDateHeader } from './evidence-date.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 const RETURN_UNITS = ['chunk', 'window', 'section', 'page', 'auto'] as const;export type ReturnUnit = typeof RETURN_UNITS[number];@@@ -97,8 -105,8 +106,10 @@@ export interface DeliveryMetadropped_reasons: Record<string, number>;fallbacks: string[];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 only when an explicit budget engaged the cap: the packing that ran. */+ auto_packing?: AutoPacking;}export type DeliveredSearchResult = SearchResult & { delivered: DeliveredEvidence };@@@ -110,11 -118,18 +121,20 @@@ export interface EvidencePlanbudgetTokens: number;/** return_unit came from the call, not config (snippet precedence). */explicitUnit: boolean;+ /** The caller passed the budget; a config or default budget never engages the cap. */+ budgetExplicit: boolean;+ /** search.auto_packing (or the library override), resolved once; allocation never rereads config. */+ packing: AutoPacking;budgetClamped?: { requested: number; max: number };+ /** `search.evidence_date_header` is on: each block starts with its date header line. */+ dateHeader?: true;}+ /** The cap runs only under `auto`, with a budget the caller passed and a packing other than `off`. */+ export function capEngaged(plan: EvidencePlan): boolean {+ return plan.unit === 'auto' && plan.budgetExplicit && plan.packing !== 'off';+ }+export interface DeliveryScope extends PageReadScope {detail?: 'low' | 'medium' | 'high';}@@@ -230,8 -262,9 +267,10 @@@ export async function resolveEvidencePlwindow,budgetTokens: budget,explicitUnit: explicit !== undefined,+ budgetExplicit,+ packing,...(budgetClamped ? { budgetClamped } : {}),+ ...(await evidenceDateHeaderEnabled(engine) ? { dateHeader: true as const } : {}),};}@@@ -264,24 -297,12 +303,25 @@@ export function conversationSignal(hit/*** The plan to run for these hits: an implied or config-level `auto` with no* conversation hit is the chunk path (null), so responses without- * conversations stay byte-identical. An explicit `auto` always runs and- * reports its per-result decision.+ * conversations stay byte-identical. An explicit `auto`, or an `auto` under+ * an explicit budget the cap enforces, always runs and reports its+ * per-result decision.*/+/**+ * A page-unit plan fills a token budget, so its hits are not cut for+ * precision first: autocut stays off unless the caller asks for it, and a+ * budget larger than the default row count can fill raises the row count (one+ * row per ~250 tokens, at most 100). Otherwise the page lane stopped at the+ * default rows (often ~10 after autocut) with half its budget unused.+ */+export function pagePlanHits(plan: EvidencePlan | null): { limit?: number; autocut?: false } {+ if (!plan || plan.unit !== 'page' || !(plan.budgetTokens > 0)) return {};+ const rows = Math.min(100, Math.ceil(plan.budgetTokens / 250));+ return { autocut: false, ...(rows > 25 ? { limit: rows } : {}) };+}+export function effectivePlan(plan: EvidencePlan | null, hits: SearchResult[]): EvidencePlan | null {- if (!plan || plan.unit !== 'auto' || plan.explicitUnit) return plan;+ if (!plan || plan.unit !== 'auto' || plan.explicitUnit || capEngaged(plan)) return plan;return hits.some(h => conversationSignal(h) !== null) ? plan : null;}@@@ -507,9 -525,11 +547,11 @@@ interface Block/** Index of the block's best hit in the ranked input. */rank: number;reason?: AutoReason;+ /** The cap cut this block: its text ends with EVIDENCE_CUT_MARKER. */+ capMarker?: boolean;}- type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason' | 'header' | 'headerTok'>;-type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason' | 'capMarker'>;++type PlannedBlock = Omit<Block, 'titleTok' | 'title' | 'rank' | 'reason' | 'capMarker' | 'header' | 'headerTok'>;/*** The hit's text as it appears in the page: a fenced_code chunk carries the@@@ -695,6 -715,62 +737,65 @@@ function enrichmentOrder(b: Block): num});}+ /** Rank one alone exceeds the budget: cut its title to `titleMax`, then keep core pieces (slicing the first) to fit. */+ function cutToFit(b: Block, remaining: number, titleMax: number, tokenizer: 'cl100k' | 'heuristic'): number {+ const core = b.anchors[0]?.pieces ?? [];++ // The date header line is kept whole and paid for first.++ remaining = Math.max(0, remaining - b.headerTok);++ titleMax = Math.max(0, titleMax - b.headerTok);+ if (b.titleTok > titleMax) {+ b.title = sliceToTokenCount(b.title, titleMax, tokenizer);+ b.titleTok = countEvidenceTokens(b.title, tokenizer);+ }+ remaining -= b.titleTok;+ let chars = 0;+ for (const i of core) {+ const t = tok(b, i, tokenizer);+ const len = b.doc.pieces[i].text.length;+ if (t <= remaining && chars + len <= EVIDENCE_BLOCK_CHAR_CAP) {+ b.selected.add(i);+ remaining -= t;+ chars += len;+ continue;+ }+ if (b.selected.size === 0) {+ const p = b.doc.pieces[i];+ p.text = sliceToTokenCount(p.text.slice(0, EVIDENCE_BLOCK_CHAR_CAP), remaining, tokenizer);+ p.end = p.start + p.text.length;+ p.tok = pieceTokens(p.text, tokenizer);+ b.selected.add(i);+ remaining -= p.tok;+ }+ break;+ }+ b.cut = true;+ return remaining;+ }++ /** Grow a kept block in enrichment order until the next piece does not fit; returns what is left. */+ function enrichBlock(b: Block, remaining: number, tokenizer: 'cl100k' | 'heuristic', omitTok: number): number {+ let chars = [...b.selected].reduce((n, i) => n + b.doc.pieces[i].text.length, 0);+ for (const i of enrichmentOrder(b)) {+ if (b.selected.has(i)) continue;+ const adj = adjacent(b, i);+ const cost = tok(b, i, tokenizer) + (adj ? 0 : omitTok);+ const len = b.doc.pieces[i].text.length + (adj ? 0 : EVIDENCE_OMISSION.length);+ if (cost > remaining || chars + len > EVIDENCE_BLOCK_CHAR_CAP) break;+ b.selected.add(i);+ remaining -= cost;+ chars += len;+ }+ return remaining;+ }++ function floorOf(b: Block, tokenizer: 'cl100k' | 'heuristic'): { tokens: number; chars: number } {+ const core = b.anchors[0]?.pieces ?? [];+ return {- tokens: b.titleTok + core.reduce((n, i) => n + tok(b, i, tokenizer), 0),++ tokens: b.titleTok + b.headerTok + core.reduce((n, i) => n + tok(b, i, tokenizer), 0),+ chars: core.reduce((n, i) => n + b.doc.pieces[i].text.length, 0),+ };+ }+/*** Reserve each block's floor in rank order, then enrich. `spill` (auto) takes* a block whose floor does not fit instead of dropping or cutting it.@@@ -766,6 -806,138 +831,139 @@@ function allocate(blocks: Block[], budgreturn kept;}+ /** A non-conversation hit under `auto`: its ranked chunk, or a cut prefix of it under the cap. */-interface ChunkItem { rank: number; hit: SearchResult; reason: AutoReason; title: string; text: string; cut: boolean }++/** `text` starts with the hit's date header line (`header`, '' when off); a cut keeps the header. */++interface ChunkItem { rank: number; hit: SearchResult; reason: AutoReason; title: string; text: string; cut: boolean; header: string }++ /** A selection as emit writes it: the pieces plus one omission line per gap. */+ function selectionCost(b: Block, sel: Set<number>, tokenizer: 'cl100k' | 'heuristic', omitTok: number): { tokens: number; chars: number } {+ const order = [...sel].sort((x, y) => x - y);+ let tokens = 0;+ let chars = 0;+ order.forEach((i, k) => {+ const gap = k > 0 && order[k - 1] !== i - 1;+ tokens += tok(b, i, tokenizer) + (gap ? omitTok : 0);+ chars += b.doc.pieces[i].text.length + (gap ? EVIDENCE_OMISSION.length : 0);+ });+ return { tokens, chars };+ }++ /**+ * The cap (explicit budget under `auto`, docs/evidence-delivery.md+ * "Explicit budgets"): global rank one first, cut to fit if it alone exceeds+ * the budget; then the rank-order prefix of the other non-conversation chunks+ * that fits; then conversations by the plan's packing. Nothing is spilled+ * outside the budget; what does not fit is counted in `dropped`.+ */+ function allocateCapped(blocks: Block[], chunks: ChunkItem[], plan: EvidencePlan, tokenizer: 'cl100k' | 'heuristic', dropped: Record<string, number>): { kept: Block[]; chunks: ChunkItem[] } {+ const omitTok = pieceTokens(EVIDENCE_OMISSION, tokenizer);+ const cutTok = countEvidenceTokens(EVIDENCE_CUT_MARKER, tokenizer);+ const drop = (reason: string) => { dropped[reason] = (dropped[reason] ?? 0) + 1; };+ const chunkCost = (c: ChunkItem) => countEvidenceTokens(c.title, tokenizer) + countEvidenceTokens(c.text, tokenizer);+ let remaining = plan.budgetTokens;+ const keptChunks: ChunkItem[] = [];+ const kept: Block[] = [];+ let lead: Block | null = null;++ const firstChunk = chunks[0];+ const firstBlock = blocks[0];+ let rest = chunks;+ let others = blocks;+ if (firstChunk && (!firstBlock || firstChunk.rank < firstBlock.rank)) {+ rest = chunks.slice(1);+ const cost = chunkCost(firstChunk);+ if (cost <= remaining) remaining -= cost;+ else {+ const room = remaining - cutTok;+ let title = firstChunk.title;+ if (countEvidenceTokens(title, tokenizer) > room - CUT_BODY_MIN) title = sliceToTokenCount(title, Math.max(0, room - CUT_BODY_MIN), tokenizer);+ const bodyRoom = room - countEvidenceTokens(title, tokenizer);+ const source = firstChunk.text.slice(0, EVIDENCE_BLOCK_CHAR_CAP);+ let end = 0;+ let used = 0;+ for (const piece of splitPieces(source)) {+ const t = pieceTokens(source.slice(piece.start, piece.end), tokenizer);+ if (used + t > bodyRoom) break;+ used += t;+ end = piece.end;+ }+ const body = end > 0 ? source.slice(0, end).replace(/\s+$/, '') : sliceToTokenCount(source, Math.max(0, bodyRoom), tokenizer);+ Object.assign(firstChunk, { title, text: body + EVIDENCE_CUT_MARKER, cut: true });+ remaining -= chunkCost(firstChunk);+ }+ keptChunks.push(firstChunk);+ } else if (firstBlock) {+ others = blocks.slice(1);+ const floor = floorOf(firstBlock, tokenizer);+ if (floor.tokens <= remaining && floor.chars <= EVIDENCE_BLOCK_CHAR_CAP) {+ for (const i of firstBlock.anchors[0]?.pieces ?? []) firstBlock.selected.add(i);+ remaining -= floor.tokens;+ lead = firstBlock;+ } else {+ remaining = cutToFit(firstBlock, remaining - cutTok, Math.max(0, remaining - cutTok - CUT_BODY_MIN), tokenizer);+ firstBlock.capMarker = true;+ }+ kept.push(firstBlock);+ }++ let stopped = false;+ for (const c of rest) {+ const cost = chunkCost(c);+ if (!stopped && cost <= remaining) { remaining -= cost; keptChunks.push(c); continue; }+ stopped = true;+ drop('budget_note');+ }++ const reserveFloor = (b: Block): boolean => {+ const floor = floorOf(b, tokenizer);+ if (floor.tokens > remaining || floor.chars > EVIDENCE_BLOCK_CHAR_CAP) return false;+ for (const i of b.anchors[0]?.pieces ?? []) b.selected.add(i);+ remaining -= floor.tokens;+ return true;+ };++ if (plan.packing === 'depth_first') {+ if (lead) remaining = enrichBlock(lead, remaining, tokenizer, omitTok);+ for (const b of others) {+ if (!reserveFloor(b)) { drop('budget_floor'); continue; }+ kept.push(b);+ remaining = enrichBlock(b, remaining, tokenizer, omitTok);+ }+ } else if (plan.packing === 'breadth_capped') {+ // k: the longest rank-order prefix of conversations whose title, floor+ // and target window (the window unit's candidates at return_window) fit.+ let capped = false;+ for (const b of lead ? [lead, ...others] : others) {+ if (capped) { drop('breadth_cap'); continue; }+ const window = new Set(windowCandidates(b.doc, b.anchors, plan.window));+ const target = new Set(b.anchors[0]?.pieces ?? []);+ for (const i of enrichmentOrder(b)) {+ if (!window.has(i)) continue;+ target.add(i);+ if (selectionCost(b, target, tokenizer, omitTok).chars > EVIDENCE_BLOCK_CHAR_CAP) { target.delete(i); break; }+ }+ const sel = selectionCost(b, target, tokenizer, omitTok);- const cost = b.titleTok + sel.tokens - (b === lead ? floorOf(b, tokenizer).tokens : 0);++ const cost = b.titleTok + b.headerTok + sel.tokens - (b === lead ? floorOf(b, tokenizer).tokens : 0);+ if (cost <= remaining && sel.chars <= EVIDENCE_BLOCK_CHAR_CAP) {+ for (const i of target) b.selected.add(i);+ remaining -= cost;+ if (b !== lead) kept.push(b);+ continue;+ }+ capped = true;+ if (b !== lead) drop('breadth_cap');+ }+ for (const b of kept) if (!b.cut) remaining = enrichBlock(b, remaining, tokenizer, omitTok);+ } else {+ for (const b of others) {+ if (reserveFloor(b)) kept.push(b);+ else drop('budget_floor');+ }+ for (const b of kept) if (!b.cut) remaining = enrichBlock(b, remaining, tokenizer, omitTok);+ }+ return { kept, chunks: keptChunks };+ }+function emit(b: Block, tokenizer: 'cl100k' | 'heuristic'): { text: string; spans: MatchSpan[]; unmapped: number[]; tokens: number } {const order = [...b.selected].sort((x, y) => x - y);const emitStart = new Map<number, number>();@@@ -927,39 -1083,101 +1125,107 @@@ export async function deliverEvidence}if (b.fallbackReason) fallbacks.add(b.fallbackReason);const title = b.hit.title ?? '';- planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer), rank: g.rank, ...(g.reason ? { reason: g.reason } : {}) });+ const header = headerFor(b.hit);+ planned.push({ ...b, title, titleTok: countEvidenceTokens(title, tokenizer), header, headerTok: countEvidenceTokens(header, tokenizer), rank: g.rank, ...(g.reason ? { reason: g.reason } : {}) });}- // Unchanged chunks are paid for first; conversations share the rest, and one- // whose matching span no longer fits keeps its ranked chunks instead.- const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(headerFor(p.hit) + (p.hit.chunk_text ?? ''), tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);- const kept = allocate(planned, Math.max(0, plan.budgetTokens - reserved), tokenizer, dropped, auto- ? b => { for (const h of b.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: 'conversation_over_budget' }); }- : undefined);+ const capped = capEngaged(plan);+ let kept: Block[];+ let chunkItems: ChunkItem[] = [];+ if (capped) {+ ({ kept, chunks: chunkItems } = allocateCapped(planned,- passthrough.map(p => ({ ...p, title: p.hit.title ?? '', text: p.hit.chunk_text ?? '', cut: false })), plan, tokenizer, dropped));++ passthrough.map(p => chunkItem(p, headerFor(p.hit))), plan, tokenizer, dropped));+ } else {+ // Unchanged chunks are paid for first; conversations share the rest, and one+ // whose matching span no longer fits keeps its ranked chunks instead.- const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(p.hit.chunk_text ?? '', tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);++ const reserved = passthrough.reduce((n, p) => n + countEvidenceTokens(headerFor(p.hit) + (p.hit.chunk_text ?? ''), tokenizer) + countEvidenceTokens(p.hit.title ?? '', tokenizer), 0);+ kept = allocate(planned, Math.max(0, plan.budgetTokens - reserved), tokenizer, dropped, auto+ ? b => { for (const h of b.hits) passthrough.push({ rank: hits.indexOf(h), hit: h, reason: 'conversation_over_budget' }); }+ : undefined);+ }let results: DeliveredSearchResult[] = kept.map(b => {const out = emit(b, tokenizer);- const text = b.capMarker ? out.text + EVIDENCE_CUT_MARKER : out.text;++ const text = b.header + (b.capMarker ? out.text + EVIDENCE_CUT_MARKER : out.text);const truncated = b.cut || b.selected.size < b.candidates.length;const delivered: DeliveredEvidence = {unit: b.unit,chunk_ids: b.hits.map(h => h.chunk_id),- match_spans: out.spans,- tokens: b.capMarker ? countEvidenceTokens(text, tokenizer) : out.tokens,+ match_spans: out.spans.map(sp => ({ ...sp, start: sp.start + b.header.length, end: sp.end + b.header.length })),- tokens: out.tokens + b.headerTok,++ tokens: b.capMarker ? countEvidenceTokens(text, tokenizer) : out.tokens + b.headerTok,truncated,...(b.revision ? { revision: b.revision } : {}),...(out.unmapped.length > 0 ? { unmapped_chunk_ids: out.unmapped } : {}),...(b.fallbackReason && b.unit === 'chunk' ? { fallback_reason: b.fallbackReason } : {}),...(b.reason ? { reason: b.reason } : {}),};- return { ...b.hit, title: b.title, chunk_text: b.header + out.text, delivered };+ return { ...b.hit, title: b.title, chunk_text: text, delivered };});- // Budget after redaction: blocks pass through the same secret redaction as- // every search response before spans and tokens are final. A block the- // redactor changed loses its spans (explicit unmapped state) and is- // re-counted, never allowed to grow past its allocation.+ // Under the cap the kept chunks join before redaction, so every evidence+ // field is redacted and recounted inside the budget.+ if (capped) {+ const ranked = results.map((r, i) => ({ rank: kept[i].rank, r }));+ for (const c of chunkItems) ranked.push({ rank: c.rank, r: chunkResult(c, tokenizer) });+ results = ranked.sort((a, b) => a.rank - b.rank).map(x => x.r);+ }+ results = redactDelivered(results, tokenizer, fallbacks);++ if (!capped && passthrough.length > 0) {+ const ranked = results.map((r, i) => ({ rank: kept[i].rank, r }));- for (const p of passthrough) ranked.push({ rank: p.rank, r: chunkResult({ ...p, title: p.hit.title ?? '', text: p.hit.chunk_text ?? '', cut: false }, tokenizer) });++ for (const p of passthrough) ranked.push({ rank: p.rank, r: chunkResult(chunkItem(p, headerFor(p.hit)), tokenizer) });+ results = ranked.sort((a, b) => a.rank - b.rank).map(x => x.r);+ }++ const tokensDelivered = results.reduce((n, r) => n + r.delivered.tokens, 0);+ const budgetUsed = tokensDelivered + results.reduce((n, r) => n + countEvidenceTokens(r.title ?? '', tokenizer), 0);+ const droppedTotal = Object.values(dropped).reduce((n, v) => n + v, 0);+ const delivery: DeliveryMeta = {+ requested_unit: plan.requestedUnit,+ applied_unit: fetchFailure ? 'chunk' : plan.unit,+ return_window: plan.window,+ budget_tokens: plan.budgetTokens,+ budget_used: budgetUsed,+ tokens_delivered: tokensDelivered,+ tokenizer,+ coordinates: 'utf16',+ blocks: results.length,+ dropped: droppedTotal,+ dropped_reasons: dropped,+ fallbacks: [...fallbacks].sort(),+ ...(plan.budgetClamped ? { budget_clamped: plan.budgetClamped } : {}),+ ...(capped ? { auto_packing: plan.packing } : {}),++ ...(plan.dateHeader ? { date_header: true as const } : {}),+ };+ return { results: capped ? capEvidenceToBudget(results, delivery) : results, delivery };+ }+-/** A non-conversation hit's delivered row: the ranked chunk unchanged, or the cap's cut prefix of it. */++function chunkItem(p: { rank: number; hit: SearchResult; reason: AutoReason }, header: string): ChunkItem {++ return { ...p, title: p.hit.title ?? '', text: header + (p.hit.chunk_text ?? ''), cut: false, header };++}++++/** A non-conversation hit's delivered row: its date header and the ranked chunk unchanged, or the cap's cut prefix of them. */+ function chunkResult(c: ChunkItem, tokenizer: 'cl100k' | 'heuristic'): DeliveredSearchResult {- const text = c.cut ? c.text : c.hit.chunk_text ?? '';++ const text = c.text;+ const matched = c.cut ? text.length - EVIDENCE_CUT_MARKER.length : text.length;- return { ...c.hit, ...(c.cut ? { title: c.title, chunk_text: text } : {}), delivered: {++ return { ...c.hit, ...(c.cut ? { title: c.title } : {}), ...(c.cut || c.header ? { chunk_text: text } : {}), delivered: {+ unit: 'chunk',+ chunk_ids: [c.hit.chunk_id],- match_spans: matched > 0 ? [{ chunk_id: c.hit.chunk_id, start: 0, end: matched }] : [],++ match_spans: matched > c.header.length ? [{ chunk_id: c.hit.chunk_id, start: c.header.length, end: matched }] : [],+ tokens: countEvidenceTokens(text, tokenizer),+ truncated: c.cut,+ reason: c.reason,+ } };+ }++ /**+ * Budget after redaction: blocks pass through the same secret redaction as+ * every search response before spans and tokens are final. A block the+ * redactor changed loses its spans (explicit unmapped state) and is+ * re-counted, never allowed to grow past its allocation.+ */+ function redactDelivered(results: DeliveredSearchResult[], tokenizer: 'cl100k' | 'heuristic', fallbacks: Set<string>): DeliveredSearchResult[] {const redacted = redactRetrievalOutput(results, {}).results;- results = results.map((r, i) => {+ return results.map((r, i) => {const rr = redacted[i];if (rr.chunk_text === r.chunk_text && rr.title === r.title) return r;fallbacks.add('redaction_unmapped');@@@ -1038,10 -1266,24 +1314,24 @@@ export function capDeliveredSnippets<Tconst out = results.map(r => {if (typeof r.chunk_text !== 'string' || r.chunk_text.length <= cap) return r;any = true;- const text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap, r.follow_up);+ let keep = cap;- let text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap);++ let text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap, r.follow_up);+ if (delivery.auto_packing) {+ // Under the cap the marker is paid from the row's own allocation: a+ // capped row never grows past what it held before the snippet cap.+ const allowed = countEvidenceTokens(r.chunk_text, tokenizer);+ if (countEvidenceTokens(text, tokenizer) > allowed) {- const markerTok = countEvidenceTokens(buildSnippetMarker(r.slug, r.chunk_text.length), tokenizer);++ const markerTok = countEvidenceTokens(buildSnippetMarker(r.slug, r.chunk_text.length, r.follow_up), tokenizer);+ const withMarker = allowed - markerTok >= 1;+ const body = sliceToTokenCount(r.chunk_text.slice(0, cap), withMarker ? allowed - markerTok : allowed, tokenizer);+ keep = body.length;- text = withMarker ? body + buildSnippetMarker(r.slug, r.chunk_text.length - keep) : body;++ text = withMarker ? body + buildSnippetMarker(r.slug, r.chunk_text.length - keep, r.follow_up) : body;+ if (!withMarker) markerOmitted = true;+ }+ }if (!r.delivered) return { ...r, chunk_text: text };- const spans = r.delivered.match_spans.filter(s => s.start < cap).map(s => ({ ...s, end: Math.min(s.end, cap) }));- const lost = r.delivered.match_spans.filter(s => s.start >= cap).map(s => s.chunk_id);+ const spans = r.delivered.match_spans.filter(s => s.start < keep).map(s => ({ ...s, end: Math.min(s.end, keep) }));+ const lost = r.delivered.match_spans.filter(s => s.start >= keep).map(s => s.chunk_id);const unmapped = [...new Set([...(r.delivered.unmapped_chunk_ids ?? []), ...lost.filter(id => !spans.some(s => s.chunk_id === id))])];return {...r,diff --cc test/config-search-registry.test.tsindex fb562a9b8b,4c70347837..0833666716--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@@ -42,10 -42,7 +42,11 @@@ const DIRECTLY_READ_SINGLETONS ='search.return_budget_default','search.return_budget_conversation','search.return_budget_max_remote',+ 'search.auto_packing', // search/evidence-delivery.ts (explicit-budget cap)+ 'search.evidence_date_header', // search/evidence-delivery.ts (C1)+ '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)];describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {diff --cc test/evidence-date-header.test.tsindex dab7ae78e1,0000000000..b9d25783edmode 100644,000000..100644--- a/test/evidence-date-header.test.ts+++ b/test/evidence-date-header.test.ts@@@ -1,208 -1,0 +1,224 @@@+/**+ * C1 — dated evidence blocks (`search.evidence_date_header`): the fixed+ * one-line header grammar, the observation-date rule (never an event date or+ * a row timestamp), budget accounting for the header, span offsets, the+ * default-off byte identity, recall fact validity windows, and the+ * configurable remote budget clamp the eval relies on.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import type { SearchResult } from '../src/core/types.ts';- import { countEvidenceTokens, deliverEvidence, type EvidencePlan } from '../src/core/search/evidence-delivery.ts';++import { countEvidenceTokens, DEFAULT_AUTO_PACKING, deliverEvidence, type EvidencePlan } from '../src/core/search/evidence-delivery.ts';+import {+ EVIDENCE_DATE_HEADER_KEY, factDateHeader, pageDateHeader, pageObservationDate,+} from '../src/core/search/evidence-date.ts';+import { formatBrainDay } from '../src/core/effective-date.ts';++const HEADER_LINE = /^\[observed (\d{4}-\d{2}-\d{2}|unknown)\]\n/;++describe('header grammar and dates', () => {+ test('page and fact headers are fixed one-line strings; unknown dates read "unknown"', () => {+ expect(pageDateHeader('2026-03-05')).toBe('[observed 2026-03-05]');+ expect(pageDateHeader(null)).toBe('[observed unknown]');+ expect(factDateHeader({ valid_from: new Date('2026-03-01T00:00:00Z'), valid_until: null })).toBe('[observed unknown; valid 2026-03-01 to unknown]');+ expect(factDateHeader({ valid_from: null, valid_until: '2026-04-01T00:00:00.000Z' })).toBe('[observed unknown; valid unknown to 2026-04-01]');+ for (const h of [pageDateHeader(null), factDateHeader({})]) expect(h).not.toContain('\n');+ // A valid_from that only records the write time is not a known start of validity.+ expect(factDateHeader({ valid_from: '2026-10-05T12:00:00.000Z', valid_until: null, created_at: '2026-10-05T12:00:00.400Z' })).toBe('[observed unknown; valid unknown to unknown]');+ expect(factDateHeader({ valid_from: '2026-03-01T00:00:00.000Z', valid_until: null, created_at: '2026-10-05T12:00:00.000Z' }, null, '2026-02-10')).toBe('[observed 2026-02-10; valid 2026-03-01 to unknown]');+ });++ test('formatBrainDay: midnight UTC renders as written, other instants in brain.timezone', () => {+ expect(formatBrainDay(new Date('2026-03-05T00:00:00Z'), 'America/Los_Angeles')).toBe('2026-03-05');+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), 'America/Los_Angeles')).toBe('2026-03-04');+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), null)).toBe('2026-03-05');+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), 'Not/AZone')).toBe('2026-03-05');+ expect(formatBrainDay(null)).toBeNull();+ expect(formatBrainDay('garbage')).toBeNull();+ });++ test('observation date: filename, date, published, created keys; never event_date or row times', () => {+ const day = (d: Date | null) => d?.toISOString().slice(0, 10) ?? null;+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { date: '2026-03-05' } }))).toBe('2026-03-05');+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { event_date: '2024-01-01', date: '2026-03-05' } }))).toBe('2026-03-05');+ expect(pageObservationDate({ slug: 'notes/x', frontmatter: { event_date: '2024-01-01' } })).toBeNull();+ expect(day(pageObservationDate({ slug: 'chat/2026-02-10-session', frontmatter: {} }))).toBe('2026-02-10');+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { created: '2025-12-31' } }))).toBe('2025-12-31');+ expect(pageObservationDate({ slug: 'notes/undated', frontmatter: {} })).toBeNull();+ });+});++describe('deliverEvidence with the header on', () => {+ const body = Array.from({ length: 30 }, (_, i) => `**${i % 2 ? 'assistant' : 'user'}:** turn ${i} about the renewal and the roadmap.`).join('\n\n');+ const chunks = [body.slice(0, body.length / 2).trim(), body.slice(body.length / 2).trim()];+ function stub(frontmatter: Record<string, unknown>) {+ return {+ async getConfig(key: string) { return key === 'brain.timezone' ? 'UTC' : null; },+ async executeRaw() { return [{ id: 1, slug: 'chat/s', frontmatter, import_filename: null }]; },+ async getChunkWindows() {+ return [{ page_id: 1, slug: 'chat/s', source_id: 'default', type: 'note', revision: 'r1', sealed: true, max_chunk_index: 1, row_limited: false,+ compiled_truth: body, timeline: '', chunks: chunks.map((t, i) => ({ id: 1000 + i, chunk_index: i, chunk_text: t, chunk_source: 'compiled_truth' })) }];+ },+ } as never;+ }+ const hit: SearchResult = { slug: 'chat/s', page_id: 1, title: 'S', type: 'note', chunk_text: chunks[1], chunk_source: 'compiled_truth', chunk_id: 1001, chunk_index: 1, score: 1, stale: false, source_id: 'default' };- const plan = (budget: number, dateHeader: boolean): EvidencePlan => ({ requestedUnit: 'page', unit: 'page', window: 1, budgetTokens: budget, explicitUnit: true, ...(dateHeader ? { dateHeader: true as const } : {}) });++ const plan = (budget: number, dateHeader: boolean): EvidencePlan => ({ requestedUnit: 'page', unit: 'page', window: 1, budgetTokens: budget, explicitUnit: true,++ budgetExplicit: false, packing: DEFAULT_AUTO_PACKING, ...(dateHeader ? { dateHeader: true as const } : {}) });++ test('every block starts with its header; tokens and spans account for it', async () => {+ const off = await deliverEvidence(stub({ date: '2026-03-05' }), [hit], plan(32000, false), {});+ const on = await deliverEvidence(stub({ date: '2026-03-05' }), [hit], plan(32000, true), {});+ const header = '[observed 2026-03-05]\n';+ expect(on.results[0].chunk_text).toBe(header + off.results[0].chunk_text);+ expect(on.results[0].delivered.tokens).toBe(off.results[0].delivered.tokens + countEvidenceTokens(header));+ expect(on.delivery.tokens_delivered).toBe(countEvidenceTokens(on.results[0].chunk_text));+ expect(on.delivery.date_header).toBe(true);+ expect(off.delivery.date_header).toBeUndefined();+ const spanOn = on.results[0].delivered.match_spans[0];+ const spanOff = off.results[0].delivered.match_spans[0];+ expect(on.results[0].chunk_text.slice(spanOn.start, spanOn.end)).toBe(off.results[0].chunk_text.slice(spanOff.start, spanOff.end));+ });++ test('the budget is honoured with the header counted', async () => {+ for (const budget of [12, 40, 120, 400]) {+ const on = await deliverEvidence(stub({}), [hit], plan(budget, true), {});+ expect(on.results[0].chunk_text).toMatch(HEADER_LINE);+ expect(on.results[0].chunk_text.startsWith('[observed unknown]\n')).toBe(true);+ expect(on.delivery.budget_used).toBeLessThanOrEqual(budget);+ }+ });+++ test('under the explicit-budget cap the header is paid first and kept whole, and the budget holds', async () => {++ const note: SearchResult = { ...hit, slug: 'notes/s', type: 'note', chunk_text: 'A plain note chunk about the walrus pricing plan. '.repeat(12) };++ const capped = (budget: number): EvidencePlan => ({ requestedUnit: 'auto', unit: 'auto', window: 1, budgetTokens: budget, explicitUnit: true,++ budgetExplicit: true, packing: DEFAULT_AUTO_PACKING, dateHeader: true });++ for (const budget of [40, 120, 4000]) {++ const on = await deliverEvidence(stub({}), [note], capped(budget), {});++ const row = on.results[0];++ expect(on.delivery.auto_packing).toBe(DEFAULT_AUTO_PACKING);++ expect(on.delivery.date_header).toBe(true);++ expect(row.chunk_text.startsWith('[observed unknown]\n')).toBe(true);++ expect(row.delivered.match_spans.every(s => s.start >= '[observed unknown]\n'.length)).toBe(true);++ expect(on.delivery.budget_used).toBeLessThanOrEqual(budget);++ }++ });+++ test('a failed date read renders unknown and says so', async () => {+ const engine = Object.assign(stub({}) as object, { async executeRaw() { throw new Error('boom'); } }) as never;+ const on = await deliverEvidence(engine, [hit], plan(32000, true), {});+ expect(on.results[0].chunk_text.startsWith('[observed unknown]\n')).toBe(true);+ expect(on.delivery.fallbacks).toContain('date_header_unavailable');+ });+});++describe('ops on PGLite', () => {+ let engine: PGLiteEngine;+ let lastMeta: Record<string, any> | null = null;+ const op = (name: string) => operations.find(o => o.name === name)!;+ const ctxOf = (overrides: Partial<OperationContext> = {}): OperationContext => ({+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') lastMeta = value as Record<string, any>; },+ ...overrides,+ }) as OperationContext;+ const SESSION = Array.from({ length: 12 }, (_, i) => `**user:** question ${i} about the walrus launch\n\n**assistant:** reply ${i} on walrus timelines`).join('\n\n');+ const NOTE = '## Walrus\n\nThe walrus pricing note describes the plan.';++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const pages: Array<[string, string, Record<string, unknown>]> = [+ ['chat/2026-02-10-walrus', SESSION, {}],+ ['notes/walrus-dated', NOTE, { date: '2026-03-05', event_date: '2020-01-01' }],+ ['notes/walrus-undated', NOTE.replace('pricing', 'support'), {}],+ ];+ for (const [slug, body, frontmatter] of pages) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '', frontmatter });+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));+ }+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await engine.insertFact({ fact: 'Walrus launch is in March', kind: 'fact', entity_slug: 'notes/walrus-dated', source: 'test', visibility: 'world',+ valid_from: new Date('2026-03-01T00:00:00Z') }, { source_id: 'default' });+ }, 240_000);++ afterAll(async () => { await engine.disconnect(); }, 240_000);++ test('default off: no header, no meta key, recall facts unchanged', async () => {+ const rows = await op('search').handler(ctxOf(), { query: 'walrus', return_unit: 'page' }) as SearchResult[];+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.some(r => HEADER_LINE.test(r.chunk_text))).toBe(false);+ expect(lastMeta!.delivery.date_header).toBeUndefined();+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-dated' }) as Record<string, any>;+ expect(recall.facts[0].date_header).toBeUndefined();+ });++ test('on: query/search blocks carry observed dates; recall facts carry their validity window', async () => {+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');+ try {+ const rows = await op('query').handler(ctxOf(), { query: 'walrus', return_unit: 'page', expand: false }) as SearchResult[];+ const by = (slug: string) => rows.find(r => r.slug === slug)!;+ expect(by('chat/2026-02-10-walrus').chunk_text.split('\n')[0]).toBe('[observed 2026-02-10]');+ expect(by('notes/walrus-dated').chunk_text.split('\n')[0]).toBe('[observed 2026-03-05]');+ expect(by('notes/walrus-undated').chunk_text.split('\n')[0]).toBe('[observed unknown]');+ expect(lastMeta!.delivery.date_header).toBe(true);+ expect(lastMeta!.delivery.budget_used).toBeLessThanOrEqual(lastMeta!.delivery.budget_tokens);+ const auto = await op('search').handler(ctxOf(), { query: 'walrus' }) as SearchResult[];+ expect(auto.every(r => HEADER_LINE.test(r.chunk_text))).toBe(true);+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-dated' }) as Record<string, any>;+ expect(recall.facts[0].date_header).toBe('[observed unknown; valid 2026-03-01 to unknown]');+ } finally {+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);+ }+ });++ test('on: a fact from a dated source page is observed on that date; a fact written without a date does not show the write time as valid-from', async () => {+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');+ try {+ const fromChat = await engine.insertFact({ fact: 'Walrus moved its launch to April', kind: 'fact', entity_slug: 'notes/walrus-undated', source: 'test', visibility: 'world',+ valid_from: new Date('2026-02-10T00:00:00Z') }, { source_id: 'default' });+ await engine.executeRaw('UPDATE facts SET source_markdown_slug = $2 WHERE id = $1', [fromChat.id, 'chat/2026-02-10-walrus']);+ const undated = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;+ expect(undated.facts.find((f: any) => f.fact.includes('April')).date_header).toBe('[observed 2026-02-10; valid 2026-02-10 to unknown]');+ const written = await engine.insertFact({ fact: 'Walrus hired a new lead', kind: 'fact', entity_slug: 'notes/walrus-undated', source: 'test', visibility: 'world' }, { source_id: 'default' });+ const again = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;+ expect(again.facts.find((f: any) => f.id === written.id).date_header).toBe('[observed unknown; valid unknown to unknown]');+ } finally {+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);+ }+ });++ test('remember with valid_from stores it, and the header shows it as the start of validity', async () => {+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');+ try {+ await op('remember').handler(ctxOf(), { fact: 'Walrus opened a Porto office', provenance: 'chat on 2026-03-01', entity: 'notes/walrus-undated', valid_from: '2026-03-01' });+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;+ const row = recall.facts.find((f: any) => f.fact.includes('Porto'));+ expect(row.valid_from.slice(0, 10)).toBe('2026-03-01');+ expect(row.date_header).toBe('[observed unknown; valid 2026-03-01 to unknown]');+ } finally {+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);+ }+ });++ test('remember rejects a valid_from that is not an ISO 8601 date', async () => {+ await expect(op('remember').handler(ctxOf(), { fact: 'Walrus is in Lisbon', provenance: 'test', valid_from: 'last spring' })).rejects.toMatchObject({ code: 'invalid_params' });+ });++ test('remote clamp: 32k by default and reported; a trusted eval brain raises it with search.return_budget_max_remote', async () => {+ await op('search').handler(ctxOf({ remote: true }), { query: 'walrus', return_unit: 'page', token_budget: 90000 });+ expect(lastMeta!.delivery.budget_clamped).toEqual({ requested: 90000, max: 32000 });+ expect(lastMeta!.delivery.fallbacks).toContain('budget_clamped');+ await engine.setConfig('search.return_budget_max_remote', '200000');+ try {+ await op('search').handler(ctxOf({ remote: true }), { query: 'walrus', return_unit: 'page', token_budget: 90000 });+ expect(lastMeta!.delivery.budget_tokens).toBe(90000);+ expect(lastMeta!.delivery.budget_clamped).toBeUndefined();+ expect(lastMeta!.delivery.fallbacks).not.toContain('budget_clamped');+ } finally {+ await engine.unsetConfig('search.return_budget_max_remote');+ }+ });+});diff --cc test/fixtures/goldens/exports/runtime.jsonindex 69258dee04,aa2f2c1078..0c79230202--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@@ -794,7 -802,7 +802,8 @@@"isConversationLabels","locateChunks","pageEvidenceText",+ "pagePlanHits",+ "parseAutoPacking","parseReturnUnit","parseReturnWindow","resolveEvidencePlan",diff --cc test/fixtures/goldens/exports/types.jsonindex afb6afbeba,6bd00ce4e5..99ed919031--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@@ -6677,9 -6692,16 +6699,16 @@@"kind": "type","name": "AutoReason","signature": [- "\"conversation_type\" | \"conversation_slug\" | \"not_conversation\" | \"conversation_over_budget\""+ "\"conversation_type\" | \"conversation_slug\" | \"not_conversation\" | \"conversation_over_budget\" | \"saved_fact\""]},+ {+ "kind": "variable",+ "name": "DEFAULT_AUTO_PACKING",+ "signature": [+ "\"off\" | \"cap_only\" | \"breadth_capped\" | \"depth_first\""+ ]+ },{"kind": "variable","name": "DEFAULT_CONVERSATION_BUDGET",@@@ -6801,9 -6830,10 +6838,11 @@@"kind": "interface","members": ["budgetClamped?: { requested: number; max: number; } | undefined",+ "budgetExplicit: boolean","budgetTokens: number",+ "dateHeader?: true | undefined","explicitUnit: boolean",+ "packing: \"off\" | \"cap_only\" | \"breadth_capped\" | \"depth_first\"","requestedUnit: \"auto\" | \"window\" | \"chunk\" | \"section\" | \"page\"","unit: \"auto\" | \"window\" | \"section\" | \"page\"","window: number"@@@ -6998,13 -7057,13 +7066,20 @@@"(page: { compiled_truth: string; timeline: string; }, includeTimeline: boolean) => { text: string; timelineAt: number; }"]},+ {+ "kind": "function",+ "name": "pagePlanHits",+ "signature": [+ "(plan: EvidencePlan | null) => { limit?: number; autocut?: false; }"+ ]+ },+ {+ "kind": "function",+ "name": "parseAutoPacking",+ "signature": [+ "(raw: unknown) => AutoPacking | undefined"+ ]+ },{"kind": "function","name": "parseReturnUnit",diff --cc test/query-page-budget-fill.test.tsindex ed3aa7a337,0000000000..0dc286c447mode 100644,000000..100644--- a/test/query-page-budget-fill.test.ts+++ b/test/query-page-budget-fill.test.ts@@@ -1,48 -1,0 +1,48 @@@+/**+ * `query` with return_unit page fills its token budget: the hit list is sized+ * to the budget (about one row per 250 tokens, at most 100) and autocut stays+ * off unless the caller sets it, so a page lane is not cut at the default row+ * count with half its budget unused. An explicit limit or autocut still wins.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { pagePlanHits, type EvidencePlan } from '../src/core/search/evidence-delivery.ts';++let engine: PGLiteEngine;+let meta: Record<string, any> | null = null;+const ctx = () => ({ engine, config: { engine: 'pglite', embedding_disabled: true }, remote: false, sourceId: 'default', dryRun: false,+ logger: { info() {}, warn() {}, error() {} }, emitResponseMeta: (k: string, v: unknown) => { if (k === 'retrieval') meta = v as Record<string, any>; } }) as unknown as OperationContext;+const query = operations.find(o => o.name === 'query')!;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (let i = 0; i < 40; i++) {+ await submitPageMutation(ctx(), { operation: 'put_page', params: { slug: `notes/garden-${i}`,+ content: `---\ntype: note\ntitle: Garden note ${i}\n---\nThe garden tomato harvest note ${i}. ` + 'We planted tomatoes and basil in the garden beds this season. '.repeat(20) } });+ }+}, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });++describe('page-unit budget fill', () => {+ test('pagePlanHits: autocut off and rows sized to large budgets, for page plans only', () => {- const plan = (unit: EvidencePlan['unit'], budgetTokens: number) => ({ requestedUnit: unit, unit, window: 1, budgetTokens, explicitUnit: true }) as EvidencePlan;++ const plan = (unit: EvidencePlan['unit'], budgetTokens: number) => ({ requestedUnit: unit, unit, window: 1, budgetTokens, explicitUnit: true, budgetExplicit: true, packing: 'cap_only' }) as EvidencePlan;+ expect(pagePlanHits(null)).toEqual({});+ expect(pagePlanHits(plan('window', 8000))).toEqual({});+ expect(pagePlanHits(plan('page', 4000))).toEqual({ autocut: false });+ expect(pagePlanHits(plan('page', 8000))).toEqual({ autocut: false, limit: 32 });+ expect(pagePlanHits(plan('page', 100_000))).toEqual({ autocut: false, limit: 100 });+ });++ test('an 8k page lane delivers close to its budget; an explicit limit still caps it', async () => {+ const rows = await query.handler(ctx(), { query: 'garden tomato harvest', return_unit: 'page', token_budget: 8000, expand: false }) as unknown[];+ expect(rows.length).toBeGreaterThan(25);+ expect(meta!.delivery.tokens_delivered ?? meta!.delivery.budget_used).toBeGreaterThan(7000);+ const capped = await query.handler(ctx(), { query: 'garden tomato harvest', return_unit: 'page', token_budget: 8000, expand: false, limit: 10 }) as unknown[];+ expect(capped.length).toBeLessThanOrEqual(10);+ });+});