Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): query facts arm behind search.query_facts_arm (default off): matching active facts as rows inside the row count and budget, superseded_claim stamps on typed claims, page-unit passthrough; gate-2 harness covers it
garrytan16288b95ca70
diff --git a/evals/entity-anchoring/regression.ts b/evals/entity-anchoring/regression.tsindex 8c2705fbb5..8d88d273cb 100644--- a/evals/entity-anchoring/regression.ts+++ b/evals/entity-anchoring/regression.ts@@ -9,7 +9,7 @@* whose questions never ask for a current state. `--dump-off <file>` writes the* key-off rows for a byte-identity check against a build without the change.*- * bun evals/entity-anchoring/regression.ts --json+ * bun evals/entity-anchoring/regression.ts --json [--key search.query_facts_arm]*/import { readFileSync, writeFileSync } from 'node:fs';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';@@ -20,8 +20,11 @@ import { haystackToPages, sessionSlug } from '../../src/eval/longmemeval/adapterimport { loadNamedThingQuestions, seedNamedThingCorpus } from '../../test/fixtures/retrieval-quality/namedthing/corpus.ts';import { RELATIONAL_QUESTIONS, seedRelationalCorpus } from '../../test/fixtures/retrieval-quality/relational/corpus.ts';-const KEY = 'search.entity_anchoring';-type Row = { slug: string; entity_anchored?: string };+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; fact_row?: unknown };+/** Page rows only: an added fact row is not a page hit for recall. */+const pagesOf = (rows: Row[]) => rows.filter(r => !r.fact_row);+const fired = (rows: Row[]) => rows.some(r => r.entity_anchored || r.fact_row);const dump: Record<string, unknown> = {};async function freshEngine(): Promise<PGLiteEngine> {@@ -46,8 +49,8 @@ async function scoreCorpus(corpus: string, engine: PGLiteEngine, questions: Namefor (const q of questions) {const on = await ranked(engine, q.query, true, corpus);const off = await ranked(engine, q.query, false, corpus);- if (on.some(x => x.entity_anchored)) r.triggered++;- const son = scoreQuestion(q, on.map(x => x.slug)), soff = scoreQuestion(q, off.map(x => x.slug));+ if (fired(on)) r.triggered++;+ const son = scoreQuestion(q, pagesOf(on).map(x => x.slug)), soff = scoreQuestion(q, pagesOf(off).map(x => x.slug));if (son.recall_at_10 < soff.recall_at_10) r.recall10_lower.push(q.query);if (son.recall_at_10 > soff.recall_at_10) r.recall10_higher++;if (soff.negative_clean === true && son.negative_clean === false) r.negative_clean_lost.push(q.query);@@ -70,8 +73,8 @@ async function longMemEval(path: string, cue: boolean): Promise<CorpusReport> {const text = cue ? `${String(q.question).replace(/[?.!\s]+$/, '')} now?` : q.question;const recall = (rows: Row[]) => gold.size ? rows.filter(x => gold.has(x.slug)).length / gold.size : 0;const rr = (rows: Row[]) => { const i = rows.findIndex(x => gold.has(x.slug)); return i < 0 ? 0 : 1 / (i + 1); };- const on = await ranked(engine, text, true, r.corpus), off = await ranked(engine, text, false, r.corpus);- if (on.some(x => x.entity_anchored)) r.triggered++;+ const on = pagesOf(await ranked(engine, text, true, r.corpus)), off = pagesOf(await ranked(engine, text, false, r.corpus));+ if (fired(await ranked(engine, text, true, `${r.corpus}#probe`))) r.triggered++;if (recall(on) < recall(off)) r.recall10_lower.push(q.question_id);if (recall(on) > recall(off)) r.recall10_higher++;r.mean_recall10.on += recall(on) / qs.length; r.mean_recall10.off += recall(off) / qs.length;@@ -96,14 +99,22 @@ 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') {+ // 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]));+ }} finally {await engine.disconnect();}}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'));- const out = { mode: 'hermetic', keyword_only: true, pass: asWritten.every(r => r.recall10_lower.length === 0), reports };+ const asWritten = reports.filter(r => !r.corpus.endsWith('+now') && !r.corpus.endsWith('+facts'));+ const out = { mode: 'hermetic', keyword_only: true, key: KEY, pass: asWritten.every(r => r.recall10_lower.length === 0), reports };const dumpPath = flag('--dump-off');if (dumpPath) writeFileSync(dumpPath, JSON.stringify(dump, null, 2));console.log(args.includes('--json') ? JSON.stringify(out, null, 2) : JSON.stringify(out));diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex e54cacf743..16a4ced3d0 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -22,8 +22,8 @@ src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live insrc/core/operations.ts 341 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line)src/core/pglite-engine.ts 2995 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)src/core/postgres-engine.ts 2932 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)-src/core/search/hybrid.ts 1586 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key-src/core/types.ts 2217 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts)+src/core/search/hybrid.ts 1587 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call+src/core/types.ts 2221 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)src/commands/init.ts 1876 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,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 1870 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; +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; +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); re-summed at the master c9ba7782 merge (1860 integration + 1864 master - 1856 base); +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 #5984 lanes: sync.lanes key registration; re-summed at the master 5184ba964 merge (1869 integration + 1865 master - 1864 base)+src/core/config.ts 1871 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; +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; +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); re-summed at the master c9ba7782 merge (1860 integration + 1864 master - 1856 base); +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 #5984 lanes: sync.lanes key registration; re-summed at the master 5184ba964 merge (1869 integration + 1865 master - 1864 base); +1 search.query_facts_arm 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 cf5705d0b9..fd67c6db93 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1381,6 +1381,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.return_budget_max_remote','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 (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 c8836bee86..d09b6f6b21 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -12,6 +12,7 @@ import { readHolders } from './context.ts';import { hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from '../search/hybrid.ts';import { anchorOpResults } from '../search/entity-anchor.ts';+import { applyQueryArms } from '../search/query-arms.ts';import { resolveSearchDateBounds } from '../search/date-bounds.ts';import { loadSearchModeConfig, resolveSearchMode, SOURCE_BOOSTS_KEY } from '../search/mode.ts';import { looksConceptShaped, classifyQueryShape } from '../search/query-intent.ts';@@ -421,7 +422,9 @@ async function buildRetrievalResponseMeta(excludeSlugPrefixes,});const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);- const savedFacts = await matchingSavedFacts(ctx, scope, queryText, aliases);+ // A fact the facts arm already returned as a row is not repeated beside the blocks.+ const factRowIds = new Set((results as SearchResult[]).flatMap(r => r.fact_row ? [r.fact_row.id] : []));+ const savedFacts = (await matchingSavedFacts(ctx, scope, queryText, aliases)).filter(f => !factRowIds.has(f.id));const heldFiles = await stampHeldHits(ctx.engine, results as SearchResult[], scope, ctx).catch(() => []);const heldNotice = heldFilesNotice(heldFiles, ctx.remote !== false);if (heldNotice) ctx.emitNotice?.(heldNotice);@@ -823,7 +826,7 @@ const query: Operation = {// cross-source mode (matches SearchOpts.sourceId contract).const typeFilter = await reconcileTypeFilter(ctx, querySourceScope, excludePrivate, types);types = typeFilter.types;- let capturedMeta: HybridSearchMeta | null = null;+ let capturedMeta: HybridSearchMeta | null = null; let queryEmbedding: Float32Array | null = null;// v0.32.x search-lite: route the query op through hybridSearchCached so// token budget and intent weighting apply at the operation boundary.// Semantic cache reuse is suspended in the wrapper.@@ -865,7 +868,7 @@ const query: Operation = {intentWeighting: typeof p.intent_weighting === 'boolean' ? (p.intent_weighting as boolean) : undefined,// v0.36 cross-modal routing param.crossModal: p.cross_modal as 'text' | 'image' | 'both' | 'auto' | undefined,- onMeta: (m) => { capturedMeta = m; },+ onMeta: (m) => { capturedMeta = m; }, onQueryEmbedding: (e) => { queryEmbedding = e; },// v0.36 (D15): per-call embedding column override. Resolver rejects// unknown names at hybrid entry with EmbeddingColumnNotRegisteredError;// the error surfaces back to the agent as the op error envelope.@@ -883,10 +886,10 @@ const query: Operation = {relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,});const declarations = new DeclarationMemo();- results = await anchorOpResults(ctx.engine, p, queryText, await withDeclaredNameFanOut(results, queryText, declarations, (alt, altLimit) => hybridSearchCached(ctx.engine, alt, {+ 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 });+ })), { ...querySourceScope, excludePrivate, requireSafeChunks: ctx.remote !== false, filtered: !!types, evidencePlan: !!plan, 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 d0c8295060..831e2a0a21 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -34,7 +34,7 @@ import { sanitizeRemoteBody } from '../remote-body.ts';import { credentialSafeProjection } from '../credential-projection.ts';import { stripChunkHeader } from '../chunkers/code.ts';import { OperationError } from '../ops/contract.ts';-import { evidenceDateHeaderEnabled, loadPageDateHeaders, pageDateHeader } from './evidence-date.ts';+import { evidenceDateHeaderEnabled, factDateHeader, loadPageDateHeaders, pageDateHeader } from './evidence-date.ts';export const RETURN_UNITS = ['chunk', 'window', 'section', 'page', 'auto'] as const;export type ReturnUnit = typeof RETURN_UNITS[number];@@ -68,7 +68,7 @@ export interface MatchSpan { chunk_id: number; start: number; end: number }* a conversation whose matching span no longer fits the budget keeps its* ranked chunks too.*/-export type AutoReason = 'conversation_type' | 'conversation_slug' | 'not_conversation' | 'conversation_over_budget';+export type AutoReason = 'conversation_type' | 'conversation_slug' | 'not_conversation' | 'conversation_over_budget' | 'saved_fact';export interface DeliveredEvidence {unit: DeliveredUnit;@@ -855,6 +855,8 @@ export async function deliverEvidence(const groups: Group[] = [];const byPage = new Map<number, Group>();hits.forEach((h, rank) => {+ // A saved-fact row (facts arm) has no page to expand: it is delivered as written, paid for first.+ if (h.fact_row) { passthrough.push({ rank, hit: h, reason: 'saved_fact' }); return; }const signal = auto ? conversationSignal(h) : null;if (auto && !signal) { passthrough.push({ rank, hit: h, reason: 'not_conversation' }); return; }const id = Number.isFinite(h.page_id) ? h.page_id : null;@@ -907,7 +909,8 @@ export async function deliverEvidence(fallbacks.add('date_header_unavailable');}}- const headerFor = (hit: SearchResult): string => dateHeaders ? `${dateHeaders.get(hit.page_id) ?? pageDateHeader(null)}\n` : '';+ const headerFor = (hit: SearchResult): string => !dateHeaders ? ''+ : hit.fact_row ? `${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.tsnew file mode 100644index 0000000000..80c3e2c183--- /dev/null+++ b/src/core/search/facts-arm.ts@@ -0,0 +1,168 @@+/**+ * Facts arm for `query` (`search.query_facts_arm`, default off; gates in+ * docs/eval/decisions/query-facts-arm/). A correction saved with `remember`+ * lives in the facts table, which page search never ranks, so the stale page+ * text answers instead. With the key on, `query` adds the active facts that+ * match the question as rows of their own, inside the caller's row count and+ * token budget, and stamps a page row `superseded_claim` when a newer active+ * fact covers the same entity and typed claim slot as a fact taken from that+ * page.+ *+ * Matching: query terms against the fact text and entity (at least half of+ * the content terms), cosine against the query embedding hybrid search+ * already computed (no extra model call; skipped when there is none), and the+ * facts of the one entity page the query names. Matches are ordered newest+ * valid_from first. Read policy is recall's: source scope, active rows only,+ * audit rows excluded, and world-visible facts with non-private provenance+ * for remote callers.+ */+import type { BrainEngine } from '../engine.ts';+import type { SearchResult } from '../types.ts';+import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';+import { getFtsLanguage } from '../fts-language.ts';+import { getEmbeddingModel } from '../ai/gateway.ts';+import { privateProvenanceFilterFragment } from './private-visibility.ts';+import { namedEntity } from './entity-anchor.ts';+import { enforceTokenBudget } from './token-budget.ts';++export const QUERY_FACTS_ARM_KEY = 'search.query_facts_arm';+/** Fact rows added per query at most. */+export const MAX_FACT_ROWS = 3;+/** Cosine similarity a fact needs against the query embedding to count as a match on its own. */+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;++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']);++export interface FactsArmScope { sourceId?: string; sourceIds?: string[]; remote: boolean }++interface 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;+}++export function queryTerms(query: string): string[] {+ return [...new Set(query.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}'-]+/gu) ?? [])].filter(t => t.length >= 3 && !STOPWORDS.has(t)).slice(0, 12);+}++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[]> {+ 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 NULL+ AND (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>();+ 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)+ SELECT ${cols}, lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) AS haystack+ FROM facts f, q WHERE ${base} AND q.q IS NOT NULL+ AND to_tsvector($3::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' ')) @@ q.q+ ORDER BY ts_rank_cd(to_tsvector($3::regconfig, f.fact || ' ' || replace(COALESCE(f.entity_slug, ''), '-', ' ')), q.q) DESC, f.valid_from DESC+ LIMIT 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);+ }+ if (queryEmbedding && queryEmbedding.length) {+ const model = getEmbeddingModel();+ const lit = `[${Array.from(queryEmbedding).join(',')}]`;+ const rows = await engine.executeRaw<FactCandidate & { similarity: number }>(+ `SELECT ${cols}, 1 - (f.embedding <=> $3::vector) AS similarity FROM facts f+ WHERE ${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);+ }+ 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}`,+ [...params, entity.slug]);+ for (const r of rows) found.set(Number(r.id), r);+ }+ return [...found.values()]+ .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);+}++function factRow(f: FactCandidate, score: number): SearchResult {+ const from = day(f.valid_from);+ const until = day(f.valid_until);+ return {+ slug: f.entity_slug ?? `facts/${f.id}`, page_id: 0, title: f.entity_slug ? `Saved fact about ${f.entity_slug}` : 'Saved fact', type: 'note',+ chunk_text: `Saved fact (${f.kind}; valid from ${from ?? 'unknown'}${until ? ` to ${until}` : ''}; provenance: ${f.source}): ${f.fact}`,+ chunk_source: 'compiled_truth', chunk_id: -Number(f.id), chunk_index: 0, score, stale: false, source_id: f.source_id,+ fact_row: { id: Number(f.id), valid_from: new Date(f.valid_from).toISOString(), valid_until: f.valid_until ? new Date(f.valid_until).toISOString() : null },+ } as SearchResult;+}++/**+ * Stamp `superseded_claim` on page rows whose page is the source of an older+ * fact for the same entity and typed claim slot as a newer matched fact.+ * Untyped claims are never compared.+ */+async function stampSupersededClaims(engine: BrainEngine, results: SearchResult[], facts: FactCandidate[]): Promise<void> {+ const typed = facts.filter(f => f.entity_slug && f.claim_metric);+ const pages = results.filter(r => !r.fact_row && r.slug);+ if (!typed.length || !pages.length) return;+ const rows = await engine.executeRaw<{ id: number; source_markdown_slug: string; source_id: string; entity_slug: string; claim_metric: string; claim_period: string | null; valid_from: Date | string }>(+ `SELECT f.id, f.source_markdown_slug, f.source_id, f.entity_slug, f.claim_metric, f.claim_period, f.valid_from FROM facts f+ WHERE f.source_markdown_slug = ANY($1::text[]) AND f.entity_slug = ANY($2::text[]) AND f.claim_metric IS NOT NULL`,+ [[...new Set(pages.map(r => r.slug))], [...new Set(typed.map(f => f.entity_slug!))]]);+ for (const r of pages) {+ for (const old of rows.filter(o => o.source_markdown_slug === r.slug && o.source_id === (r.source_id ?? o.source_id))) {+ const newer = typed.find(f => f.entity_slug === old.entity_slug && f.claim_metric === old.claim_metric+ && (!f.claim_period || !old.claim_period || f.claim_period === old.claim_period)+ && Number(f.id) !== Number(old.id) && new Date(f.valid_from).getTime() > new Date(old.valid_from).getTime());+ if (newer) { r.superseded_claim = { fact_id: Number(newer.id), valid_from: new Date(newer.valid_from).toISOString() }; break; }+ }+ }+}++export interface FactsArmOpts extends FactsArmScope {+ tokenBudget?: number;+ queryEmbedding?: Float32Array | null;+ /** The caller's row count (explicit limit or the mode's default), read only when a fact matches. */+ rowCap?: () => Promise<number>;+}++/**+ * The facts arm: matched facts appended as rows (in free slots, else the+ * last ones, so the row count never grows), superseded page claims stamped,+ * and the token budget re-applied. No match or any error: the results unchanged.+ */+export async function applyFactsArm(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts): Promise<SearchResult[]> {+ try {+ const facts = await matchQueryFacts(engine, query, opts, opts.queryEmbedding);+ if (!facts.length) return results;+ // Facts fill free slots first; they displace the lowest page rows only when the pages already fill the row count.+ const rowCount = Math.max(results.length, (await opts.rowCap?.().catch(() => 0)) ?? 0, facts.length);+ let pages = results.slice(0, Math.min(results.length, rowCount - facts.length)).map(r => ({ ...r }));+ const floor = pages.reduce((m, r) => (Number.isFinite(r.score) && r.score < m ? r.score : m), pages[0]?.score ?? 1);+ const rows = facts.map((f, i) => factRow(f, floor - (i + 1) * 1e-6));+ // Facts are paid for first inside the budget; the pages share the rest.+ if (opts.tokenBudget) pages = enforceTokenBudget(pages, Math.max(1, opts.tokenBudget - enforceTokenBudget(rows, opts.tokenBudget).meta.used)).results;+ const merged = [...pages, ...rows];+ await stampSupersededClaims(engine, merged, facts).catch(() => undefined);+ return merged;+ } catch {+ return results;+ }+}++/** `search.query_facts_arm` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */+export async function queryFactsArmEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {+ try {+ const raw = (await engine.getConfig(QUERY_FACTS_ARM_KEY))?.trim().toLowerCase();+ return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';+ } catch {+ return false;+ }+}diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 7a8602f190..b42676fe62 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -958,6 +958,8 @@ export interface HybridSearchOpts extends SearchOpts {* seam cannot poison `query_cache` for production queries.*/queryEmbedFn?: (text: string) => Float32Array | Promise<Float32Array>;+ /** Receives the text query embedding the vector arm used (not called on keyword-only or cached paths). */+ onQueryEmbedding?: (embedding: Float32Array) => void;/*** INTERNAL — cache-consult outcome threaded from `hybridSearchCached` into@@ -1111,6 +1113,7 @@ export async function hybridSearch(const { effectiveModality, unifiedRouting, queries } = await resolveModalityAndQueries(req);const { vectorArms, queryEmbedding, imageQueryEmbedding, unifiedDone } =await runVectorArms(req, { effectiveModality, unifiedRouting, queries, multimodalProviderProbe });+ if (queryEmbedding) opts?.onQueryEmbedding?.(queryEmbedding);if (vectorArms.length === 0) {return searchVectorFallback(req, lexical, relationalList, postFusionOpts);}diff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.tsnew file mode 100644index 0000000000..86c12b5ed4--- /dev/null+++ b/src/core/search/query-arms.ts@@ -0,0 +1,21 @@+/**+ * The `query` op's opt-in arms, applied after hybrid search and the+ * declared-name fan-out, before the CRAG grade: entity anchoring+ * (`search.entity_anchoring`, search/entity-anchor.ts) and then the facts arm+ * (`search.query_facts_arm`, search/facts-arm.ts). Both default off; with+ * both 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';++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[]> {+ 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,+ tokenBudget: !scope.evidencePlan && typeof p.token_budget === 'number' ? p.token_budget : undefined,+ });+}diff --git a/src/core/types.ts b/src/core/types.tsindex d213baa34f..3acb08149e 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1055,6 +1055,10 @@ export interface SearchResult {* entity's page, or a page that links to it or names it (newest first).*/entity_anchored?: 'entity' | 'linked';+ /** Set on a saved-fact row the `search.query_facts_arm` arm added (search/facts-arm.ts); page_id is 0. */+ fact_row?: { id: number; valid_from: string; valid_until: string | null };+ /** A newer active fact covers the same entity and typed claim slot as a fact taken from this page. */+ superseded_claim?: { fact_id: number; valid_from: string };/*** T4 — the strongest signal that surfaced this page (alias_hit >* exact_title_match > high_vector_match > keyword_exact > weak_semantic).diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex 2c15bf671d..c58ca580db 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -42,6 +42,7 @@ const DIRECTLY_READ_SINGLETONS = ['search.return_budget_max_remote','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)];describe('KNOWN_CONFIG_KEYS search.* rows mirror what the code reads (#4605)', () => {diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex a9ee4d0b44..ccf94cd6fe 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1386,6 +1386,7 @@"evidence?: Evidence | undefined","exact_lookup?: \"title\" | \"slug\" | undefined","exact_match_boost?: number | undefined",+ "fact_row?: { id: number; valid_from: string; valid_until: string | null; } | undefined","feedback_boost?: number | undefined","graph_adjacency_boost?: number | undefined","graph_adjacency_hits?: number | undefined",@@ -1422,6 +1423,7 @@"supersede_penalty?: number | undefined","superseded?: boolean | undefined","superseded_by?: string | undefined",+ "superseded_claim?: { fact_id: number; valid_from: string; } | undefined","thread_id?: string | undefined","title: string","title_match_boost?: number | undefined",@@ -6422,7 +6424,7 @@"kind": "type","name": "AutoReason","signature": [- "\"conversation_type\" | \"conversation_slug\" | \"not_conversation\" | \"conversation_over_budget\""+ "\"conversation_type\" | \"conversation_slug\" | \"not_conversation\" | \"conversation_over_budget\" | \"saved_fact\""]},{@@ -6875,6 +6877,7 @@"nearSymbol?: string | undefined","offset?: number | undefined","onMeta?: ((meta: HybridSearchMeta) => void) | undefined",+ "onQueryEmbedding?: ((embedding: Float32Array) => void) | undefined","onRelationalMeta?: ((meta: RelationalArmMeta) => void) | undefined","onRerankPool?: ((pool: readonly SearchResult[], preRerank: readonly SearchResult[]) => void) | undefined","onVectorPoolMeta?: ((m: VectorPoolMeta) => void) | undefined",@@ -8388,6 +8391,7 @@"evidence?: Evidence | undefined","exact_lookup?: \"title\" | \"slug\" | undefined","exact_match_boost?: number | undefined",+ "fact_row?: { id: number; valid_from: string; valid_until: string | null; } | undefined","feedback_boost?: number | undefined","graph_adjacency_boost?: number | undefined","graph_adjacency_hits?: number | undefined",@@ -8424,6 +8428,7 @@"supersede_penalty?: number | undefined","superseded?: boolean | undefined","superseded_by?: string | undefined",+ "superseded_claim?: { fact_id: number; valid_from: string; } | undefined","thread_id?: string | undefined","title: string","title_match_boost?: number | undefined",diff --git a/test/search-facts-arm.test.ts b/test/search-facts-arm.test.tsnew file mode 100644index 0000000000..d936b50301--- /dev/null+++ b/test/search-facts-arm.test.ts@@ -0,0 +1,101 @@+/**+ * Facts arm for `query` (`search.query_facts_arm`, search/facts-arm.ts): with+ * the key on, an active fact that matches the question comes back as a row of+ * its own inside the row count and budget; a remote caller never sees a+ * private fact; page-unit delivery passes the fact row through as written;+ * a page whose typed claim a newer fact covers is stamped superseded_claim;+ * with the key off the rows are unchanged. PGLite, keyword-only, no network.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { handleToolCall } from '../src/mcp/server.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { QUERY_FACTS_ARM_KEY, matchQueryFacts, queryTerms } from '../src/core/search/facts-arm.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 Q = 'Where is the Forge offsite booked?';+const query = async (params: Record<string, unknown> = {}) => await handleToolCall(engine, 'query', { query: Q, expand: false, use_cache: false, source_id: sourceId, limit: 6, ...params }) as SearchResult[];+const remote = async (params: Record<string, unknown>) => {+ const auth = { token: 't', clientId: 'facts-probe', scopes: ['read'], sourceId, allowedSources: [sourceId] };+ const r = await dispatchToolCall(engine, 'query', { query: Q, expand: false, limit: 6, ...params }, { remote: true, transport: 'stdio', sourceId, auth, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} } });+ return r.content.map(c => (c as { text?: string }).text ?? '').join('\n');+};++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ sourceId = await newSource(engine);+ for (let i = 0; i < 6; i++) {+ await putPage(engine, sourceId, `conversations/chat-${i}`, page('conversation', `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`));+ }+ await engine.insertFact({ fact: 'The Forge offsite is booked in Missoula.', kind: 'fact', entity_slug: 'forge', source: 'user correction, 2025-07-12', visibility: 'world', valid_from: new Date('2025-07-12T00:00:00Z') }, { source_id: sourceId });+ await engine.insertFact({ fact: 'The Forge offsite budget is a secret.', kind: 'fact', entity_slug: 'forge', source: 'private note', visibility: 'private', valid_from: new Date('2025-07-13T00:00:00Z') }, { source_id: sourceId });+}, 120_000);+afterAll(async () => { await engine?.disconnect(); }, 60_000);++describe('facts arm', () => {+ test('query terms drop stopwords and short words', () => {+ expect(queryTerms(Q)).toEqual(['forge', 'offsite', 'booked']);+ });++ test('off (unset or false): no fact rows, rows unchanged', async () => {+ const unset = await query();+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false');+ const off = await query();+ expect(JSON.stringify(off.map(r => [r.slug, r.chunk_text]))).toBe(JSON.stringify(unset.map(r => [r.slug, r.chunk_text])));+ expect(unset.some(r => r.fact_row)).toBe(false);+ });++ test('on: the matching fact is a row of its own, newest first, inside the same row count', async () => {+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false');+ const off = await query();+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');+ try {+ const on = await query();+ expect(on).toHaveLength(off.length);+ const facts = on.filter(r => r.fact_row);+ expect(facts.map(r => r.fact_row!.valid_from.slice(0, 10))).toEqual(['2025-07-13', '2025-07-12']);+ expect(facts[1]!.chunk_text).toContain('Missoula');+ expect(facts[1]!.chunk_text).toContain('valid from 2025-07-12');+ expect(facts[0]!.chunk_text).toContain('secret');+ } finally { await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false'); }+ });++ test('on, remote: a private fact never comes back; the world fact does', async () => {+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');+ try {+ const text = await remote({});+ expect(text).toContain('Missoula');+ expect(text).not.toContain('secret');+ expect(await matchQueryFacts(engine, Q, { sourceIds: [sourceId], remote: true })).toHaveLength(1);+ } finally { await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false'); }+ });++ test('on, return_unit page: the fact row passes through as written and counts in the budget', async () => {+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');+ try {+ const rows = await query({ return_unit: 'page', token_budget: 2000 }) as Array<SearchResult & { delivered?: { reason?: string } }>;+ const fact = rows.find(r => r.fact_row && r.chunk_text.includes('Missoula'))!;+ expect(fact.delivered?.reason).toBe('saved_fact');+ expect(fact.chunk_text.startsWith('Saved fact')).toBe(true);+ } finally { await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false'); }+ });++ test('on: a page whose typed claim a newer fact covers is stamped superseded_claim; untyped pages are not', async () => {+ const old = await engine.insertFact({ fact: 'Forge offsite city is Santa Fe', kind: 'fact', entity_slug: 'forge', source: 'extracted', visibility: 'world', valid_from: new Date('2025-07-01T00:00:00Z') }, { source_id: sourceId });+ await engine.executeRaw(`UPDATE facts SET source_markdown_slug = 'conversations/chat-0', claim_metric = 'offsite_city', expired_at = now() WHERE id = $1`, [old.id]);+ const newer = await engine.insertFact({ fact: 'The Forge offsite city is now Missoula, booked last week', kind: 'fact', entity_slug: 'forge', source: 'user correction', visibility: 'world', valid_from: new Date('2025-07-14T00:00:00Z') }, { source_id: sourceId });+ await engine.executeRaw(`UPDATE facts SET claim_metric = 'offsite_city' WHERE id = $1`, [newer.id]);+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');+ try {+ const rows = await query({ limit: 10 });+ const stamped = rows.filter(r => r.superseded_claim);+ expect(stamped.map(r => r.slug)).toEqual(['conversations/chat-0']);+ expect(stamped[0]!.superseded_claim!.fact_id).toBe(newer.id);+ } finally { await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false'); }+ });+});