Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): temporal fact reserve behind search.temporal_fact_reserve (default off)
garrytan716b0f5b4c6b
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex b712693895..b207eab65b 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -311,6 +311,14 @@ Two cross-cutting seams sit around the pipeline rather than inside it:with correction-dated writes it lifted forget-then-remember from 92% to 100%correct. `search.query_facts_arm=false` turns it off. Verdict and gates:`docs/eval/decisions/query-facts-arm/`.+- **Temporal fact reserve (default off).** With `search.temporal_fact_reserve=true`,+ a `query` with a deterministic temporal cue (when, before, after, how long,+ since, until, ordinal-time words, ISO dates, month names) and a token budget+ (`token_budget`, or the one evidence delivery resolves) gives facts ranked by+ the question (cosine + term share, +0.1 for a real date) up to 15% of the+ budget and 30% of the rows. They render with their date header, oldest first+ after the pages, in place of the facts arm. No model call. Gates:+ `docs/eval/decisions/temporal-fact-reserve/`.### Use-attributed feedbackdiff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex c1cd5c99e1..6d9d3db8dd 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -7,8 +7,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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` (midnight UTC renders as written, other instants in `brain.timezone`; the rule think's page dates use), `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/`.-- `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); with both off it returns the rows untouched.+- `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 --git a/docs/eval/decisions/temporal-fact-reserve/README.md b/docs/eval/decisions/temporal-fact-reserve/README.mdindex e44598da62..32ca105f13 100644--- a/docs/eval/decisions/temporal-fact-reserve/README.md+++ b/docs/eval/decisions/temporal-fact-reserve/README.md@@ -1,8 +1,29 @@# Temporal fact reserve in query: preregistered gates-Not built and not measured. The gates below are written before any code or gated run. The change sits behind-`search.temporal_fact_reserve`, which is off by default. With the key off, and for every query without a temporal-cue, `query` returns exactly what it returns today.+Built behind `search.temporal_fact_reserve`, which is off by default. Gate 2 passed, but the reserve never fires on+those sets as written; gate 1 waits on the harness lane. With the key off, and for every query without a temporal+cue, `query` returns exactly what it returned before.++## Gate 2 result++Gate 2 ran on the bounded build (row share 30%), hermetic and keyword-only, with the key on and off. No question's+recall@10 is lower with the key on, in any of the five sets, with or without `token_budget: 8000`. That makes gate 2+a pass.++The pass is close to vacuous. None of the five sets has a temporal cue in its questions, so the reserve fired 0+times in each. A diagnostic outside the gate appends ", and when?" to the questions of the two fact copies:++- NamedThingBench: the reserve fired on 11 of 12 questions with no recall loss (0.833 both ways).+- Relational fixture: the reserve fired on 38 of 38, but the appended words already drop page recall to 0 with the+ key off, so this copy shows nothing.++With the key off, `query` output on these sets matches garrytan/gbrain@eb696b3df, apart from wall-clock recency+scores. The facts arm's own gate-2 numbers are unchanged.++Gate 1 (BEAM dev, harness lane) has not run.++## Preregistration+## Why@@ -25,8 +46,9 @@ With the key on, a `query` whose text carries a temporal cue gives saved facts a- **Budget.** The reserve applies only when the call has a token budget: the caller's `token_budget`, or the budgetevidence delivery resolves for `return_unit`. Without one, `query` behaves as today (the facts arm's spare-capacityrows).-- **Share.** Facts take at most 15% of that budget, counted with the search token estimator, and at most 20 rows.- Pages fill the rest. The row count never grows: a fact row takes a free row, else the lowest page row.+- **Share.** Facts take at most 15% of that budget, counted with the search token estimator, and at most 30% of the+ caller's row count (at least 1, at most 20 rows). Pages fill the rest. The row count never grows: a fact row takes+ a free row, else the lowest page row.- **Candidates.** Active facts only, under the same read policy as the facts arm (source scope, world facts only forremote callers, audit rows excluded): the 50 nearest by the query embedding `query` already computed, plus the 50best keyword matches, plus the named entity's facts.@@ -58,3 +80,8 @@ owns its spend. The spend cap for this lane's own runs is $10.## Changelog- 2026-10-06: gates preregistered before any code or gated run.+- 2026-10-06: before gate 1 ran, the row bound changed from "at most 20 rows" to "at most 30% of the row count (1-20)".+ The first build let reserved facts fill every row of a `limit: 10` call under the default `auto` budget. The gate 2+ runs made on that build are void and were rerun on the bounded build. The token share and both gates are+ unchanged.+- 2026-10-06: built; gate 2 passed on the bounded build (the reserve never fired on the sets as written).diff --git a/evals/entity-anchoring/regression.ts b/evals/entity-anchoring/regression.tsindex 82455ac681..11186d1c02 100644--- a/evals/entity-anchoring/regression.ts+++ b/evals/entity-anchoring/regression.ts@@ -21,10 +21,13 @@ import { loadNamedThingQuestions, seedNamedThingCorpus } from '../../test/fixturimport { RELATIONAL_QUESTIONS, seedRelationalCorpus } from '../../test/fixtures/retrieval-quality/relational/corpus.ts';const KEY = (() => { const i = process.argv.indexOf('--key'); return i >= 0 ? process.argv[i + 1]! : 'search.entity_anchoring'; })();-type Row = { slug: string; entity_anchored?: string; result_type?: string };+const TOKEN_BUDGET = (() => { const i = process.argv.indexOf('--token-budget'); return i >= 0 ? Number(process.argv[i + 1]) : undefined; })();+type Row = { slug: string; entity_anchored?: string; result_type?: string; chunk_text?: string };/** Page rows only: an added fact row is not a page hit for recall. */const pagesOf = (rows: Row[]) => rows.filter(r => r.result_type !== 'fact');-const fired = (rows: Row[]) => rows.some(r => r.entity_anchored || r.result_type === 'fact');+/** The key's own rows: anchored pages, facts-arm rows, or (temporal reserve) date-headed fact rows. */+const fired = (rows: Row[]) => rows.some(r => r.entity_anchored+ || (r.result_type === 'fact' && (KEY !== 'search.temporal_fact_reserve' || r.chunk_text?.startsWith('[observed '))));const dump: Record<string, unknown> = {};async function freshEngine(): Promise<PGLiteEngine> {@@ -36,7 +39,7 @@ async function freshEngine(): Promise<PGLiteEngine> {async function ranked(engine: PGLiteEngine, query: string, on: boolean, label: string): Promise<Row[]> {await engine.setConfig(KEY, on ? 'true' : 'false');- const rows = await handleToolCall(engine, 'query', { query, limit: 10, expand: false, use_cache: false }) as Row[];+ const rows = await handleToolCall(engine, 'query', { query, limit: 10, expand: false, use_cache: false, ...(TOKEN_BUDGET ? { token_budget: TOKEN_BUDGET } : {}) }) as Row[];if (!on) dump[`${label}::${query}`] = rows;return rows;}@@ -99,13 +102,15 @@ if (import.meta.main) {await seed(engine);reports.push(await scoreCorpus(name, engine, [...questions]));reports.push(await scoreCorpus(`${name}+now`, engine, withCue([...questions])));- if (KEY === 'search.query_facts_arm') {+ if (KEY === 'search.query_facts_arm' || KEY === 'search.temporal_fact_reserve') {// Diagnostic: one saved fact restating each question's answer, so fact rows take page slots.for (const q of questions) {const answer = q.relevant?.[0];if (answer) await engine.insertFact({ fact: `${q.query.replace(/[?.!\s]+$/, '')}: ${answer}`, kind: 'fact', entity_slug: q.seed ?? null, source: 'regression diagnostic', visibility: 'world' }, { source_id: 'default' });}reports.push(await scoreCorpus(`${name}+facts`, engine, [...questions]));+ // Not a gate: the same questions with a temporal cue, so the reserve fires.+ if (KEY === 'search.temporal_fact_reserve') reports.push(await scoreCorpus(`${name}+facts+when`, engine, questions.map(q => ({ ...q, query: `${q.query.replace(/[?.!\s]+$/, '')}, and when?` }))));}} finally {await engine.disconnect();@@ -114,8 +119,8 @@ if (import.meta.main) {const lme = new URL('../../test/fixtures/longmemeval-nightly.jsonl', import.meta.url).pathname;reports.push(await longMemEval(lme, false), await longMemEval(lme, true));const asWritten = reports.filter(r => !r.corpus.endsWith('+now') && !r.corpus.endsWith('+facts'));- const withFacts = reports.filter(r => !r.corpus.endsWith('+now'));- const out = { mode: 'hermetic', keyword_only: true, key: KEY, pass: asWritten.every(r => r.recall10_lower.length === 0),+ const withFacts = reports.filter(r => !r.corpus.endsWith('+now') && !r.corpus.endsWith('+when'));+ const out = { mode: 'hermetic', keyword_only: true, key: KEY, token_budget: TOKEN_BUDGET ?? null, pass: asWritten.every(r => r.recall10_lower.length === 0),pass_with_facts_diagnostics: withFacts.every(r => r.recall10_lower.length === 0), reports };const dumpPath = flag('--dump-off');if (dumpPath) writeFileSync(dumpPath, JSON.stringify(dump, null, 2));diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex da96c10d79..10b54ebbbe 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 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 readsrc/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 1878 ratchet +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 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)+src/core/config.ts 1879 ratchet +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 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 2711 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 envsrc/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 663 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)diff --git a/src/core/config.ts b/src/core/config.tsindex dd12ea4659..99a5b74351 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1386,6 +1386,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['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 --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex ffcc490726..4b79905ab4 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -896,7 +896,7 @@ const query: Operation = {results = await applyQueryArms(ctx.engine, p, queryText, await withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {limit: altLimit, excludePrivate, requireSafeChunks: ctx.remote !== false, takesHoldersAllowList: readHolders(ctx),expansion: false, types, ...querySourceScope,- })), { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan, remote: ctx.remote !== false, queryEmbedding, rowCap: () => resolveEffectiveLimit(ctx, p) });+ })), { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan, evidenceBudget: plan?.budgetTokens, remote: ctx.remote !== false, queryEmbedding, rowCap: () => resolveEffectiveLimit(ctx, p) });// #1663 — CRAG confidence gate. Grade what retrieval returned (zero-LLM;// reads the stamped honesty signals: evidence, exact_lookup, rerank// score), attach grade + query shape to the retrieval meta on EVERY call,diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 4c64749f34..d817a81703 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -910,7 +910,7 @@ export async function deliverEvidence(}}const headerFor = (hit: SearchResult): string => !dateHeaders ? ''- : hit.fact_row ? `${factDateHeader(hit.fact_row)}\n` : `${dateHeaders.get(hit.page_id) ?? pageDateHeader(null)}\n`;+ : hit.fact_row ? (hit.chunk_text?.startsWith('[observed ') ? '' : `${factDateHeader(hit.fact_row)}\n`) : `${dateHeaders.get(hit.page_id) ?? pageDateHeader(null)}\n`;const planned: Block[] = [];for (const g of groups) {diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 4d33554295..46f18facd2 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -25,6 +25,7 @@ import { privateProvenanceFilterFragment } from './private-visibility.ts';import { namedEntity } from './entity-anchor.ts';import { pageReadFilter } from './read-policy-sql.ts';import { enforceTokenBudget, resultTokens } from './token-budget.ts';+import { factDateHeader } from './evidence-date.ts';export const QUERY_FACTS_ARM_KEY = 'search.query_facts_arm';/** Fact rows added per query at most. */@@ -34,6 +35,27 @@ export const FACT_COSINE_MIN = 0.6;/** Share of the query's content terms a fact's text and entity must hold to match by keyword. */const TERM_SHARE_MIN = 0.5;+/** Temporal fact reserve (docs/eval/decisions/temporal-fact-reserve/): off by default. */+export const TEMPORAL_FACT_RESERVE_KEY = 'search.temporal_fact_reserve';+/** Share of the caller's token budget reserved facts may take. */+export const TEMPORAL_RESERVE_SHARE = 0.15;+export const MAX_RESERVE_ROWS = 20;+/** Share of the caller's row count reserved facts may take (at least one row). */+export const TEMPORAL_RESERVE_ROW_SHARE = 0.3;+const RESERVE_COSINE_MIN = 0.5;+const RESERVE_TERM_SHARE_MIN = 0.34;+const DATED_BONUS = 0.1;+/** valid_from this far from created_at means the writer supplied the date. */+const DATED_MIN_MS = 24 * 60 * 60 * 1000;+const MONTHS = 'january|february|march|april|may|june|july|august|september|october|november|december';+const TEMPORAL_CUE = new RegExp(`\\b(when|before|after|since|until|till|during|ago|earlier|later|earliest|latest|first|last|previous|next|dates?|day|week|month|year|order|sequence|${MONTHS})\\b`+ + `|\\bhow (long|many (days|weeks|months|years))\\b|\\bwhat time\\b|\\b\\d{4}-\\d{2}-\\d{2}\\b`, 'i');++/** Whether `query` carries a deterministic temporal cue (the preregistered word, phrase, ISO date and month-name list). */+export function hasTemporalCue(query: string): boolean {+ return TEMPORAL_CUE.test(query);+}+const STOPWORDS = new Set(['the', 'and', 'for', 'who', 'what', 'when', 'where', 'which', 'with', 'from', 'that', 'this', 'are', 'was', 'were', 'our', 'your', 'their','now', 'current', 'currently', 'should', 'does', 'did', 'has', 'have', 'how', 'any', 'all', 'about', 'into', 'its', 'next', 'use', 'uses', 'tell']);@@ -41,7 +63,7 @@ export interface FactsArmScope { sourceId?: string; sourceIds?: string[]; remoteinterface FactCandidate {id: number; fact: string; kind: string; entity_slug: string | null; source_id: string; source: string;- valid_from: Date | string; valid_until: Date | string | null; claim_metric: string | null; claim_period: string | null;+ valid_from: Date | string; valid_until: Date | string | null; created_at?: Date | string | null; claim_metric: string | null; claim_period: string | null;}export function queryTerms(query: string): string[] {@@ -50,16 +72,30 @@ export function queryTerms(query: string): string[] {const day = (v: Date | string | null) => (v ? new Date(v).toISOString().slice(0, 10) : null);-/** The active facts that match `query`, newest valid_from first (at most MAX_FACT_ROWS). */-export async function matchQueryFacts(engine: BrainEngine, query: string, scope: FactsArmScope, queryEmbedding?: Float32Array | null): Promise<FactCandidate[]> {+type ScoredCandidate = FactCandidate & { similarity?: number; matched: number; terms: number; entity: boolean };++/**+ * Active facts near `query` under the caller's read policy: the keyword+ * matches (with how many query terms each holds), the `cosineLimit` nearest by+ * the query embedding (with their similarity), and the named entity's newest+ * `entityLimit` facts.+ */+async function collectFactCandidates(engine: BrainEngine, query: string, scope: FactsArmScope, queryEmbedding: Float32Array | null | undefined,+ limits: { cosine: number; entity: number }): Promise<ScoredCandidate[]> {const terms = queryTerms(query);const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];const params: unknown[] = [sources, [...AUDIT_ROW_SOURCES]];const base = `f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULLAND (f.valid_until IS NULL OR f.valid_until > now()) AND f.source != ALL($2::text[])${scope.remote ? `AND f.visibility = 'world' AND ${privateProvenanceFilterFragment('f')}` : ''}`;- const cols = 'f.id, f.fact, f.kind, f.entity_slug, f.source_id, f.source, f.valid_from, f.valid_until, f.claim_metric, f.claim_period';- const found = new Map<number, FactCandidate>();+ const cols = 'f.id, f.fact, f.kind, f.entity_slug, f.source_id, f.source, f.valid_from, f.valid_until, f.created_at, f.claim_metric, f.claim_period';+ const found = new Map<number, ScoredCandidate>();+ const add = (r: FactCandidate & { haystack?: string; similarity?: number }, entity = false) => {+ const prev = found.get(Number(r.id));+ const haystack = r.haystack ?? `${r.fact} ${r.entity_slug ?? ''}`.toLowerCase();+ found.set(Number(r.id), { ...r, similarity: r.similarity !== undefined ? Number(r.similarity) : prev?.similarity,+ matched: terms.filter(t => haystack.includes(t)).length, terms: terms.length, entity: entity || !!prev?.entity });+ };if (terms.length) {const rows = await engine.executeRaw<FactCandidate & { haystack: string }>(`WITH q AS (SELECT NULLIF(replace(plainto_tsquery($3::regconfig, $4)::text, ' & ', ' | '), '')::tsquery AS q)@@ -68,8 +104,7 @@ export async function matchQueryFacts(engine: BrainEngine, query: string, scope:AND to_tsvector($3::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' ')) @@ q.qORDER BY ts_rank_cd(to_tsvector($3::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' ')), q.q) DESC, f.valid_from DESCLIMIT 50`, [...params, getFtsLanguage(), terms.join(' ')]);- const need = Math.max(Math.min(2, terms.length), Math.ceil(terms.length * TERM_SHARE_MIN));- for (const r of rows) if (terms.filter(t => r.haystack.includes(t)).length >= need) found.set(Number(r.id), r);+ for (const r of rows) add(r);}if (queryEmbedding && queryEmbedding.length) {const model = getEmbeddingModel();@@ -78,17 +113,24 @@ export async function matchQueryFacts(engine: BrainEngine, query: string, scope:`SELECT ${cols}, 1 - (f.embedding <=> $3::vector) AS similarity FROM facts fWHERE ${base} AND f.embedding IS NOT NULL AND f.embedding_model = $4 AND f.embedded_text_hash = md5(f.fact)AND vector_dims(f.embedding) = $5- ORDER BY f.embedding <=> $3::vector LIMIT 10`, [...params, lit, model, queryEmbedding.length]).catch(() => []);- for (const r of rows) if (Number(r.similarity) >= FACT_COSINE_MIN) found.set(Number(r.id), r);+ ORDER BY f.embedding <=> $3::vector LIMIT ${limits.cosine}`, [...params, lit, model, queryEmbedding.length]).catch(() => []);+ for (const r of rows) add(r);}const entity = await namedEntity(engine, query, { sourceIds: sources, excludePrivate: scope.remote }).catch(() => null);if (entity) {const rows = await engine.executeRaw<FactCandidate>(- `SELECT ${cols} FROM facts f WHERE ${base} AND f.entity_slug = $3 ORDER BY f.valid_from DESC, f.id DESC LIMIT ${MAX_FACT_ROWS}`,+ `SELECT ${cols} FROM facts f WHERE ${base} AND f.entity_slug = $3 ORDER BY f.valid_from DESC, f.id DESC LIMIT ${limits.entity}`,[...params, entity.slug]);- for (const r of rows) found.set(Number(r.id), r);+ for (const r of rows) add(r, true);}- return [...found.values()]+ return [...found.values()];+}++/** The active facts that match `query`, newest valid_from first (at most MAX_FACT_ROWS). */+export async function matchQueryFacts(engine: BrainEngine, query: string, scope: FactsArmScope, queryEmbedding?: Float32Array | null): Promise<FactCandidate[]> {+ const candidates = await collectFactCandidates(engine, query, scope, queryEmbedding, { cosine: 10, entity: MAX_FACT_ROWS });+ return candidates+ .filter(c => c.entity || (c.similarity ?? -1) >= FACT_COSINE_MIN || (c.terms > 0 && c.matched >= Math.max(Math.min(2, c.terms), Math.ceil(c.terms * TERM_SHARE_MIN)))).sort((a, b) => new Date(b.valid_from).getTime() - new Date(a.valid_from).getTime() || Number(b.id) - Number(a.id)).slice(0, MAX_FACT_ROWS);}@@ -190,6 +232,63 @@ export async function applyFactsArm(engine: BrainEngine, query: string, results:}}+const isDated = (f: FactCandidate) => !!f.created_at && Math.abs(new Date(f.valid_from).getTime() - new Date(f.created_at).getTime()) > DATED_MIN_MS;++/**+ * Temporal fact reserve: for a query with a temporal cue and a token budget,+ * the facts that best match the question (cosine + term share, +0.1 when the+ * fact carries a real date) take up to TEMPORAL_RESERVE_SHARE of the budget and+ * TEMPORAL_RESERVE_ROW_SHARE of the row count (1 to MAX_RESERVE_ROWS rows), rendered with their date header and ordered oldest+ * first after the pages. The row count never grows (a fact takes a free row,+ * else the lowest page row) and pages fill the rest of the budget. No match or+ * any error: the results unchanged.+ */+export async function applyTemporalFactReserve(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }): Promise<SearchResult[]> {+ try {+ const candidates = await collectFactCandidates(engine, query, opts, opts.queryEmbedding, { cosine: 50, entity: MAX_RESERVE_ROWS });+ const scored = candidates+ .map(c => ({ c, share: c.terms ? c.matched / c.terms : 0, cos: c.similarity ?? 0 }))+ .filter(x => x.cos >= RESERVE_COSINE_MIN || x.share >= RESERVE_TERM_SHARE_MIN)+ .map(x => ({ c: x.c, score: x.cos + x.share + (isDated(x.c) ? DATED_BONUS : 0) }))+ .sort((a, b) => b.score - a.score || Number(b.c.id) - Number(a.c.id));+ if (!scored.length) return results;+ const rowCap = Math.max(results.length, (await opts.rowCap?.().catch(() => 0)) ?? 0);+ const pageSlugs = await readableEntityPages(engine, scored.map(x => x.c), opts.readScope).catch(() => new Set<string>());+ const pagesFloor = results.reduce((m, r) => (Number.isFinite(r.score) && r.score < m ? r.score : m), results[0]?.score ?? 1);+ let left = Math.floor(opts.budget * TEMPORAL_RESERVE_SHARE);+ const chosen: Array<{ c: FactCandidate; row: SearchResult }> = [];+ for (const { c } of scored) {+ if (chosen.length >= Math.min(MAX_RESERVE_ROWS, Math.max(1, Math.floor(rowCap * TEMPORAL_RESERVE_ROW_SHARE)))) break;+ const row = factRow(c, 0, c.entity_slug && pageSlugs.has(`${c.source_id}\u0000${c.entity_slug}`) ? c.entity_slug : undefined);+ row.chunk_text = `${factDateHeader(c)}\n${c.fact}`;+ const cost = resultTokens(row);+ if (cost > left) continue;+ left -= cost;+ chosen.push({ c, row });+ }+ if (!chosen.length) return results;+ chosen.sort((a, b) => new Date(a.c.valid_from).getTime() - new Date(b.c.valid_from).getTime() || Number(a.c.id) - Number(b.c.id));+ const rows = chosen.map(({ row }, i) => ({ ...row, score: pagesFloor - (i + 1) * 1e-6 }));+ let pages = results.slice(0, Math.max(0, Math.min(results.length, rowCap - rows.length))).map(r => ({ ...r }));+ if (opts.tokenBudget) pages = enforceTokenBudget(pages, Math.max(1, opts.tokenBudget - rows.reduce((n, r) => n + resultTokens(r), 0))).results;+ const merged = [...pages, ...rows];+ await stampSupersededClaims(engine, merged, chosen.map(x => x.c)).catch(() => undefined);+ return merged;+ } catch {+ return results;+ }+}++/** `search.temporal_fact_reserve` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */+export async function temporalFactReserveEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {+ try {+ const raw = (await engine.getConfig(TEMPORAL_FACT_RESERVE_KEY))?.trim().toLowerCase();+ return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';+ } catch {+ return false;+ }+}+/*** `search.query_facts_arm`: on by default (gates 1b and 2 passed,* docs/eval/decisions/query-facts-arm/); 'false' | 'off' | '0' | 'no' turns itdiff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.tsindex 91b245c53c..86a3467c42 100644--- a/src/core/search/query-arms.ts+++ b/src/core/search/query-arms.ts@@ -2,20 +2,24 @@* The `query` op's post-retrieval arms, applied after hybrid search and the* declared-name fan-out, before the CRAG grade: entity anchoring* (`search.entity_anchoring`, default off, search/entity-anchor.ts) and then- * the facts arm (`search.query_facts_arm`, default on, search/facts-arm.ts).- * With both off the rows pass through unchanged.+ * the facts arm (`search.query_facts_arm`, default on, search/facts-arm.ts),+ * or in its place, for a query with a temporal cue and a token budget, the+ * temporal fact reserve (`search.temporal_fact_reserve`, default off). With+ * all off the rows pass through unchanged.*/import type { BrainEngine } from '../engine.ts';import type { PageReadScope, SearchResult } from '../types.ts';import { anchorOpResults } from './entity-anchor.ts';-import { applyFactsArm, queryFactsArmEnabled } from './facts-arm.ts';+import { applyFactsArm, applyTemporalFactReserve, hasTemporalCue, queryFactsArmEnabled, temporalFactReserveEnabled } from './facts-arm.ts';export async function applyQueryArms(engine: BrainEngine, p: Record<string, unknown>, query: string, results: SearchResult[],- scope: PageReadScope & { filtered: boolean; evidencePlan: boolean; remote: boolean; queryEmbedding: Float32Array | null; rowCap: () => Promise<number> }): Promise<SearchResult[]> {+ scope: PageReadScope & { filtered: boolean; evidencePlan: boolean; evidenceBudget?: number; remote: boolean; queryEmbedding: Float32Array | null; rowCap: () => Promise<number> }): Promise<SearchResult[]> {const anchored = await anchorOpResults(engine, p, query, results, scope);- if (p.offset || scope.filtered || p.since || p.until || p.lang || p.symbol_kind || p.near_symbol || !await queryFactsArmEnabled(engine)) return anchored;- return applyFactsArm(engine, query, anchored, {- sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope,- tokenBudget: !scope.evidencePlan && typeof p.token_budget === 'number' ? p.token_budget : undefined,- });+ if (p.offset || scope.filtered || p.since || p.until || p.lang || p.symbol_kind || p.near_symbol) return anchored;+ const tokenBudget = !scope.evidencePlan && typeof p.token_budget === 'number' ? p.token_budget : undefined;+ const opts = { sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope, tokenBudget };+ const budget = scope.evidencePlan ? scope.evidenceBudget : tokenBudget;+ if (budget && hasTemporalCue(query) && await temporalFactReserveEnabled(engine)) return applyTemporalFactReserve(engine, query, anchored, { ...opts, budget });+ if (!await queryFactsArmEnabled(engine)) return anchored;+ return applyFactsArm(engine, query, anchored, opts);}diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex c58ca580db..c7ebc97212 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -43,6 +43,7 @@ const DIRECTLY_READ_SINGLETONS = ['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 --git a/test/search-temporal-fact-reserve.test.ts b/test/search-temporal-fact-reserve.test.tsnew file mode 100644index 0000000000..3523d1dbe0--- /dev/null+++ b/test/search-temporal-fact-reserve.test.ts@@ -0,0 +1,89 @@+/**+ * Temporal fact reserve for `query` (`search.temporal_fact_reserve`, default+ * off; gates in docs/eval/decisions/temporal-fact-reserve/): a query with a+ * temporal cue and a token budget gives question-ranked, dated-first facts up+ * to 15% of the budget, rendered with their date header and ordered oldest+ * first after the pages; the row count never grows. The budget is the+ * caller's token_budget or the one evidence delivery resolves (return_unit,+ * including the default auto). With the key off, without a cue or with no+ * budget at all (chunk unit, no token_budget), the result is byte-identical to+ * the build without the reserve. PGLite, keyword-only, no network.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { handleToolCall } from '../src/mcp/server.ts';+import { MAX_RESERVE_ROWS, TEMPORAL_FACT_RESERVE_KEY, TEMPORAL_RESERVE_ROW_SHARE, TEMPORAL_RESERVE_SHARE, hasTemporalCue } from '../src/core/search/facts-arm.ts';+import { resultTokens } from '../src/core/search/token-budget.ts';+import type { SearchResult } from '../src/core/types.ts';+import { newSource, page, putPage } from './helpers/pinned-questions-fixture.ts';++let engine: PGLiteEngine;+let sourceId: string;+const TEMPORAL = 'When was the Forge offsite booked, and what happened after the venue changed?';+const PLAIN = 'Where is the Forge offsite booked?';+const query = async (q: string, params: Record<string, unknown> = {}) =>+ await handleToolCall(engine, 'query', { query: q, expand: false, use_cache: false, source_id: sourceId, limit: 6, ...params }) as SearchResult[];+const withKey = async <T>(value: string | null, run: () => Promise<T>): Promise<T> => {+ if (value === null) await engine.executeRaw('DELETE FROM config WHERE key = $1', [TEMPORAL_FACT_RESERVE_KEY]);+ else await engine.setConfig(TEMPORAL_FACT_RESERVE_KEY, value);+ try { return await run(); } finally { await engine.executeRaw('DELETE FROM config WHERE key = $1', [TEMPORAL_FACT_RESERVE_KEY]); }+};++/** Recency boosts read the wall clock, so scores move between calls; every other byte must match. */+const stable = (v: unknown) => JSON.stringify(v, (k, x) => (k === 'score' || k === 'recency_boost' ? undefined : x));++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ sourceId = await newSource(engine);+ for (let i = 0; i < 6; i++) {+ await putPage(engine, sourceId, `conversations/chat-${i}`, page('conversation', `chat ${i}`, `**User:** Notes on the Forge offsite part ${i}. The Forge offsite venue was booked and the venue changed once.\n\n**Assistant:** Noted.`, `date: 2025-07-0${i + 1}\n`));+ }+ await engine.insertFact({ fact: 'The Forge offsite venue was booked in Santa Fe.', kind: 'event', entity_slug: 'forge', source: 'conversation', visibility: 'world', valid_from: new Date('2025-06-02T00:00:00Z') }, { source_id: sourceId });+ await engine.insertFact({ fact: 'The Forge offsite venue changed to Missoula.', kind: 'event', entity_slug: 'forge', source: 'conversation', visibility: 'world', valid_from: new Date('2025-07-12T00:00:00Z') }, { source_id: sourceId });+ await engine.insertFact({ fact: 'The Forge offsite venue booking needs a deposit.', kind: 'fact', entity_slug: 'forge', source: 'conversation', visibility: 'world' }, { source_id: sourceId });+}, 120_000);+afterAll(async () => { await engine?.disconnect(); }, 60_000);++describe('temporal fact reserve', () => {+ test('temporal cues are deterministic words, phrases, ISO dates and month names', () => {+ for (const q of [TEMPORAL, 'how long did the trip take', 'What did I do on 2025-03-04?', 'the first time we met', 'plans for March']) expect(hasTemporalCue(q)).toBe(true);+ for (const q of [PLAIN, 'Who leads the platform team?', 'list every vendor']) expect(hasTemporalCue(q)).toBe(false);+ });++ test('off (unset or false), a query without a cue, or a chunk-unit call without token_budget (no budget at all): byte-identical to the build without the reserve', async () => {+ const chunkNoBudget = { return_unit: 'chunk' };+ const unset = await withKey(null, async () => [await query(TEMPORAL, { token_budget: 4000 }), await query(PLAIN, { token_budget: 4000 }), await query(TEMPORAL, chunkNoBudget)]);+ const off = await withKey('false', async () => [await query(TEMPORAL, { token_budget: 4000 }), await query(PLAIN, { token_budget: 4000 }), await query(TEMPORAL, chunkNoBudget)]);+ const onNoCueNoBudget = await withKey('true', async () => [await query(PLAIN, { token_budget: 4000 }), await query(TEMPORAL, chunkNoBudget)]);+ expect(stable(off)).toBe(stable(unset));+ expect(stable(onNoCueNoBudget)).toBe(stable([unset[1], unset[2]]));+ });++ test('on, temporal cue and token budget: dated facts first, date headers, oldest first, inside 15% of the budget and 30% of the rows', async () => {+ const budget = 4000;+ const off = await withKey(null, () => query(TEMPORAL, { token_budget: budget, limit: 10 }));+ const on = await withKey('true', () => query(TEMPORAL, { token_budget: budget, limit: 10 }));+ const facts = on.filter(r => r.result_type === 'fact');+ expect(facts.length).toBeGreaterThanOrEqual(2);+ expect(facts.length).toBeLessThanOrEqual(Math.min(MAX_RESERVE_ROWS, Math.floor(10 * TEMPORAL_RESERVE_ROW_SHARE)));+ expect(on.length).toBeLessThanOrEqual(Math.max(off.length, 10));+ expect(facts.slice(0, 2).map(r => r.chunk_text.split('\n')[0])).toEqual(['[observed unknown; valid 2025-06-02 to unknown]', '[observed unknown; valid 2025-07-12 to unknown]']);+ expect(facts.reduce((n, r) => n + resultTokens(r), 0)).toBeLessThanOrEqual(Math.floor(budget * TEMPORAL_RESERVE_SHARE));+ expect(on.findIndex(r => r.result_type === 'fact')).toBe(on.length - facts.length);+ });++ test('on, return_unit page: reserved facts are delivered first in the budget with one date header each', async () => {+ await engine.setConfig('search.evidence_date_header', 'true');+ try {+ const rows = await withKey('true', () => query(TEMPORAL, { token_budget: 4000, return_unit: 'page', limit: 10 })) as Array<SearchResult & { delivered?: { reason?: string } }>;+ const facts = rows.filter(r => r.result_type === 'fact');+ expect(facts.length).toBeGreaterThanOrEqual(2);+ for (const f of facts) {+ expect(f.delivered?.reason).toBe('saved_fact');+ expect(f.chunk_text.match(/\[observed /g)?.length).toBe(1);+ }+ } finally { await engine.executeRaw(`DELETE FROM config WHERE key = 'search.evidence_date_header'`); }+ });+});