Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): rank gbrain-generated pages below primary records for the same entity

garrytan4cd3c91e1944
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index c03f2ec2f4..62a5d5b8c5 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -15,6 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain.
- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.
+- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.
- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 10495da62d..ed8162a6a4 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -23,7 +23,7 @@ src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown
src/core/pglite-engine.ts 3007 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); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out); +10 Cat 40 Hard F2: countKeywordPages + searchKeywordPages delegates (SQL in engine-sql/keyword-pages.ts) and their imports
src/core/postgres-engine.ts 2952 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); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +1 cat40 hard wave F1.6: SearchOpts.rankQuery ranks keyword score by a separate query (alias fan-out); +10 Cat 40 Hard F2: countKeywordPages + searchKeywordPages delegates (SQL in engine-sql/keyword-pages.ts) and their imports
src/core/search/hybrid.ts 1615 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; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
-src/core/types.ts 2246 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +4 cat40 hard wave F1.6: SearchOpts.rankQuery and SearchResult.matched_alias; +3 Cat 40 Hard F2: keyword_count_unavailable degraded stage, SearchResult.evidence_omitted
+src/core/types.ts 2248 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +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 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +4 cat40 hard wave F1.6: SearchOpts.rankQuery and SearchResult.matched_alias; +3 Cat 40 Hard F2: keyword_count_unavailable degraded stage, SearchResult.evidence_omitted; +2 cat40 hard wave F3: SearchResult.provenance/generated_demotion
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/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 4d68fdc178..0ba558a5a4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -295,6 +295,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.105.0', text: 'Pages that name the same subject under different title prefixes ("Account sheet: X" and "CRM record: X") are shown as identity siblings on the entity card, never merged; a name both claim now links mentions to each of them instead of to neither. Frontmatter `identity: separate` or `gbrain config set mentions.sibling_merge false` keeps pages apart.' },
{ since: '0.60.105.0', text: 'The entity card gains `aka_sources`, `identity_siblings`, `identity_excerpt` (verbatim lines that may name the entity otherwise) and `alias_guidance`; `aka` is unchanged. search and query also search every other name of the entity a query names (up to 4, keyword-only, rows marked `matched_alias`); `gbrain config set search.alias_fanout_max 0` turns that off.' },
{ since: '0.60.105.0', text: 'search now says how many pages match the query\'s keywords (`keyword_total`, up to 10000+) and adds one line after the rows saying they are a ranked top-K. `match: "keyword"` lists every keyword match with `total`, `truncated` and a ready-to-send `next`. An agent-facing `mode` is now refused (it was ignored) with a fix naming `match: "keyword"`, and an offset over 10,000 is refused.' },
+ { since: '0.60.105.0', text: 'search and query rank a page gbrain generated (frontmatter `dream_generated: true`, type `extract_receipt`) at half its score when the query names an entity and a primary record about it is among the results; such rows carry `provenance: "generated"`. Generated corrections are never demoted. `gbrain config set search.demote_generated false` turns the demotion off.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index af5ca995d6..2f6b8d3f44 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -3,6 +3,7 @@
* Each stage reads the resolved request (HybridRequest, request.ts) and
* writes its per-request accumulators only as `req.<field>`.
*/
+import { applyGeneratedDemotion } from '../provenance-demotion.ts';
import { normalizeChainSlots } from '../relational-chain.ts';
import type { BrainEngine } from '../../engine.ts';
import { perArmPoolLimit } from '../eval-pool-depth.ts';
@@ -305,6 +306,7 @@ export async function resolveHybridRequest(
// shared by the fused path and both keyword-only paths. Caller re-sorts.
export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult[]): Promise<void> {
const { engine, query, opts, suggestions, intentWeightingOn, intentWeights, resolvedMode } = req;
+ await applyGeneratedDemotion(engine, list, query, { sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate });
if (intentWeights.exactMatchBoost === 1.0) {
// #4694: general and temporal questions still honor a multi-token
// title that is the query's subject. Not concept intent (Cat 13: a
diff --git a/src/core/search/provenance-demotion.ts b/src/core/search/provenance-demotion.ts
new file mode 100644
index 0000000000..6e046290ed
--- /dev/null
+++ b/src/core/search/provenance-demotion.ts
@@ -0,0 +1,75 @@
+/**
+ * Provenance-aware ranking: a page gbrain itself generated ranks below a
+ * primary record about the same entity that matches the same query, because a
+ * summary is not evidence.
+ *
+ * Generated means a gbrain-owned marker only: frontmatter `dream_generated:
+ * true` (dream synthesis output) or `type: extract_receipt`. Every such row is
+ * stamped `provenance: "generated"`. It is demoted (score x GENERATED_FACTOR)
+ * only when the query names an entity (search/alias-fanout.ts
+ * `resolveQueryEntity`), the generated page links to that entity, and a
+ * non-generated row in the same pool is the entity page or links to it. A
+ * generated page recording a correction (frontmatter `supersedes` or
+ * `corrects`, or a facts-fence row with a `valid_until`) is never demoted, and
+ * facts saved with `remember` are not pages, so nothing here touches them.
+ *
+ * Runs in the identity-boost stage (hybrid/request.ts `applyIdentityBoosts`):
+ * after fusion and the metadata boosts, before reranking and before the pool
+ * is cut. `search.demote_generated=false` turns demotion off (rows are still
+ * stamped). Fail-soft: any error leaves scores unchanged.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { SearchResult } from '../types.ts';
+import { parseFactsFence } from '../facts-fence.ts';
+import { resolveQueryEntity } from './alias-fanout.ts';
+
+export const GENERATED_FACTOR = 0.5;
+
+const isOff = (v: string | null) => v != null && ['false', '0', 'no', 'off'].includes(v.trim().toLowerCase());
+
+/** Whether a generated page records a correction (never demoted). */
+export function recordsCorrection(frontmatter: Record<string, unknown> | null, body: string | null): boolean {
+ if (frontmatter && (frontmatter.supersedes != null || frontmatter.corrects != null)) return true;
+ try {
+ return parseFactsFence(body ?? '').facts.some(f => !!f.validUntil);
+ } catch {
+ return false;
+ }
+}
+
+export async function applyGeneratedDemotion(engine: BrainEngine, list: SearchResult[], query: string,
+ scope: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<void> {
+ try {
+ const ids = [...new Set(list.map(r => r.page_id).filter((id): id is number => typeof id === 'number'))];
+ if (!ids.length) return;
+ const generated = await engine.executeRaw<{ id: number; frontmatter: Record<string, unknown> | null; compiled_truth: string | null }>(
+ `SELECT id, frontmatter, compiled_truth FROM pages
+ WHERE id = ANY($1::int[]) AND (frontmatter->>'dream_generated' = 'true' OR type = 'extract_receipt')`, [ids]);
+ if (!generated.length) return;
+ const generatedIds = new Set(generated.map(g => Number(g.id)));
+ for (const r of list) if (generatedIds.has(r.page_id)) r.provenance = 'generated';
+ if (isOff(await engine.getConfig('search.demote_generated'))) return;
+ const demotable = new Set(generated.filter(g => !recordsCorrection(g.frontmatter, g.compiled_truth)).map(g => Number(g.id)));
+ if (!demotable.size) return;
+ const entity = await resolveQueryEntity(engine, query, { ...scope, excludePrivate: scope.excludePrivate ?? true });
+ if (!entity) return;
+ const targets = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE deleted_at IS NULL AND (source_id, slug) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,
+ [entity.pages.map(p => p.source_id), entity.pages.map(p => p.slug)]);
+ const targetIds = targets.map(t => Number(t.id));
+ if (!targetIds.length) return;
+ const linking = new Set((await engine.executeRaw<{ id: number }>(
+ `SELECT DISTINCT from_page_id AS id FROM links WHERE from_page_id = ANY($1::int[]) AND to_page_id = ANY($2::int[])`,
+ [ids, targetIds])).map(r => Number(r.id)));
+ const primaryPresent = list.some(r => !generatedIds.has(r.page_id) && (targetIds.includes(r.page_id) || linking.has(r.page_id)));
+ if (!primaryPresent) return;
+ for (const r of list) {
+ if (!demotable.has(r.page_id) || !linking.has(r.page_id)) continue;
+ r.score *= GENERATED_FACTOR;
+ r.generated_demotion = GENERATED_FACTOR;
+ }
+ } catch {
+ /* ranking-only: never break the search */
+ }
+}
diff --git a/src/core/types.ts b/src/core/types.ts
index c139be3f28..562b35cccf 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -848,6 +848,8 @@ export interface SearchResult {
matched_alias?: string;
/** `search` `match: "keyword"`: an enumerated page whose text did not fit the evidence budget keeps its row, without text. */
evidence_omitted?: boolean;
+ /** `generated` on pages gbrain wrote (dream_generated, extract_receipt); `generated_demotion` when ranked below a primary record (search/provenance-demotion.ts). */
+ provenance?: 'generated'; generated_demotion?: number;
/**
* Extraction quarantine lane (issue #160): true when the result's page is
* an unverified auto-extracted entity stub (frontmatter
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index d0e2cc9926..ff422c4e88 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1407,6 +1407,7 @@
"exact_lookup?: \"title\" | \"slug\" | undefined",
"exact_match_boost?: number | undefined",
"feedback_boost?: number | undefined",
+ "generated_demotion?: number | undefined",
"graph_adjacency_boost?: number | undefined",
"graph_adjacency_hits?: number | undefined",
"graph_cross_source_boost?: number | undefined",
@@ -1421,6 +1422,7 @@
"message_id?: string | undefined",
"modality?: \"image\" | \"text\" | undefined",
"page_id: number",
+ "provenance?: \"generated\" | undefined",
"recency_boost?: number | undefined",
"relational?: RelationalEvidence | undefined",
"relational_hop?: number | undefined",
@@ -8566,6 +8568,7 @@
"exact_lookup?: \"title\" | \"slug\" | undefined",
"exact_match_boost?: number | undefined",
"feedback_boost?: number | undefined",
+ "generated_demotion?: number | undefined",
"graph_adjacency_boost?: number | undefined",
"graph_adjacency_hits?: number | undefined",
"graph_cross_source_boost?: number | undefined",
@@ -8580,6 +8583,7 @@
"message_id?: string | undefined",
"modality?: \"image\" | \"text\" | undefined",
"page_id: number",
+ "provenance?: \"generated\" | undefined",
"recency_boost?: number | undefined",
"relational?: RelationalEvidence | undefined",
"relational_hop?: number | undefined",
diff --git a/test/search-provenance-demotion.test.ts b/test/search-provenance-demotion.test.ts
new file mode 100644
index 0000000000..bfd4c1ee21
--- /dev/null
+++ b/test/search-provenance-demotion.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Provenance-aware ranking (Cat 40 Hard fix wave, F3): pages gbrain generated
+ * (frontmatter `dream_generated: true`, `type: extract_receipt`) rank below a
+ * primary record about the same entity that matches the same query, and only
+ * then; corrections are never demoted.
+ *
+ * Protects: an auto-generated summary outranking the account's own record for
+ * a question about that account; a human-authored page, a generated page with
+ * no competing record, and a generated correction keep their scores.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { applyGeneratedDemotion, GENERATED_FACTOR, recordsCorrection } from '../src/core/search/provenance-demotion.ts';
+import { mentionBrain, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+async function put(slug: string, type: string, title: string, body: string, fm: Record<string, unknown> = {}) {
+ await importFromContent(engine, slug, serializeMarkdown(fm, body, '', { type, title, tags: [] }), { noEmbed: true, forceRechunk: true });
+}
+async function rows(slugs: string[]): Promise<SearchResult[]> {
+ const r = await engine.executeRaw<{ id: number; slug: string; source_id: string }>('SELECT id, slug, source_id FROM pages WHERE slug = ANY($1::text[])', [slugs]);
+ return slugs.map(s => { const p = r.find(x => x.slug === s)!; return { slug: s, page_id: Number(p.id), source_id: p.source_id, score: 1, title: s, type: 'note', chunk_text: '', chunk_source: 'compiled_truth', chunk_id: 0, chunk_index: 0, stale: false } as SearchResult; });
+}
+const scope = { sourceId: 'default', excludePrivate: false };
+
+async function seed() {
+ await put('crm/widget-co', 'crm', 'CRM record: Widget Co', 'Account code: WGCO. Discount: 12 percent.');
+ await put('notes/renewal', 'note', 'Renewal memo', 'Widget Co renewal: discount stays at 12 percent.');
+ await put('syntheses/widget', 'synthesis', 'Summary: Widget Co', 'Widget Co discount is 10 percent (summary).', { dream_generated: true });
+ await put('receipts/r1', 'extract_receipt', 'Extract receipt', 'Extracted from Widget Co notes: discount 10 percent.');
+ await put('notes/human', 'note', 'Human note', 'Widget Co discount history by hand.');
+ await sweep(engine);
+}
+
+describe('generated-page demotion', () => {
+ test('dream_generated and extract_receipt rows are stamped and demoted when a primary record for the entity is in the pool', async () => {
+ await seed();
+ const list = await rows(['syntheses/widget', 'receipts/r1', 'crm/widget-co', 'notes/human']);
+ await applyGeneratedDemotion(engine, list, 'Widget Co discount', scope);
+ const by = Object.fromEntries(list.map(r => [r.slug, r]));
+ expect(by['syntheses/widget']).toMatchObject({ provenance: 'generated', score: GENERATED_FACTOR, generated_demotion: GENERATED_FACTOR });
+ expect(by['receipts/r1']).toMatchObject({ provenance: 'generated', score: GENERATED_FACTOR });
+ expect(by['notes/human'].provenance).toBeUndefined();
+ expect(by['notes/human'].score).toBe(1);
+ expect(by['crm/widget-co'].score).toBe(1);
+ });
+
+ test('no competing primary record, or no resolved entity: nothing moves (rows still stamped)', async () => {
+ await seed();
+ const alone = await rows(['syntheses/widget']);
+ await applyGeneratedDemotion(engine, alone, 'Widget Co discount', scope);
+ expect(alone[0]).toMatchObject({ provenance: 'generated', score: 1 });
+ const unnamed = await rows(['syntheses/widget', 'crm/widget-co']);
+ await applyGeneratedDemotion(engine, unnamed, 'what discount did we give', scope);
+ expect(unnamed[0]!.score).toBe(1);
+ });
+
+ test('a generated page about another entity is not demoted for this one', async () => {
+ await seed();
+ await put('crm/kite-co', 'crm', 'CRM record: Kite Co', 'Account code: KTCO.');
+ await put('syntheses/kite', 'synthesis', 'Summary: Kite Co', 'Kite Co discount is 5 percent.', { dream_generated: true });
+ await sweep(engine);
+ const list = await rows(['syntheses/kite', 'crm/widget-co']);
+ await applyGeneratedDemotion(engine, list, 'Widget Co discount', scope);
+ expect(list[0]!.score).toBe(1);
+ });
+
+ test('a generated correction is never demoted and keeps outranking the obsolete original', async () => {
+ await seed();
+ await put('syntheses/correction', 'synthesis', 'Correction: Widget Co discount', 'Widget Co discount corrected to 15 percent.', { dream_generated: true, supersedes: 'notes/renewal' });
+ await sweep(engine);
+ const list = await rows(['syntheses/correction', 'notes/renewal', 'crm/widget-co']);
+ list[0]!.score = 2;
+ await applyGeneratedDemotion(engine, list, 'Widget Co discount', scope);
+ expect(list[0]).toMatchObject({ provenance: 'generated', score: 2 });
+ expect(list[0]!.generated_demotion).toBeUndefined();
+ expect(recordsCorrection(null, '## Facts\n\n<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n| 1 | Discount 10 | fact | 1.0 | world | medium | 2026-01-01 | 2026-03-01 | test | |\n<!--- gbrain:facts:end -->\n')).toBe(true);
+ });
+
+ test('search.demote_generated=false keeps scores', async () => {
+ await seed();
+ await engine.setConfig('search.demote_generated', 'false');
+ const list = await rows(['syntheses/widget', 'crm/widget-co']);
+ await applyGeneratedDemotion(engine, list, 'Widget Co discount', scope);
+ expect(list[0]).toMatchObject({ provenance: 'generated', score: 1 });
+ });
+
+ test('end to end (keyword path, no reranker): the record ranks above the summary', async () => {
+ await seed();
+ const r = await dispatchToolCall(engine, 'search', { query: 'Widget Co discount', fields: 'full' }, { remote: false, sourceId: 'default', config: { engine: 'pglite' } } as never);
+ const slugs = (JSON.parse(r.content[0].text!) as Array<{ slug: string; provenance?: string }>);
+ const at = (s: string) => slugs.findIndex(x => x.slug === s);
+ expect(at('syntheses/widget')).toBeGreaterThan(-1);
+ expect(at('syntheses/widget')).toBeGreaterThan(at('crm/widget-co'));
+ expect(slugs.find(x => x.slug === 'syntheses/widget')!.provenance).toBe('generated');
+ });
+});