Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): fact rows are never page-shaped: result_type "fact", fact_id and a follow_up recall call; no slug, id, type or chunk_id; page_slug only when the caller can read the entity page
garrytancb29d53f1292
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex bb3f5bf175..7d8da260b9 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -208,7 +208,7 @@ Every non-localOnly operation on the MCP surface: 144 tools across 24 areas. **S|---|---|---|---|---|| `assemble_evidence` | Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): the same windows, sections or pages `query` returns with return_unit, packed into token_budget. | read | | || `cache_stats` | Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. | admin | | |-| `query` | Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). | read | yes | |+| `query` | Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonym phrasings). | read | yes | || `rate_answer` | Rate how useful an answer's retrieved evidence was, so this brain ranks better next time (zero LLM calls). | write | | || `search` | Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. | read | yes | || `search_by_image` | Image-as-query retrieval. | read | | |diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex ea8b18b8f2..b712693895 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -304,7 +304,10 @@ Two cross-cutting seams sit around the pipeline rather than inside it:capacity only: free slots under the caller's row count, and what the pagerows leave of the token budget. A page row is never displaced. It also marksa page row `superseded_claim` when a newer fact covers its typed claim- (`src/core/search/facts-arm.ts`). No model call. In the B2 corrections suite+ (`src/core/search/facts-arm.ts`). A fact row is never page-shaped: it carries+ `result_type: "fact"`, `fact_id` and a `follow_up` recall call, no `slug` or+ `id`, and `page_slug` only when the caller can read the entity page. No model+ call. In the B2 corrections suitewith correction-dated writes it lifted forget-then-remember from 92% to 100%correct. `search.query_facts_arm=false` turns it off. Verdict and gates:`docs/eval/decisions/query-facts-arm/`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 4187a3867a..c1cd5c99e1 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` (midnight UTC renders as written, other instants in `brain.timezone`; the rule think's page dates use), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, read-policy filtered; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.-- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads active facts only (not expired, not superseded, `valid_until` not passed, audit rows excluded) under recall's read policy (source scope; remote callers get world facts with private provenance filtered) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms) or a named entity, newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`.+- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads active facts only (not expired, not superseded, `valid_until` not passed, audit rows excluded) under recall's read policy (source scope; remote callers get world facts with private provenance filtered) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms) or a named entity, newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`.- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, then the facts arm), each behind its own key (entity anchoring default off, the facts arm default on); with both off it returns the rows untouched.- `src/core/search/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`.diff --git a/docs/mcp/CHATGPT.md b/docs/mcp/CHATGPT.mdindex b646fd9d77..52510a4514 100644--- a/docs/mcp/CHATGPT.md+++ b/docs/mcp/CHATGPT.md@@ -118,7 +118,8 @@ chat: the server must expose a `search`/`fetch` tool PAIR, where every`{ id, title, text, url, metadata }`. GBrain ships both:- `search` results carry an opaque, versioned `id` identifying the hit's- source and slug alongside the native fields. `query` uses the same IDs.+ source and slug alongside the native fields. `query` uses the same IDs;+ its fact rows (`result_type: "fact"`) carry no `id` and are not fetchable.- Pass the `id` unchanged to `fetch`; do not replace it with the slug orconstruct it from the current source. `fetch` returns the OpenAI shape — `text` is thepage's full canonical markdown, `url` is a stable `gbrain://page/...`diff --git a/docs/mcp/README.md b/docs/mcp/README.mdindex 57f2e1f2fa..0317233889 100644--- a/docs/mcp/README.md+++ b/docs/mcp/README.md@@ -109,3 +109,20 @@ claim and never grants access.Say to your agent: *"Search my brain for the acme-example renewal terms andshow me every ranking field for the top result."*++### Fact rows in `query`++`query` can return saved facts as rows of their own, after the page rows and+only in slots and token budget the pages left free. A fact row is not a page.+It has `result_type: "fact"` and `fact_id`, and no `slug`, `id`, `type` or+`chunk_id`, so it can't be passed to `get_page`, `fetch` or+`assemble_evidence`. `follow_up` names the call that returns the fact:+`recall` with the fact's entity, or with a `grep` of its text when it has no+entity. `page_slug` is present only when the caller can read the entity's page;+pass it to `get_page`.++```json+{"result_type":"fact","fact_id":"412","page_slug":"companies/acme-example","follow_up":{"op":"recall","args":{"entity":"companies/acme-example"}},"title":"Saved fact about companies/acme-example","chunk_text":"Saved fact (fact; valid from 2026-09-01; provenance: user update): The billing contact for Acme Example is Bob.","score":0.42,"source_id":"default"}+```++`search.query_facts_arm=false` turns fact rows off.diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex bd65778bda..591e8a04a6 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -283,7 +283,7 @@ Replace a complete canonical Markdown page. Read get_page with include_content:t## `query`-Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged.+Hybrid search with vector + keyword + multi-query expansion. Prefer `query` for concept / synonym / landscape questions ('all the X that do Y', 'the landscape of Z') — expansion recovers synonym- and outcome-phrased matches a single embedding misses. Still top-K, and the default count when `limit` is omitted depends on the configured search mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param description); pass `limit` explicitly for a stable count regardless of mode. When the answer needs the surrounding conversation or section, pass `return_unit` ('page' / 'section' / 'window') to get that evidence in one call instead of get_page per hit; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For exhaustive enumeration use list_pages; for exact known tokens `search` is cheaper (no expansion LLM call). For personal/emotional questions ('what's going on with me', 'anything notable', 'how am I feeling'), prefer get_recent_salience, find_anomalies, or get_recent_transcripts. Semantic search returns polished pages and misses recent activity bursts. Do NOT assume words like 'crazy', 'notable', or 'big' mean impressive — they often mean difficult or emotionally charged. Rows with `result_type: "fact"` are saved facts, not pages: they have no `slug` or `id`; follow `follow_up` (a `recall` call), or pass `page_slug` to get_page when it is present.| Parameter | Type | Guidance || --- | --- | --- |diff --git a/evals/entity-anchoring/regression.ts b/evals/entity-anchoring/regression.tsindex 64203f5910..82455ac681 100644--- a/evals/entity-anchoring/regression.ts+++ b/evals/entity-anchoring/regression.ts@@ -21,10 +21,10 @@ import { loadNamedThingQuestions, seedNamedThingCorpus } from '../../test/fixturimport { RELATIONAL_QUESTIONS, seedRelationalCorpus } from '../../test/fixtures/retrieval-quality/relational/corpus.ts';const KEY = (() => { const i = process.argv.indexOf('--key'); return i >= 0 ? process.argv[i + 1]! : 'search.entity_anchoring'; })();-type Row = { slug: string; entity_anchored?: string; fact_row?: unknown };+type Row = { slug: string; entity_anchored?: string; result_type?: string };/** 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 pagesOf = (rows: Row[]) => rows.filter(r => r.result_type !== 'fact');+const fired = (rows: Row[]) => rows.some(r => r.entity_anchored || r.result_type === 'fact');const dump: Record<string, unknown> = {};async function freshEngine(): Promise<PGLiteEngine> {diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c5709daeb5..150d18bb6c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -23,7 +23,7 @@ src/core/operations.ts 341 ratchet peel target: containment sprint C4-C7; grownsrc/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 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/types.ts 2223 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); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped)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 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); 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)diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex e5d0c5fba0..1afa13c27d 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -49,7 +49,7 @@ export const LIST_PAGES_DESCRIPTION ="List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows (remote max 100); a full page may be truncated: continue with updated_after + updated_after_slug from the last row.";export const QUERY_DESCRIPTION =- "Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.";+ "Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonym phrasings). Still top-K; return_unit returns whole sections/conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; host transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows aren't pages: use follow_up. fields: \"full\" adds diagnostics.";export const SEARCH_DESCRIPTION ="Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.";diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 320213984b..2a553c45df 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -1188,7 +1188,7 @@ export function stampEvidenceSafe(results: SearchResult[]): void {}export function stampDeepResearchIds(results: SearchResult[]): void {- for (const r of results) (r as SearchResult & { id?: string }).id = encodeDeepResearchId(r.source_id, r.slug);+ for (const r of results) if (r.result_type !== 'fact') (r as SearchResult & { id?: string }).id = encodeDeepResearchId(r.source_id, r.slug);}/** T4 — shared eval-capture for the `search` op (keyword-only + cheap-hybrid paths). */diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex d09b6f6b21..02da7350e7 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -13,6 +13,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 { factRowOutput } from '../search/facts-arm.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';@@ -90,7 +91,7 @@ function searchOutput(ctx: OperationContext, p: Record<string, unknown>, resultsif (!evidence) {const output = redactRetrievalOutput(results, { ...meta, ...shown });ctx.emitResponseMeta?.('retrieval', output.meta);- return projectRows(applySnippetCap(output.results, snippetCap), rows);+ return projectRows(applySnippetCap(output.results, snippetCap).map(factRowOutput), rows);}// Evidence delivery: explicit snippet_chars wins over the delivered blocks;// otherwise the blocks are returned whole (their budget already bounds@@ -98,7 +99,7 @@ function searchOutput(ctx: OperationContext, p: Record<string, unknown>, resultsconst output = redactRetrievalOutput(results, { ...meta, delivery: evidence.delivery, ...shown });const capped = evidence.explicitSnippet ? capDeliveredSnippets(output.results, snippetCap, output.meta.delivery) : output.results;ctx.emitResponseMeta?.('retrieval', output.meta);- return projectRows(capped, rows);+ return projectRows(capped.map(factRowOutput), rows);}/** C1: the per-call row-shape escape hatch shared by `search` and `query` (`detail` is query's low/medium/high). */diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 831e2a0a21..4c64749f34 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -1038,7 +1038,7 @@ export function capDeliveredSnippets<T extends SearchResult & { delivered?: Deliconst out = results.map(r => {if (typeof r.chunk_text !== 'string' || r.chunk_text.length <= cap) return r;any = true;- const text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap);+ const text = r.chunk_text.slice(0, cap) + buildSnippetMarker(r.slug, r.chunk_text.length - cap, r.follow_up);if (!r.delivered) return { ...r, chunk_text: text };const spans = r.delivered.match_spans.filter(s => s.start < cap).map(s => ({ ...s, end: Math.min(s.end, cap) }));const lost = r.delivered.match_spans.filter(s => s.start >= cap).map(s => s.chunk_id);diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 5fbb945982..4d33554295 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -17,12 +17,13 @@* for remote callers.*/import type { BrainEngine } from '../engine.ts';-import type { SearchResult } from '../types.ts';+import type { PageReadScope, 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 { pageReadFilter } from './read-policy-sql.ts';import { enforceTokenBudget, resultTokens } from './token-budget.ts';export const QUERY_FACTS_ARM_KEY = 'search.query_facts_arm';@@ -92,11 +93,14 @@ export async function matchQueryFacts(engine: BrainEngine, query: string, scope:.slice(0, MAX_FACT_ROWS);}-function factRow(f: FactCandidate, score: number): SearchResult {+function factRow(f: FactCandidate, score: number, pageSlug: string | undefined): SearchResult {const from = day(f.valid_from);const until = day(f.valid_until);+ const args: Record<string, string> = f.entity_slug ? { entity: f.entity_slug } : { grep: f.fact.slice(0, 60) };+ if (f.source_id !== 'default') args.source_id = f.source_id;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',+ result_type: 'fact', fact_id: String(f.id), ...(pageSlug ? { page_slug: pageSlug } : {}), follow_up: { op: 'recall', args },+ 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 },@@ -126,7 +130,30 @@ async function stampSupersededClaims(engine: BrainEngine, results: SearchResult[}}+/** `source\0slug` keys of the facts' entity pages (page slug = fact entity_slug, same source) the caller may read. */+async function readableEntityPages(engine: BrainEngine, facts: FactCandidate[], scope: PageReadScope | undefined): Promise<Set<string>> {+ const slugs = [...new Set(facts.flatMap(f => f.entity_slug ? [f.entity_slug] : []))];+ if (!slugs.length) return new Set();+ const params: unknown[] = [slugs];+ const filter = pageReadFilter('p', scope, params, true);+ const rows = await engine.executeRaw<{ slug: string; source_id: string }>(`SELECT p.slug, p.source_id FROM pages p WHERE p.slug = ANY($1::text[]) AND ${filter}`, params);+ return new Set(rows.map(r => `${r.source_id}\u0000${r.slug}`));+}++/**+ * What a caller sees of a fact row: the fact, its identity and how to follow+ * it, never page fields (slug, id, type, chunk_id) that would invite get_page+ * or fetch on a page that may not exist.+ */+export function factRowOutput<T extends Partial<SearchResult>>(row: T): T {+ if (row.result_type !== 'fact') return row;+ const { slug: _slug, id: _id, type: _type, chunk_id: _chunk, page_id: _page, chunk_index: _index, chunk_source: _source, fact_row: _fact, ...rest } = row as T & { id?: string };+ return rest as T;+}+export interface FactsArmOpts extends FactsArmScope {+ /** The caller's page read policy: a fact's entity page is named (`page_slug`) only when the caller may read it. */+ readScope?: PageReadScope;tokenBudget?: number;queryEmbedding?: Float32Array | null;/** The caller's row count (explicit limit or the mode's default), read only when a fact matches. */@@ -147,7 +174,9 @@ export async function applyFactsArm(engine: BrainEngine, query: string, results:if (free <= 0) return results;const pages = results.map(r => ({ ...r }));const floor = pages.reduce((m, r) => (Number.isFinite(r.score) && r.score < m ? r.score : m), pages[0]?.score ?? 1);- let rows = facts.slice(0, free).map((f, i) => factRow(f, floor - (i + 1) * 1e-6));+ const shown = facts.slice(0, free);+ const pageSlugs = await readableEntityPages(engine, shown, opts.readScope).catch(() => new Set<string>());+ let rows = shown.map((f, i) => factRow(f, floor - (i + 1) * 1e-6, f.entity_slug && pageSlugs.has(`${f.source_id}\u0000${f.entity_slug}`) ? f.entity_slug : undefined));if (opts.tokenBudget) {let left = opts.tokenBudget - enforceTokenBudget(pages, opts.tokenBudget).meta.used;rows = rows.filter(r => { const cost = resultTokens(r); if (cost > left) return false; left -= cost; return true; });diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.tsindex 61d4b13b86..7d50aa1328 100644--- a/src/core/search/lean-rows.ts+++ b/src/core/search/lean-rows.ts@@ -27,7 +27,7 @@ const KEPT_FIELDS: ReadonlySet<string> = new Set(['id', 'slug', 'title', 'type', 'chunk_text', 'score', 'effective_date', 'source_id', 'chunk_id','evidence', 'create_safety','injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by',- 'message_id', 'thread_id', 'source_subject', 'relational',+ 'message_id', 'thread_id', 'source_subject', 'relational', 'result_type', 'fact_id', 'page_slug', 'follow_up',]);/** Explicit `fields` wins; then trusted local callers get full rows; then the transport's choice (default lean). */diff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.tsindex c17ba7a692..91b245c53c 100644--- a/src/core/search/query-arms.ts+++ b/src/core/search/query-arms.ts@@ -15,7 +15,7 @@ export async function applyQueryArms(engine: BrainEngine, p: Record<string, unknconst 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,+ sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope,tokenBudget: !scope.evidencePlan && typeof p.token_budget === 'number' ? p.token_budget : undefined,});}diff --git a/src/core/search/snippet-cap.ts b/src/core/search/snippet-cap.tsindex 02b201de8a..cf8a7e3ccf 100644--- a/src/core/search/snippet-cap.ts+++ b/src/core/search/snippet-cap.ts@@ -20,8 +20,8 @@/** Default snippet budget (chars) for subagent callers when config is unset. */export const DEFAULT_AGENT_SNIPPET_CHARS = 300;-export function buildSnippetMarker(slug: string | undefined, droppedChars: number): string {- const target = slug && slug.length > 0 ? `get_page ${slug}` : 'get_page <slug>';+export function buildSnippetMarker(slug: string | undefined, droppedChars: number, followUp?: { op: string; args: Record<string, string> }): string {+ const target = followUp ? `${followUp.op} ${JSON.stringify(followUp.args)}` : slug && slug.length > 0 ? `get_page ${slug}` : 'get_page <slug>';return `… [truncated ${droppedChars} chars — ${target} for full text]`;}@@ -31,7 +31,7 @@ export function buildSnippetMarker(slug: string | undefined, droppedChars: numbe* Returns the ORIGINAL array (same object identities) when nothing needed* truncation, so untouched paths stay allocation-free.*/-export function applySnippetCap<T extends { chunk_text?: unknown; slug?: unknown }>(+export function applySnippetCap<T extends { chunk_text?: unknown; slug?: unknown; follow_up?: { op: string; args: Record<string, string> } }>(results: T[],chars: number,): T[] {@@ -44,7 +44,7 @@ export function applySnippetCap<T extends { chunk_text?: unknown; slug?: unknownconst slug = typeof r.slug === 'string' ? r.slug : undefined;return {...r,- chunk_text: text.slice(0, chars) + buildSnippetMarker(slug, text.length - chars),+ chunk_text: text.slice(0, chars) + buildSnippetMarker(slug, text.length - chars, r.follow_up),};});return anyTruncated ? out : results;diff --git a/src/core/types.ts b/src/core/types.tsindex 3acb08149e..0b40b13b5a 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1057,6 +1057,8 @@ export interface SearchResult {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 };+ /** Fact rows only, and what callers see of them: never a page (no slug or id); follow with `follow_up`, read `page_slug` when the entity page exists. */+ result_type?: 'fact'; fact_id?: string; page_slug?: string; follow_up?: { op: 'recall'; args: Record<string, string> };/** 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 };/**diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 91f0cc6f92..3e6a45799a 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -679,7 +679,7 @@"stdout": ["Usage: gbrain query <query> [options]","",- "Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.",+ "Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonym phrasings). Still top-K; return_unit returns whole sections/conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; host transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows aren't pages: use follow_up. fields: \"full\" adds diagnostics.","","Options:"," <query> Question or topic (required unless image).",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 6cd9c860d1..f53468f780 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 210255,- "stdoutSha256": "7f7b92a191673f77ea013ad2fc77d8bb291ebd5029ec21391ca02f869de1d5da",+ "stdoutBytes": 210265,+ "stdoutSha256": "cb8cf3d2f8ef0214ac2463b42d7d5fa6a8e80709db0de845637c8906bea1efdc","toolNames": ["remember","entity",@@ -1103,7 +1103,7 @@"scope": "read"},{- "description": "Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.",+ "description": "Hybrid search plus multi-query expansion for concept/landscape questions (expansion recovers synonym phrasings). Still top-K; return_unit returns whole sections/conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no LLM call). Personal: get_recent_salience, find_anomalies; host transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows aren't pages: use follow_up. fields: \"full\" adds diagnostics.","idempotent": true,"local_only": false,"mutating": false,diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 9b13e3dbcf..5bdb0240bb 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1386,8 +1386,10 @@"evidence?: Evidence | undefined","exact_lookup?: \"title\" | \"slug\" | undefined","exact_match_boost?: number | undefined",+ "fact_id?: string | undefined","fact_row?: { id: number; valid_from: string; valid_until: string | null; } | undefined","feedback_boost?: number | undefined",+ "follow_up?: { op: \"recall\"; args: Record<string, string>; } | undefined","graph_adjacency_boost?: number | undefined","graph_adjacency_hits?: number | undefined","graph_cross_source_boost?: number | undefined",@@ -1401,6 +1403,7 @@"message_id?: string | undefined","modality?: \"image\" | \"text\" | undefined","page_id: number",+ "page_slug?: string | undefined","recency_boost?: number | undefined","relational?: RelationalEvidence | undefined","relational_hop?: number | undefined",@@ -1412,6 +1415,7 @@"rerank_score?: number | undefined","rerank_score_kind?: \"rubric\" | undefined","reranker_delta?: number | undefined",+ "result_type?: \"fact\" | undefined","salience_boost?: number | undefined","score: number","session_demote_factor?: number | undefined",@@ -3421,7 +3425,7 @@"kind": "type","name": "FactKind","signature": [- "\"event\" | \"preference\" | \"commitment\" | \"belief\" | \"fact\" | \"idea\""+ "\"fact\" | \"event\" | \"preference\" | \"commitment\" | \"belief\" | \"idea\""]},{@@ -8468,8 +8472,10 @@"evidence?: Evidence | undefined","exact_lookup?: \"title\" | \"slug\" | undefined","exact_match_boost?: number | undefined",+ "fact_id?: string | undefined","fact_row?: { id: number; valid_from: string; valid_until: string | null; } | undefined","feedback_boost?: number | undefined",+ "follow_up?: { op: \"recall\"; args: Record<string, string>; } | undefined","graph_adjacency_boost?: number | undefined","graph_adjacency_hits?: number | undefined","graph_cross_source_boost?: number | undefined",@@ -8483,6 +8489,7 @@"message_id?: string | undefined","modality?: \"image\" | \"text\" | undefined","page_id: number",+ "page_slug?: string | undefined","recency_boost?: number | undefined","relational?: RelationalEvidence | undefined","relational_hop?: number | undefined",@@ -8494,6 +8501,7 @@"rerank_score?: number | undefined","rerank_score_kind?: \"rubric\" | undefined","reranker_delta?: number | undefined",+ "result_type?: \"fact\" | undefined","salience_boost?: number | undefined","score: number","session_demote_factor?: number | undefined",diff --git a/test/search-facts-arm.test.ts b/test/search-facts-arm.test.tsindex f74fbe33da..e059b27d04 100644--- a/test/search-facts-arm.test.ts+++ b/test/search-facts-arm.test.ts@@ -49,9 +49,9 @@ describe('facts arm', () => {const unset = await query({ limit: 10 });await engine.setConfig(QUERY_FACTS_ARM_KEY, 'false');const off = await query({ limit: 10 });- expect(unset.some(r => r.fact_row)).toBe(true);- expect(off.some(r => r.fact_row)).toBe(false);- expect(JSON.stringify(unset.filter(r => !r.fact_row).map(r => [r.slug, r.chunk_text]))).toBe(JSON.stringify(off.map(r => [r.slug, r.chunk_text])));+ expect(unset.some(r => r.result_type === 'fact')).toBe(true);+ expect(off.some(r => r.result_type === 'fact')).toBe(false);+ expect(JSON.stringify(unset.filter(r => r.result_type !== 'fact').map(r => [r.slug, r.chunk_text]))).toBe(JSON.stringify(off.map(r => [r.slug, r.chunk_text])));});test('on: the matching fact is a row of its own, newest first, in free slots after every page row', async () => {@@ -62,8 +62,8 @@ describe('facts arm', () => {const on = await query({ limit: 10 });expect(on.length).toBeLessThanOrEqual(10);expect(on.slice(0, off.length).map(r => [r.slug, r.chunk_id])).toEqual(off.map(r => [r.slug, r.chunk_id]));- 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']);+ const facts = on.filter(r => r.result_type === 'fact');+ expect(facts.map(r => r.chunk_text.match(/valid from (\S+?);/)![1])).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');@@ -97,12 +97,36 @@ describe('facts arm', () => {await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');try {const rows = await query({ return_unit: 'page', token_budget: 2000, limit: 10 }) as Array<SearchResult & { delivered?: { reason?: string } }>;- const fact = rows.find(r => r.fact_row && r.chunk_text.includes('Missoula'))!;+ const fact = rows.find(r => r.result_type === 'fact' && 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, remote: a fact row is never page-shaped and never points at get_page; the entity page is named only when it exists', async () => {+ await engine.setConfig(QUERY_FACTS_ARM_KEY, 'true');+ try {+ const factRows = async () => {+ const r = await dispatchToolCall(engine, 'query', { query: Q, expand: false, limit: 10, snippet_chars: 20 }, { remote: true, transport: 'stdio', sourceId,+ auth: { token: 't', clientId: 'facts-probe', scopes: ['read'], sourceId, allowedSources: [sourceId] }, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} } });+ const text = r.content.map(c => (c as { text?: string }).text ?? '').join('\n');+ return { text, rows: (JSON.parse((r.content[0] as { text: string }).text) as Array<Record<string, unknown>>).filter(row => row.result_type === 'fact') };+ };+ const before = await factRows();+ expect(before.rows.length).toBeGreaterThan(0);+ for (const row of before.rows) {+ expect(row).toMatchObject({ result_type: 'fact', fact_id: expect.stringMatching(/^\d+$/), follow_up: { op: 'recall', args: { entity: 'forge', source_id: sourceId } } });+ for (const key of ['slug', 'id', 'type', 'chunk_id', 'page_slug', 'fact_row']) expect(row).not.toHaveProperty(key);+ expect(String(row.chunk_text)).toContain(`recall {"entity":"forge","source_id":"${sourceId}"}`);+ }+ expect(before.text).not.toContain('get_page forge');+ expect(before.text).not.toContain('get_page facts/');+ await putPage(engine, sourceId, 'forge', page('company', 'Forge', 'Forge runs an annual offsite.'));+ const after = await factRows();+ for (const row of after.rows) expect(row.page_slug).toBe('forge');+ } 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]);