Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
search: the facts block is on by default (search.query_facts_block)
garrytandb5a82a02e72
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex 583d443631..2e5663e67e 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -345,12 +345,16 @@ Two cross-cutting seams sit around the pipeline rather than inside it:budget and 30% of the rows. They render with their date header, oldest firstafter the pages, in place of the facts arm. No model call. Gates:`docs/eval/decisions/temporal-fact-reserve/`.-- **Facts block and fact source pages (default off, GBRA-205).** With- `search.query_facts_block=true`, every `query` with a token budget gets the- reserve's dated facts, up to 22% of the budget and 40 rows, oldest first- ahead of the pages. With `search.fact_source_pages=true`, the conversations- the best-matching facts came from join the hits after the top three rows.- Both wait on a held-out gate before any default change.+- **Facts block (default on) and fact source pages (default off), GBRA-205.**+ Every `query` with a token budget gets the reserve's dated facts, up to 22%+ of the budget and 40 rows, oldest first ahead of the pages, in place of the+ facts arm and the temporal reserve. On the sealed held-out set it answered+ 183 of 200 questions against 151 without it (gbrain-evals+ `docs/benchmarks/2026-10-26-gbrain-8k-conversion.md`).+ `search.query_facts_block=false` turns it off; a config read error also+ leaves it off. With `search.fact_source_pages=true`, the conversations the+ best-matching facts came from join the hits after the top three rows; it+ stays off (inert on development data).### Use-attributed feedbackdiff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 99e702139f..6f6feca751 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it by a ranking link type or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.- The facts arm, temporal fact reserve, facts block and fact source pages (`search/facts-arm.ts`): [Core Search (evidence blocks)](core-search-evidence.md).- `src/core/search/fact-relevance.ts` — question relevance for saved facts, shared by recall's `question` (`facts/question-recall.ts`), the temporal fact reserve and (pool only) the facts arm. `collectFactCandidates`: one bounded pool under recall's read policy (source scope, active and not superseded, audit rows excluded, quarantine and rederive hiding through `projectionEligibleSql`, the trust floor, remote world-only, `privateProvenanceFilterFragment` when `excludePrivate`) plus recall's filters inside every arm before its LIMIT (`(source_id, entity_slug)` pairs, `source_session`, event-time since, escaped `ILIKE` grep); arms, run concurrently and merged in a fixed order, are keyword FTS (`factsFtsDocument`, served by `idx_facts_fts`), cosine (cast to the facts column type, filtered on model only so the HNSW index serves it, a stale hash or other dimensions yielding no similarity; `ef_search` sized to the depth and pgvector's iterative scan when `hnswIterativeScan` is set) and the named entity page's facts in its own source; depths are bound parameters; `cosineForAll` scores every candidate's cosine whichever arm found it. A missing embedding column or other dimensions skips the cosine arm; any other DB error throws. `scoreFactCandidates`: cosine + whole-word term share + 0.1 when dated, the share's denominator growing past `TERM_STUFFING_RATIO` times the question's terms for a long fact; order score, newest valid_from, id. `admitted`: the `reserve` rule (cosine >= 0.5 or share >= 0.34) or the `facts_arm` rule (cosine >= 0.6, half the terms, or the named entity). `countUncomparableFacts` counts the pool's facts the cosine arm cannot compare, per source: candidates from `idx_facts_unembedded` and `idx_facts_embedding_model` first, the read policy on those rows only. The keyword arm and the count run under `customPlan` (`plan_cache_mode = force_custom_plan` in a transaction): a cached generic plan cannot see the source arrays and nests the policy anti-joins over every match. p95 at 100k facts: Postgres 51 ms local / 65 ms remote, PGLite 152 / 139 ms. Tests: `test/fact-relevance.test.ts`, `test/recall-question.test.ts`.-- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, fact source pages, then the facts arm), each behind its own key (the facts arm default on, the rest off); a query with a token budget takes the facts block (`search.query_facts_block`) or, with a temporal cue, the temporal fact reserve (`search.temporal_fact_reserve`) instead of the facts arm; with all off it returns the rows untouched.+- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, fact source pages, then the facts arm), each behind its own key (the facts arm default on, the rest off); a query with a token budget takes the facts block (`search.query_facts_block`, default on) or, with a temporal cue, the temporal fact reserve (`search.temporal_fact_reserve`) instead of the facts arm; with all off it returns the rows untouched.- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns; a segmented page's row says `segmented` and carries no body) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction. Chunk rows carry `projected_byte_start/end` when recorded, and on a segmented page their `occurrence_id` (the span is relative to that occurrence's projection), the references `search/segmented-evidence.ts` reads windows around.diff --git a/docs/architecture/key-files/core-search-evidence.md b/docs/architecture/key-files/core-search-evidence.mdindex 15f7fbc9f2..73bf2583fe 100644--- a/docs/architecture/key-files/core-search-evidence.md+++ b/docs/architecture/key-files/core-search-evidence.md@@ -5,4 +5,4 @@ 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` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off) and `evidenceTitlesEnabled` (`search.evidence_titles`, GBRA-205, default off: with the header on, `blockDateHeaders` ends a page block's line with its title via `titledPageHeader`, fact headers unchanged; think's `<page>` tag gets a `title` attribute). Tests: `test/evidence-date-header.test.ts`, `test/search-8k-conversion.test.ts`.- `src/core/search/evidence-tail-trim.ts` — the protected tail trim (`search.evidence_tail_trim`, default off, GBRA-156). `resolveEvidencePlan` sets `EvidencePlan.tailTrim` only for `unit: auto` with the key on; `deliverEvidence` calls `trimEvidenceTail(results, opts.query)` on the rank-order delivered rows after redaction and before the token totals, and only when `DeliverOptions.query` is set (`search`/`query` pass `p.query`; the library `assembleEvidenceForHits` passes `input.query` and frozen hits may carry `score`; the `assemble_evidence` op passes neither, so the trim never runs there). Rows past `TAIL_TRIM_PROTECTED` = 3 that are whole-conversation blocks (`delivered.reason` `conversation_type`/`conversation_slug`) and score under `TAIL_TRIM_SCORE_FRACTION` = 0.5 of rank one are dropped, unless their `chunk_text` holds at least `TAIL_TRIM_TERM_FRACTION` = 0.8 of rank one's share of the query's terms (`queryTerms`: letter/digit runs, stopwords and single characters dropped, cut to six characters). Rank one's score must be a positive finite number and every row's finite, or nothing changes. `delivery.tail_trim` is `{ dropped, kept_by_query_terms }`; `dropped_reasons.tail_trim` counts drops. Pinned by `test/evidence-tail-trim.test.ts` (the knowledge-update regression case).-- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Fact reserves: `applyFactReserve` serves two policies. The temporal fact reserve (`applyTemporalFactReserve`, `search.temporal_fact_reserve`, default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`. The facts block (`applyFactsBlock`, `search.query_facts_block`, GBRA-205, default off): the same facts for every budgeted query, up to 22% of the budget and 40 rows, oldest first ahead of the pages, adding rows. Fact source pages (`applyFactSourcePages`, `search.fact_source_pages`, GBRA-205, default off): the conversations (`facts.source_markdown_slug`, never the entity page) of the best-matching admitted facts, at most 2 not already present, read through `getChunkWindows` under the caller's read scope and placed after the top 3 rows; the row count never grows. Tests: `test/search-8k-conversion.test.ts`.+- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Fact reserves: `applyFactReserve` serves two policies. The temporal fact reserve (`applyTemporalFactReserve`, `search.temporal_fact_reserve`, default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`. The facts block (`applyFactsBlock`, `search.query_facts_block`, GBRA-205, default on since the held-out gate passed; `false` or a config read error turns it off): the same facts for every budgeted query, up to 22% of the budget and 40 rows, oldest first ahead of the pages, adding rows. Fact source pages (`applyFactSourcePages`, `search.fact_source_pages`, GBRA-205, default off): the conversations (`facts.source_markdown_slug`, never the entity page) of the best-matching admitted facts, at most 2 not already present, read through `getChunkWindows` under the caller's read scope and placed after the top 3 rows; the row count never grows. Tests: `test/search-8k-conversion.test.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 6a532dc58a..6f4f1155da 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,6 +13,7 @@ src/commands/jobs.ts 687 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)src/core/ai/gateway.ts 4533 ratchet +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved forsrc/commands/sync.ts 556 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts); +6 G8a git-canonical: SyncOpts.canonicalOverride interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-discovery.ts)+src/core/behavior-change-notice.ts 1502 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 GBRA-205 search.query_facts_block default-on row and its approval commentsrc/core/cycle.ts 3338 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug listsrc/core/cycle/synthesize.ts 3241 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip); +1 GBRA-60: a managed synthesis child carries dream_output (verify and stamp before put_page; cycle/synthesize-child-verify.ts)src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guarddiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 4c1af63423..3f9e6394f0 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1302,6 +1302,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.460.0', text: 'A legacy fact row whose `notability` or `confidence` is empty (a long-lived database whose column lost its NOT NULL) is now adopted into its page\'s `## Facts` table with the column default (notability `medium`, confidence 1) instead of being refused as unadoptable (`parse`) on every run, which held its page out of fact reconciliation and booked an `integrity_guard` halt each cycle. The fence cell is written first and the row derives its values from it. A row with no kind or visibility is still refused.' },{ since: '0.60.460.0', text: '`gbrain repair duplicate-facts` keeps the copy that is a row of a page\'s `## Facts` table over an older database-only copy of the same fact, so the legacy copy is superseded onto the fence row instead of holding it (which left the legacy row unfenced and its page out of fact reconciliation). With no fenced copy it still keeps the oldest row. It stays preview-first and explicit.' },{ since: '0.60.460.0', text: 'Dream consolidation on a managed brain now closes a fenced fact in its page: the closing `valid_until` is written into the fact\'s row in the entity page\'s `## Facts` fence, published with the take, and the database row takes its value from that cell, so a later sync or re-import keeps the fact closed. Before, only the database row was closed and the next re-import of the page reopened it. A fact with no fence row is still closed in the database. A fenced fact whose fence row is on another page is left open. Facts an earlier release closed in the database only are not changed (GBRA-190).' },+ // GBRA-205: Garry approved the default ("Yes", 2026-10-26), on the sealed held-out result (gbrain-evals docs/benchmarks/2026-10-26-gbrain-8k-conversion.md).+ { since: 'TBD', text: '`query` with a token budget now puts question-ranked dated saved facts ahead of the pages (the facts block): up to 22% of the budget and 40 rows, oldest first, each with its date header, in place of the facts arm (and of the temporal fact reserve when it is on). On a sealed held-out set of 200 questions it answered 183 against 151 without it. It adds about 70 tokens to a median budgeted result (p95 about 700) and no model call. Queries without a budget, `search` and `think` are unchanged; remote callers see only facts whose source pages they could read. `gbrain config set search.query_facts_block false` restores the previous results.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config.ts b/src/core/config.tsindex ce82cb7d92..09966125e6 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1439,7 +1439,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.entity_anchoring', // entity-anchored retrieval for entity-scoped current-state query/search (default off; search/entity-anchor.ts)'search.query_facts_arm', // query adds matching active facts as rows in spare capacity (default on; search/facts-arm.ts)'search.temporal_fact_reserve', // temporal-cue queries reserve up to 15% of the token budget for question-ranked dated facts (default off; search/facts-arm.ts)- 'search.query_facts_block', 'search.fact_source_pages', // GBRA-205, default off: a dated facts block (up to 22% of a query budget) ahead of the pages; matched facts' source conversations join the hits (search/facts-arm.ts)+ 'search.query_facts_block', 'search.fact_source_pages', // GBRA-205: a dated facts block (up to 22% of a query budget) ahead of the pages, default on; matched facts' source conversations join the hits, default off (search/facts-arm.ts)'search.page_rank_cut', // W5: whole_pages (default) | off — page unit + caller token_budget stops adding pages once their whole pages fill factor x the budget (search/page-rank-cut.ts)'search.page_rank_cut_factor', // W5: whole_pages target = factor x the budget (default 1.5)'think.return_unit',diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 52ecd90a57..cdb64b6d56 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -327,11 +327,11 @@ export async function temporalFactReserveEnabled(engine: { getConfig(key: string}}-/** `search.query_facts_block` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */+/** `search.query_facts_block` is on by default; 'false' | 'off' | '0' | 'no' turns it off, and so does any read error. */export async function queryFactsBlockEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {try {const raw = (await engine.getConfig(QUERY_FACTS_BLOCK_KEY))?.trim().toLowerCase();- return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';+ return !(raw === 'false' || raw === 'off' || raw === '0' || raw === 'no');} catch {return false;}diff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.tsindex e00fa25f0e..e022b16ad9 100644--- a/src/core/search/query-arms.ts+++ b/src/core/search/query-arms.ts@@ -5,9 +5,10 @@* source pages (`search.fact_source_pages`, default off) and then the facts* arm (`search.query_facts_arm`, default on, search/facts-arm.ts), or in its* place, for a query with a token budget, the facts block- * (`search.query_facts_block`, default off) or, with a temporal cue, the+ * (`search.query_facts_block`, default on) or, with a temporal cue, the* temporal fact reserve (`search.temporal_fact_reserve`, default off). With- * all off the rows pass through unchanged.+ * all off the rows pass through unchanged; the facts block is checked first, so+ * turning it off restores the temporal reserve or the facts arm.*/import type { BrainEngine } from '../engine.ts';import type { PageReadScope, SearchResult } from '../types.ts';diff --git a/test/search-8k-conversion.test.ts b/test/search-8k-conversion.test.tsindex bd8efbca74..4c1ddc2e09 100644--- a/test/search-8k-conversion.test.ts+++ b/test/search-8k-conversion.test.ts@@ -21,7 +21,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { handleToolCall } from '../src/mcp/server.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';-import { FACT_SOURCE_PAGE_RANK, FACT_SOURCE_PAGES_KEY, MAX_FACT_SOURCE_PAGES, MAX_FACTS_BLOCK_ROWS, QUERY_FACTS_BLOCK_KEY, QUERY_FACTS_BLOCK_SHARE } from '../src/core/search/facts-arm.ts';+import { FACT_SOURCE_PAGE_RANK, FACT_SOURCE_PAGES_KEY, MAX_FACT_SOURCE_PAGES, MAX_FACTS_BLOCK_ROWS, QUERY_FACTS_BLOCK_KEY, QUERY_FACTS_BLOCK_SHARE, queryFactsBlockEnabled } from '../src/core/search/facts-arm.ts';import { QUERY_BUDGET_UNIT_CONFIG_KEY } from '../src/core/search/evidence-delivery.ts';import { EVIDENCE_DATE_HEADER_KEY, EVIDENCE_TITLES_KEY } from '../src/core/search/evidence-date.ts';import { renderPagesBlockDetailed } from '../src/core/think/gather.ts';@@ -62,12 +62,12 @@ beforeAll(async () => {}, 120_000);afterAll(async () => { await engine?.disconnect(); }, 60_000);-describe('every key unset or off', () => {- test('byte-identical to the build without the keys', async () => {+describe('every key off', () => {+ test('byte-identical to the build without the keys (the facts block, on by default, turned off)', async () => {const calls = async () => [await query(PLAIN, { token_budget: 4000 }), await query(PLAIN), await query(PLAIN, { token_budget: 4000, return_unit: 'auto' })];- const unset = await calls();+ const defaultsOff = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: 'false' }, calls);const off = await withKeys({ [QUERY_BUDGET_UNIT_CONFIG_KEY]: 'chunk', [EVIDENCE_TITLES_KEY]: 'false', [QUERY_FACTS_BLOCK_KEY]: 'false', [FACT_SOURCE_PAGES_KEY]: 'false' }, calls);- expect(stable(off)).toBe(stable(unset));+ expect(stable(off)).toBe(stable(defaultsOff));});});@@ -135,10 +135,30 @@ describe('search.query_facts_block', () => {});test('on without a budget (chunk unit): unchanged', async () => {- const base = await query(PLAIN, { return_unit: 'chunk' });+ const base = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: 'false' }, () => query(PLAIN, { return_unit: 'chunk' }));const on = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: 'true' }, () => query(PLAIN, { return_unit: 'chunk' }));expect(stable(on)).toBe(stable(base));});++ test('unset: on by default, the same rows as an explicit true', async () => {+ const unset = await query(PLAIN, { token_budget: 4000, limit: 10 });+ const on = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: 'true' }, () => query(PLAIN, { token_budget: 4000, limit: 10 }));+ expect(unset.filter(r => r.result_type === 'fact').length).toBeGreaterThanOrEqual(2);+ expect(unset[0]!.result_type).toBe('fact');+ expect(stable(unset)).toBe(stable(on));+ });++ test('false (or off, 0, no) turns it off: no facts block ahead of the pages', async () => {+ for (const v of ['false', 'off', '0', 'no']) {+ const rows = await withKeys({ [QUERY_FACTS_BLOCK_KEY]: v }, () => query(PLAIN, { token_budget: 4000, limit: 10 }));+ expect(rows[0]!.result_type).not.toBe('fact');+ }+ });++ test('a config read error leaves it off (fail-closed)', async () => {+ expect(await queryFactsBlockEnabled({ getConfig: async () => { throw new Error('config unreadable'); } })).toBe(false);+ expect(await queryFactsBlockEnabled({ getConfig: async () => null })).toBe(true);+ });});describe('search.fact_source_pages', () => {diff --git a/test/search-facts-arm.test.ts b/test/search-facts-arm.test.tsindex 2ce339b5df..052ff774a3 100644--- a/test/search-facts-arm.test.ts+++ b/test/search-facts-arm.test.ts@@ -14,7 +14,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { handleToolCall } from '../src/mcp/server.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';-import { QUERY_FACTS_ARM_KEY, matchQueryFacts, queryTerms } from '../src/core/search/facts-arm.ts';+import { QUERY_FACTS_ARM_KEY, QUERY_FACTS_BLOCK_KEY, matchQueryFacts, queryTerms } 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';@@ -36,6 +36,8 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();sourceId = await newSource(engine);+ // The facts block (on by default) takes every budgeted query; this suite tests the arm it replaces.+ await engine.setConfig(QUERY_FACTS_BLOCK_KEY, 'false');for (let i = 0; i < 6; i++) {await putPage(engine, sourceId, `conversations/chat-${i}`, page('conversation', `chat ${i}`, `**User:** Notes on Forge part ${i}. By the way, the Forge offsite is booked in Santa Fe.\n\n**Assistant:** Noted.`, `date: 2025-07-0${i + 1}\n`));}diff --git a/test/search-temporal-fact-reserve.test.ts b/test/search-temporal-fact-reserve.test.tsindex fd1dfdb62e..a2e25a5f13 100644--- a/test/search-temporal-fact-reserve.test.ts+++ b/test/search-temporal-fact-reserve.test.ts@@ -14,7 +14,7 @@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 { MAX_RESERVE_ROWS, QUERY_FACTS_BLOCK_KEY, 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';@@ -41,6 +41,8 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();sourceId = await newSource(engine);+ // The facts block (on by default) takes every budgeted query; this suite tests the arm it replaces.+ await engine.setConfig(QUERY_FACTS_BLOCK_KEY, 'false');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`));}