Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): opt-in qualified alias and title matching
garrytan81f6bf23d201
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8cadb056cf..04c4b14cf4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Two opt-in search switches let a page's long alias, or a person or company name inside a longer query, find that page.** Agents rarely search a bare name: they write "status of the acme widget project" or "acme alice example". With `gbrain config set search.qualified_aliases true`, a 3 to 6 word phrase inside a query of up to 14 words that is the alias of exactly one page you can read brings that page to the top; two pages claiming the phrase, or a phrase with fewer than three content words ("hall of light"), change nothing. With `gbrain config set search.title_qualified true`, a person or company page whose title is mentioned inside the query gets the title boost once, never stacked on an identity boost. Both are off by default, and with them off search results and cache keys are unchanged. Neither switch ever marks a page `create_safety: exists`, so an agent still decides whether to write a new page on real identity evidence. A common three-word alias can lead a query about something else, so turn them on after checking your own queries. Works the same on a brain with no git repository. Proposed and first implemented by @calebhicks.++### Itemized changes++- `src/core/search/alias-hop.ts`: `qualifiedAliasCandidates` builds the 3 to min(6, n-1) word windows (3+ content words, longest then leftmost, at most 42) and adds them to the same single alias read; the first window with a readable, non-excluded claimant decides, one claimant leads at top-of-organic + epsilon (moved or injected through the private re-check) stamped `qualified_alias_hit`, two suppress it. Order is full-query alias, then qualified, then the token hop. A query over 6 words probes only the windows, so the exact-alias hop, `search.alias_token_hop` and the rerank gate's alias grades keep their 6-word cap.+- `src/core/search/intent-weights.ts`, `src/core/search/hybrid/request.ts`: `applyQualifiedTitleBoost` runs last in `applyIdentityBoosts` on every path; it boosts a person or company title (2+ content words) mentioned in the query or a given-name variant by `title_boost`, stamps `title_mention_boost`, and skips forward title matches and rows that already carry `exact_match_boost`.+- `src/core/search/hybrid/rank.ts`, `src/core/search/remote-page-cap.ts`: autocut and the remote page cap keep a `qualified_alias_hit` row; `classifyEvidence`, CRAG and System One protection do not read it. `gbrain search --explain` prints `title-mention`.+- `src/core/search/mode.ts`, `src/core/search/modes-report.ts`, `src/core/config.ts`, `src/core/search/config-values.ts`: `qualified_aliases` and `title_qualified` mode knobs (off in every bundle), append-only `qa=1` / `tq=1` cache-key parts only when on, `gbrain search modes` rows, and `gbrain config set` refuses a value other than true/false (exit 2, `invalid_params`, nothing written).+- Docs: `docs/architecture/RETRIEVAL.md`, KEY_FILES entries for `alias-hop.ts`, `hybrid.ts`, `explain-formatter.ts`, `title-match.ts` and `remote-page-cap.ts`.+- Tests: `test/search/alias-hop.test.ts`, `test/search/qualified-alias-visibility.test.ts` (PGLite and Postgres, `readable_by` members, `visibility: private`, MCP `search` with `remote: true`; Postgres arm also through `test/e2e/qualified-alias-visibility-postgres.test.ts`), `test/search/title-boost-stage.test.ts`, `test/search/title-retrieval-arm.test.ts` (keyless keyword-only path), `test/search-mode.test.ts`, `test/config-set-unread-prefixed-key.test.ts`, `test/search-remote-page-cap.test.ts`, `test/search/explain-formatter.test.ts`.+## [0.60.620.0] - 2026-11-09**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex d492ebc7b8..40c08c1bc1 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -127,12 +127,26 @@ written up in [`RETRIEVAL_MAXPOOL_INCIDENT.md`](../incidents/RETRIEVAL_MAXPOOL_Iinside `page.title` (or an exact full-title match), a floor-ratio-gated,bounded multiplier fires (`applyTitleBoost`, `search.title_boost` knob). Aquery that is a phrase from the title can't lose to a body chunk by luck.+ Opt-in `search.title_qualified` (off by default) covers the reverse case: a+ person or company title (2+ content words) mentioned inside a longer query+ ("acme alice example") gets the same multiplier, unfloored, stamped+ `title_mention_boost`, unless an identity boost already raised the row.+ Evidence never reads that stamp as an exact title match.- **Alias hop** — free-text `aliases:` frontmatter is projected into a`page_aliases` table (separate from the `slug_aliases` wikilink redirect) andconsulted at query time: a full normalized-query match injects/boosts thecanonical page (`applyAliasHop`). The only layer that bridges true synonymswith zero surface overlap ("the Sun Room" → the Helios page). Backfill- existing pages with `gbrain reindex --aliases`.+ existing pages with `gbrain reindex --aliases`. Opt-in+ `search.qualified_aliases` (off by default) also matches a 3-6 word+ sub-phrase with 3+ content words inside a query of up to 14 words: when+ exactly one page the caller can read claims it, that page leads, stamped+ `qualified_alias_hit`; two claimants suppress the hop. The stamp keeps the+ row past autocut and the remote page cap but never sets evidence+ `alias_hit`, and the rerank gate does not grade it. A common three-word+ alias can lead a query about something else, so confirm on your own eval+ before turning it on: `gbrain config set search.qualified_aliases true`+ (`false` turns it back off).- **Evidence contract** — every result carries `evidence`(`alias_hit | exact_title_match | high_vector_match | keyword_exact |weak_semantic`) and `create_safety` (`exists | probable | unknown`). An agent@@ -251,7 +265,8 @@ relational re-pin (relational-arm rows back above the reranked text rows, inreordered — src/core/search/relational-rerank-pin.ts)│▼-alias hop (exact alias match injects/boosts the canonical page; like the+alias hop (exact alias match injects/boosts the canonical page; opt-in+ qualified sub-phrase match leads one page; like theexact-lookup tier below it never re-sorts, so the reranked order holds)│▼diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 198dd347ac..4e3f8281f2 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking at the SQL layer (curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `<fork>/chat/`, `daily/`, `media/x/`). `searchVector` uses a two-stage CTE so source-boost re-ranking doesn't kill the HNSW index. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/` by default) filter at retrieval, not post-rank. Both gates honor `detail !== 'high'` so temporal queries surface chat pages normally.-- `src/core/search/alias-hop.ts` — the post-rerank alias hop (`applyAliasHop` = `lookupAliasHop`, the alias-table read, then `applyAliasHopLookup`; `aliasHopCanonicals` is the filtered, ordered, capped canonical list both apply and the rerank gate read; re-exported by `hybrid.ts`), the opt-in single-token hop (`applyAliasTokenHop`, #5428) and the exclude contract both identity injections share (`IdentityTierOpts`, `isExcludedIdentity`; `exact-lookup.ts` imports it). Behavior is documented under the `hybrid.ts` entry. Pinned by `test/search/alias-hop.test.ts`, `test/search/alias-token-hop.test.ts`, `test/search/injection-excludes-keyword-boost.test.ts`.+- `src/core/search/alias-hop.ts` — the post-rerank alias hop (`applyAliasHop` = `lookupAliasHop`, the alias-table read, then `applyAliasHopLookup`; `aliasHopCanonicals` is the filtered, ordered, capped canonical list both apply and the rerank gate read; re-exported by `hybrid.ts`), the opt-in single-token hop (`applyAliasTokenHop`, #5428), the opt-in qualified hop (`qualifiedAliasCandidates`, `applyQualifiedAliasHop`) and the exclude contract both identity injections share (`IdentityTierOpts`, `isExcludedIdentity`; `exact-lookup.ts` imports it). Behavior is documented under the `hybrid.ts` entry. Pinned by `test/search/alias-hop.test.ts`, `test/search/alias-token-hop.test.ts`, `test/search/qualified-alias-visibility.test.ts`, `test/search/injection-excludes-keyword-boost.test.ts`.- `src/core/search/alias-normalize.ts` — ONE normalizer shared by the WRITE path (ingest projects frontmatter `aliases:` into `page_aliases`) and the READ path (search matches query against `page_aliases`), so stored aliases can't silently fail to match queries via divergent normalization (same single-source posture as `cjk.ts`). `normalizeAlias(raw)` does NFKC + lowercase + whitespace-collapse + trim + strip one layer of wrapping quotes/brackets; returns `''` for empty (callers MUST skip empty aliases). `normalizeAliasList(value)` coerces a frontmatter scalar / array / comma-list / garbage into a deduped list of normalized non-empty aliases — used by both the ingest projection and the `reindex --aliases` backfill.- `src/core/search/arm-confidence.ts` — arm-confidence-weighted fusion for the keyword arm (`search.keyword_arm_confidence_floor`; `null` = off in every bundle — the pre-registered Cat 13 E2 mechanism FAILED its held-out rule at the calibrated floor 0.6121 (53.0 → 53.0), so the knob ships default off for operators and the receipt is published). `keywordArmConfidence(rows)` reads the strict keyword arm's raw `score` column into a scale-free statistic (`top`, `second`, `margin_ratio`; TypeScript-side — engines still return raw `ts_rank × sourceFactor`, no SQL change); `decideKeywordArmWeight({keywordList, floor, vectorArmVoted, relationalQuery})` down-weights the keyword AND title fusion entries to `KEYWORD_ARM_WEAK_WEIGHT` (0.5) only when the floor is set, the keyword list is non-empty, a text vector arm voted, the query is not relational, and `margin_ratio < floor`; otherwise it emits no weight (byte-identical fusion). It is called from `composeFusionLists` (`fusion-lists.ts`) so the weight lands through the same per-list `weight` primitive as the expansion budget, never a k change. `normalizeKeywordArmConfidenceFloor` is the ONE range contract (number in `(0, 1]` or a string parsing to one; `null`/`false`/`off` → `null`; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`. The decision (`{top, second, margin_ratio, downweighted}`) is surfaced as `HybridSearchMeta.keyword_arm_confidence` even with the floor off, so a calibration run can pick a floor from per-probe receipts; knobs-hash part `kacf=`. Pinned by `test/search/arm-confidence.test.ts` (pure contract) and `test/search/arm-confidence-hybrid.test.ts` (hermetic PGLite: a weak keyword arm is down-weighted only with the floor set; off is byte-identical).@@ -29,13 +29,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/expansion.ts` — Multi-query expansion via Haiku. Exports `sanitizeQueryForPrompt` + `sanitizeExpansionOutput` (prompt-injection defense-in-depth). Sanitized query is only used for the LLM channel; the original query still drives search. `expandQuery` returns the original first plus 2-3 variants; `hybridSearch` re-enforces `queries[0]` = the caller's query and dedupes repeats, then fuses each variant's vector list as a role `variant` arm through `src/core/search/fusion-lists.ts` (see that entry), where the variant arms share `search.expansion_variant_budget` as total RRF weight — `null` (every bundle's default) is legacy equal weight, the configuration under which the LongMemEval receipt shows expansion halving strict `recall_all@5` (93.19% plain hybrid vs 54.89% with expansion, paired +3 / -183; `docs/architecture/RETRIEVAL.md` "Multi-query expansion"). The harness records `expansion_variants` per row and `--expansion-replay` serves them back so a budget sweep changes only the budget.-- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field; also prints the raw query↔chunk cosine (`SearchResult.cosine`, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. `formatResultsExplain(results, meta?)` prepends header lines from the captured retrieval meta when present — `formatAutocutSummary` (the autocut decision) and `formatDegradedSummary(meta.degraded)`, which renders the closed `degraded[]` vocabulary as `degraded: reranker_skipped (no_key)` (null when the run was clean); `cli.ts:formatResult` threads `lastRetrievalMeta` into it, so a silently skipped reranker is visible from the CLI. Pinned by `test/search/explain-formatter.test.ts` + `test/cli-explain-degraded-render.test.ts`. `formatDecideSummary` prints one `decide <slot>:` line per slot that ran (all-off: none), including the slot's answer summary (S2 label, S4 probability and verdict). `formatTimingsSummary` (stage-timings.ts) adds the `timings:` line.+- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field (`title_mention_boost` renders as `title-mention`); also prints the raw query↔chunk cosine (`SearchResult.cosine`, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. `formatResultsExplain(results, meta?)` prepends header lines from the captured retrieval meta when present — `formatAutocutSummary` (the autocut decision) and `formatDegradedSummary(meta.degraded)`, which renders the closed `degraded[]` vocabulary as `degraded: reranker_skipped (no_key)` (null when the run was clean); `cli.ts:formatResult` threads `lastRetrievalMeta` into it, so a silently skipped reranker is visible from the CLI. Pinned by `test/search/explain-formatter.test.ts` + `test/cli-explain-degraded-render.test.ts`. `formatDecideSummary` prints one `decide <slot>:` line per slot that ran (all-off: none), including the slot's answer summary (S2 label, S4 probability and verdict). `formatTimingsSummary` (stage-timings.ts) adds the `timings:` line.- `src/core/search/fusion-lists.ts` — the ONE composition point for `hybridSearch`'s RRF inputs. Every vector recall list is a ROLE-tagged arm (`VectorArm {list, role: 'original'|'variant'|'clause'|'image'}`, appended only via `pushVectorList`) — never a parallel index-aligned array, since the `allSettled` salvage path drops failed arms and the both-mode image branch fails open, so positional rules mis-tag lists. `composeFusionLists({arms, keywordFusionList, titleFusionList, relationalList, includeRelational, ks, knobs})` returns the complete weighted list set (`FusionListEntry {list, k, weight?}`) in the fixed order vector arms → keyword (`keywordK`) → title (`keywordK`, only if non-empty) → relational (`baseRrfK`, only if non-empty and not image modality): text arms fuse at `textRrfK` and the image arm at `imageRrfK` only when BOTH kinds are present, otherwise every arm at `vectorK` (text, image-only, unified, and a both-mode whose image branch fell open). `variant`/`clause` arms share `expansionVariantBudget` as total RRF weight — `weight_i = b / n_voting_arms` over the NON-EMPTY expansion arms (an empty list casts no vote), the `original` arm always weight 1; a `null` budget emits no `weight` key, byte-identical to unweighted fusion; when the original is missing every surviving text arm is a `variant` sharing the budget. `rrfFusionWeighted` (hybrid.ts) scores `weight / (k + rank)` (weighted RRF: a list-level multiplier at every rank). `textArmsNonEmpty` is the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count). `normalizeExpansionVariantBudget` is the single range contract for the knob: finite `(0, 4]` (or a string parsing to one) → number, `null`/`legacy`/`null`-literal → null, anything else → `undefined` (fall through to config → bundle); shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`, so an invalid per-call value never reaches fusion or the cache key. `interleaveFusion(arms, key, limit)`: score-free round-robin (each arm's #1, then #2, deduped by key, cut at `limit`) for fact supersession candidates (`facts.candidate_fusion`); hybrid search stays on RRF (`test/search/interleave-fusion.test.ts`). Pure, no engine/IO. Pinned by `test/search/fusion-lists.test.ts` (knife-edge arithmetic at budget 1.0, legacy deep-equals the pre-role text mapping, role alignment under rejected arms), `test/search/expansion-variant-budget.test.ts` (hermetic directional PGLite test), and the both-mode demotion-gate regression in `test/keyword-relaxed-fusion.serial.test.ts`.- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.-- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` (`search/cosine-rescore.ts`) scores the active column in SQL with the JS rules (a failure falls back to JS and sets `cosine_rescore`), and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).+- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths, and bare `hybridSearch` never touches `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (consumer: `gbrain whoknows`); AND-applies with the single-value `type` filter. `hybridSearch` resolves the embedding column via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` (`search/cosine-rescore.ts`) scores the active column in SQL with the JS rules (a failure falls back to JS and sets `cosine_rescore`), and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, floor-ratio-gated; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. Opt-in `search.qualified_aliases`: the same alias read probes a 3–14 token query's 3–6 token windows (3+ content tokens, longest then leftmost); the first window with a readable claimant leads its page (`qualified_alias_hit`: autocut and the remote page cap keep it, evidence and the rerank gate ignore it), two claimants suppress it, and a query over 6 tokens probes only windows. Opt-in `search.title_qualified` (`applyQualifiedTitleBoost`, last in `applyIdentityBoosts`): a person/company title mentioned in the query gets `title_boost` as `title_mention_boost`, except forward title matches and rows with `exact_match_boost`. Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped once at function entry, before any boost. Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Every boost stage stamps its own field, which `--explain` reads. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `hybridSearch` and `hybridSearchCached` are short orchestrators over the named stages in `src/core/search/hybrid/` (next entry); the file keeps the post-fusion boosts, RRF, cosine rescore, the cache-write drainer and the public helpers.- `src/core/search/hybrid/` — hybridSearch pipeline stages. `startVectorSide` runs modality, expansion and the vector arms alongside the lexical and relational arms (`runLexicalAndRelational`) on its own timer branch, `degraded` list and `vectorPoolMetaSink`; `joinVectorSide` merges its stamps and `expansionApplied` after the lexical ones, so `degraded[]` keeps the sequential order. Every other stage runs in a fixed order: `request.ts` (`resolveHybridRequest` builds a `HybridRequest` once: mode, embedding column, limits (per-arm pool from `perArmPoolLimit` in `src/core/search/eval-pool-depth.ts`: today's max(2·limit, floor, offset+limit) capped at 100 unless an eval sets `--eval-pool-depth`), intent, `searchOpts`, identity-tier opts, and the accumulators `vectorPoolUnderfill` / `expansionApplied` / `lastResultsCount` / `lastRank1Score` that stages write only as `req.<field>`; `emitHybridMeta`, `applyIdentityBoosts`), `arms.ts` (lexical, relational, modality + expansion, vector arms), `keyword-only.ts` (the no-provider and all-vector-arms-empty return paths; `opts.decide.keywordOnly`, the System One S6 fire retrieval, takes the no-provider path on purpose without the vector-unavailable degraded marker or warning), `rank.ts` (fusion + post-fusion boosts, A2 expansion, rerank + relational pin, identity tiers + adaptive return + autocut + relational slot, main return), `cache-stages.ts` (hybridSearchCached mode resolution, semantic-cache handle, skip gate, hit path; the result cache stays hard-disabled), `degraded.ts`, `effective-modes.ts`, `rerank-gate.ts` (the W3 pre-rerank grade; see the `crag.ts` entry in Core Search 2/2). The orchestrators wrap each stage in `req.timer` / `opts._timings` (stage-timings.ts). Stages import public helpers back from `hybrid.ts` at call time only (the `exact-lookup.ts` pattern); `hybrid.ts` exports nothing new. Pinned by `test/hybrid-golden.test.ts` (exact `(id, score)`, cold and warm).diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 23df17085a..83351b47d6 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -42,7 +42,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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. `keywordPhraseFactorSql`: opt-in 2x on a phrase match (#7175).- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (`cc` source, full-text match, text modality). For excludePrivate callers it plans the match alone in an `OFFSET 0` subquery; joined, the visibility subplans' cost let a seq scan detoasting every `search_vector` win (1.1 → 0.2 s, common term, 250k chunks). Local callers keep the unfenced, parallel-capable join. `KEYWORD_RANKED_ROWS_CTE`: ranking carries only ids, score and bounded_rows; display columns come from one `LIMIT 1` key probe per ranked chunk. Output equals the wide statement's; under the 50k bound (sample in plan order), its unspilled output. Not on PGLite. Pinned by `test/search/keyword-arm-ranking.test.ts`, `test/e2e/keyword-arm-ranking-postgres.test.ts`.-- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. `isTitleMentionedInQuery(query, title)` is the reverse direction the intent exact-match boost uses: the title appears as a contiguous token run INSIDE the query ("who is Alice Example" → "Alice Example"), guarded to titles with ≥2 content tokens or one content token of ≥4 characters. `titleNameVariants(query)` (#7471) is the query with its given name swapped for each other form in its nickname group (`givenNameVariants` in `entities/name-variants.ts`), none for websearch-operator queries; the title arm ORs them into its query and the T2 boost accepts a variant title-phrase match. Exports `tokenizeTitle` + `__test__` internals.+- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. `contentTokenCount(s)` counts non-stopword tokens (the qualified alias windows and the qualified title boost read it). `isTitleMentionedInQuery(query, title)` is the reverse direction the intent exact-match boost and the opt-in qualified title boost use: the title appears as a contiguous token run INSIDE the query ("who is Alice Example" → "Alice Example"), guarded to titles with ≥2 content tokens or one content token of ≥4 characters. `titleNameVariants(query)` (#7471) is the query with its given name swapped for each other form in its nickname group (`givenNameVariants` in `entities/name-variants.ts`), none for websearch-operator queries; the title arm ORs them into its query and the T2 boost accepts a variant title-phrase match. Exports `tokenizeTitle` + `__test__` internals.- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.diff --git a/docs/architecture/key-files/core-search-evidence.md b/docs/architecture/key-files/core-search-evidence.mdindex 0be09c78a6..9d928c9407 100644--- a/docs/architecture/key-files/core-search-evidence.md+++ b/docs/architecture/key-files/core-search-evidence.md@@ -7,4 +7,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/evidence-tail-trim.ts` — the protected tail trim (`search.evidence_tail_trim`, default off, GBRA-156). `resolveEvidencePlan` sets `EvidencePlan.tailTrim` only for `unit: auto` with the key on; `deliverEvidence` calls `trimEvidenceTail(results, opts.query)` on the rank-order delivered rows after redaction and before the token totals, and only when `DeliverOptions.query` is set (`search`/`query` pass `p.query`; the library `assembleEvidenceForHits` passes `input.query` and frozen hits may carry `score`; the `assemble_evidence` op passes neither, so the trim never runs there). Rows past `TAIL_TRIM_PROTECTED` = 3 that are whole-conversation blocks (`delivered.reason` `conversation_type`/`conversation_slug`) and score under `TAIL_TRIM_SCORE_FRACTION` = 0.5 of rank one are dropped, unless their `chunk_text` holds at least `TAIL_TRIM_TERM_FRACTION` = 0.8 of rank one's share of the query's terms (`queryTerms`: letter/digit runs, stopwords and single characters dropped, cut to six characters). Rank one's score must be a positive finite number and every row's finite, or nothing changes. `delivery.tail_trim` is `{ dropped, kept_by_query_terms }`; `dropped_reasons.tail_trim` counts drops. Pinned by `test/evidence-tail-trim.test.ts` (the knowledge-update regression case).- `src/core/search/transcript-quote.ts` — quotes third-party text on every read that hands it to a model (#7600, #8042). The signal is stored metadata, in one place: `isQuotedPageType` (every concrete type in `facts/conversation-types.ts` `ALLOWED_TYPE_ALIASES` plus `transcript` and `chat`) for page rows, and for fact rows `isQuotedFactSource` (`facts.source` starting `cli:extract-conversation-facts`, the prefix in `facts/audit-sources.ts`) or `factsFromQuotedPages` (one bounded read, same source: the fact's `source_markdown_slug` page, a `derivation_inputs` page edge the backstop and extract_facts already write, or for a `sync:import` / `mcp:put_page` fact the page its `source_session` names (`sync:<slug>`, `put_page:<slug>`, covering facts saved before edges or rebuilt from git) has a quoted type; it writes nothing, and a lookup failure withholds `saved_facts` (stage `saved_facts_withheld`) and remote recall facts (`facts_degraded.reason`) and fails the delta facts arm; the facts arm carries both on `fact_row.source`/`from_quoted_page`, stripped by `factRowOutput`; marker `fact <id>`); nothing reads the text to decide, so other rows come back byte-for-byte unchanged. `quoteLabel` is the row decision. GST-687: for an untrusted (remote, `ctx.remote !== false`) reader the signal also includes the stored trust tier: `quotesTier` (below `OWNER_TIER_FLOOR`, `operator_curated`; a missing tier reads as `unknown`, so it fails closed) and `quotesStored` (page type or tier) quote agent-written, tool-data, external and unverified-origin text. `quoteLabel(row, untrusted)`, `deliveredQuoteText`, `fenceTranscriptRows` and `quoteFacts(engine, facts, untrusted)` take that flag (`quoteFacts` reads each fact's stored tier from `facts`, never from the caller's row); only third-party types get tool calls summarized. `quotePageText` and `pageTypesById` serve reads whose rows name only a page (`get_timeline`, `get_chunks`). Local reads are unchanged. Beyond search: `recall` (remote callers: neutralize + fence its results before packing, `quoteFacts` its facts), think's pages block (`think/gather.ts renderPagesBlockDetailed`: neutralize before the excerpt, fence what it renders, every run), `saved_facts` in search/query meta, remote `delta` facts and `_meta.brain_hot_memory` (`quoteFacts`, which also quotes a representative when a collapsed member qualifies), remote `get_page known_as_of` and `get_versions` bodies and diffs (`ops/known-as-of.ts intervalView`, `ops/admin.ts`), and remote `get_page`/`fetch` (`ops/get-page-projection.ts projectGetPage` `quote`, which `projectFetchText` reuses: compiled_truth, timeline and `content` fenced without the tool-call summary, so text inside stays byte-exact; windows fenced in `get-page-body.ts envelopeText`; `quoted: "transcript"`; `quotesBody(ctx, page, trust)` also quotes a page below the owner's tier, and `neutralizesBody` summarizes tool calls only on a third-party page's reading shapes, never for the thin client, with `include_content` and `view: markdown` keeping the stored bytes inside the fence). Remote `get_timeline`, `get_chunks`, `search_exact`, think's extractive fallback, `context_pack` and `list_write_requests`/`get_write_request` outcome text quote by tier too, and so (#8377) do the `chronicle_*` reads and `volunteer_chronicle`'s timeline (`ops/chronicle.ts remoteTimeline`, each row by its own page; `quoteTimelineRows` fences a row's free-text `source` with summary and detail, #8384, and an event row's `kind` is fenced by its event page's type and tier), its ontology values, `ontology_get`'s and `ontology_conflicts`' (`remoteOntology`, `quoteFacts` by `fact_id`; remote `ontology_propose` drops a fact fence), `takes_list`/`takes_search` (`ops/takes.ts quoteTakes`), a quoted page's title, frontmatter strings and tags (`quotedPageMeta`, also `get_tags`; remote `add_tag`/`remove_tag` drop a fence naming the page; `include_content` and fetch `text` fence the whole serialized markdown), a quoted search/query/assemble_evidence/recall row's title (`deliveredQuoteTitle`, which `capEvidenceToBudget` counts), a `context_pack` card below the owner's tier rendering its title under the card's trust label, the per-turn push hook's hot facts and the pushed context pack (`untrusted: true`); `context_pack` counts entity facts a failed quote lookup withholds in `suppressed`. Remote `remember` drops a fact fence (`unquoteFactText`) and `add_timeline_entry` a fence naming its page, so a copied-back entry keeps its replay key. Remote `put_page` (`ctx.remote !== false`) runs `unquoteTranscriptText` over `content` (`persistence/page-mutations.ts unquotedPutContent`, after the replay check so the request digest covers what the caller sent; slug lowercased as admission does) when the stored page or the incoming frontmatter has a quoted type or the stored page is below the owner's tier (an owner-tier page keeps a fence naming it only when its stored body already holds one), removing only a marker naming that slug and its own fence (lines may end in CRLF), so get → edit → put writes the body and a note's fence-like text is kept (`unclosed`: a fence opening the content, after blank lines at most, whose closing line the edit replaced is removed too, #8377, #8384; `closingLine` takes the first line that is exactly the read's fence outside a code block the text opens itself, so an agent's added block stays whole; every search of one text shares a budget of eight times its length, past which the rest is kept as written, so many unclosed markers stay linear). Remote `put_page` content holding a tool-call summary that a whole read of the stored conversation page never produces, or fewer of a call's summaries than the page holds (`holdsSummarizedToolCalls`), refuses `invalid_params` and stores nothing; only summaries outside the text's own tool-call blocks count, and a named summary the page never wrote is admitted while every stored call stays (#8377). A thin client paging a quoted page (`cli/page-render.ts spoolWholePage`) unquotes each window before checking size and sha256, then prints the page (and `--json` content) inside one quote fence (`transcriptFence`). Trusted local get_page/fetch/put_page, recall and delta are unchanged. `searchOutput` (`ops/search.ts`) runs `neutralizeTranscriptRows` before the snippet and evidence caps and `fenceTranscriptRows` after them, on copies, after ranking and evidence delivery; `assembleEvidenceForHits` (`evidence-delivery.ts`, so the `assemble_evidence` op and gbrain-evals) does the same around `capEvidenceToBudget`. That cap counts a conversation row as delivered, inside its fence (`deliveredQuoteText`, its `quote` flag; deliverEvidence's own cap, which recall uses, counts the text as returned), so an explicit `auto` token budget still holds, `snippet_chars` included (a rank-one row is kept even when its fence alone exceeds a very small budget); a row it cuts is shortened until the fenced text fits, and other rows are cut exactly as before. The neutralizer replaces each tool-call block with `[tool call: <name>, arguments omitted]` (`[tool calls: a, b, …]` for several): an object typed `tool_use`, `server_tool_use`, `mcp_tool_use`, `function_call`, `custom_tool_call`, `tool_call` or `toolCall` (the enclosing object, found by walking back over candidate `{` with a string-aware scan), the value of a `tool_calls` array or a `function_call` or Gemini `functionCall` object (the message object and its `content` or `parts` stay), and an XML-style `function_calls`, `invoke`, `tool_use` or `tool_call` element with its `parameter` children, namespace prefix optional (the name from `invoke name="…"`, a `<name>` child, or the root `name` of the JSON object a `tool_call` opens with; result elements are never matched, and a tag counts as markup only when it ends its line (LF or CRLF) or the text, runs into the next tag, is an `invoke` with a name, or is a `tool_call` followed by `{`; blocks separated only by whitespace merge). The XML pass runs before the JSON pass. Text between evidence omission lines is read separately; a block cut by the end of the text is replaced to the end or the next message anchor line (an open-ended block never swallows a later message), one whose `{` lies before the text from the text start (or the last message anchor) when the type is followed by `,` or `}`, and prose that only names the shape is left alone. An XML block whose close lies past the text runs to the end or the next message anchor line; a closing tag with no opener (or a `parameter` opener outside a call) starts at the text start or the last message anchor. A trailing evidence cut marker and a leading `[observed …]` date header stay outside any block. Message anchor lines may end in CRLF. Scanning is linear: anchors are indexed once, and past a per-text work budget the rest of a message is summarized (fails closed). Names outside `[A-Za-z0-9_.:/-]{1,64}` are dropped. The fence is a marker line naming the slug (`[`, `]`, `;` and line breaks shown as `?`), then a code fence of at least three backticks, one longer than the longest run in the text; the row gets `quoted: "transcript"` (kept in lean rows). `rowPreview` is the CLI human line: `[quoted transcript]` and the start of the fenced text. Stored pages, chunks, ranking and scores are unchanged; delivered `match_spans` are remapped to the returned text, and `tokens`, `tokens_delivered` and `budget_used` count the fenced text (`fenceTranscriptRows` with a recount). Tests: `test/search/transcript-quote.test.ts`, `test/search-transcript-quote.test.ts` (ChatGPT export through the importer, with a JSON and an XML call; remote MCP `search`/`query`/`assemble_evidence` and CLI human/`--json`, both engines), `test/search-transcript-quote-budget.test.ts` (budget, spans and snippet cap through the ops), `test/search-transcript-quote-coverage.test.ts` (#8042 matrix: slack, imessage, email, meeting and conversation pages plus a conversation-extracted fact against a note and a remembered fact, plus backstop facts linked to a synced slack page by a derivation edge or only by their sync session, and one derived from a note, a failed lookup withholding facts, a retried retype put, over remote search, query, saved_facts, assemble_evidence, recall, get_page body/content/window, local get_page, the get→put round trip (a note's fence-like text, a mixed-case slug), thin-client paging of a 12,000-line slack page, fetch, think's prompt, delta, hot memory, and get_page known_as_of / get_versions bodies and diff, both engines), `test/search-transcript-quote-tiers.test.ts` (GST-687: every placement and read surface by tier, both engines) and `test/search-transcript-quote-legacy-claim.test.ts` (a legacy note is quoted, raw again after claim and backfill, both engines), `test/search-transcript-quote-followups.test.ts` (#8377: the chronicle, takes and page title/frontmatter reads, hook-injected facts, and the copied-back writes, red on master, both engines) and `test/trust-keep-maintenance-reimport-8352.test.ts` (#8352: maintenance re-imports keep an owner note's tier, both engines) and `test/search-transcript-quote-8384.test.ts` (#8384: whole-markdown round-trip edges, timeline source, ontology values, the `quoted_unverified_origin` notice from `get-page-projection.ts unverifiedOriginNotice`, both engines) and `test/search-transcript-quote-8384b.test.ts` (#8384 wave 3: CRLF whole-markdown, chronicle `kind`, search row and card titles, tags, a fenced value next to a naive datetime, both engines).- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Fact reserves: `applyFactReserve` serves two policies. The temporal fact reserve (`applyTemporalFactReserve`, `search.temporal_fact_reserve`, default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`. The facts block (`applyFactsBlock`, `search.query_facts_block`, GBRA-205, default on since the held-out gate passed; `false` or a config read error turns it off): the same facts for every query whose caller passed `token_budget` (the no-budget evidence plan's implicit budget does not run it, #8411), up to 22% of the budget, 40 rows and the caller's `limit`, oldest first ahead of the pages at the top page's score (never above it), adding rows. Fact source pages (`applyFactSourcePages`, `search.fact_source_pages`, GBRA-205, default off): the conversations (`facts.source_markdown_slug`, never the entity page) of the best-matching admitted facts, at most 2 not already present, read through `getChunkWindows` under the caller's read scope and placed after the top 3 rows; the row count never grows. Tests: `test/search-8k-conversion.test.ts`.-- `src/core/search/remote-page-cap.ts` — GBRA-156: the default distinct-page cap of a remote `search`/`query` that names no `limit` (and no `offset`). `remotePageCap(ctx, p)` reads `search.remote_page_cap` (default `DEFAULT_REMOTE_PAGE_CAP`, `0` = off; null for trusted local callers and `viaSubagent` host tool calls); `capVectorOnlyPages(rows, cap)` keeps every page with lexical evidence (`keyword_hit`, strict or relaxed, `alias_hit`, `exact_lookup`, `relational_pinned`) and admits vector-only pages, in rank order, only while the result holds fewer than `cap` distinct `(source_id, slug)` pages; it reports `{ cap, kept_pages, dropped_pages }` as `_meta.retrieval.page_cap` when it dropped any. `pageCapLine(retrieval, how)` renders that as the model-visible line dispatch's `retrievalNoticeBlocks` appends after the keyword count line (hosts that show only `content[]` never see `_meta`), and the CLI's `formatResult` writes on stderr with `--limit`. Applied to the hybrid output before alias fan-out (search) and to the first pass and an adopted CRAG re-run (query); keyword-only paths carry no vector-only rows and the image branch is uncapped (`test/search-remote-page-cap.test.ts`). Every vector path (the hybrid vector arm, the embed-failure fallback, the `query` image branch) reads the keyword path's source scope (`test/search-vector-scope-parity.test.ts`).+- `src/core/search/remote-page-cap.ts` — GBRA-156: the default distinct-page cap of a remote `search`/`query` that names no `limit` (and no `offset`). `remotePageCap(ctx, p)` reads `search.remote_page_cap` (default `DEFAULT_REMOTE_PAGE_CAP`, `0` = off; null for trusted local callers and `viaSubagent` host tool calls); `capVectorOnlyPages(rows, cap)` keeps every page with lexical evidence (`keyword_hit`, strict or relaxed, `alias_hit`, `qualified_alias_hit`, `exact_lookup`, `relational_pinned`) and admits vector-only pages, in rank order, only while the result holds fewer than `cap` distinct `(source_id, slug)` pages; it reports `{ cap, kept_pages, dropped_pages }` as `_meta.retrieval.page_cap` when it dropped any. `pageCapLine(retrieval, how)` renders that as the model-visible line dispatch's `retrievalNoticeBlocks` appends after the keyword count line (hosts that show only `content[]` never see `_meta`), and the CLI's `formatResult` writes on stderr with `--limit`. Applied to the hybrid output before alias fan-out (search) and to the first pass and an adopted CRAG re-run (query); keyword-only paths carry no vector-only rows and the image branch is uncapped (`test/search-remote-page-cap.test.ts`). Every vector path (the hybrid vector arm, the embed-failure fallback, the `query` image branch) reads the keyword path's source scope (`test/search-vector-scope-parity.test.ts`).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 91c4fa72d0..5edadae8bf 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -23,7 +23,7 @@ src/core/operations.ts 249 ratchet +1 #7168: graphRankOperations import (ops/grasrc/core/pglite-engine.ts 3103 ratchet +9 #7191: findPages/countPagesBy delegates and imports (SQL in engine-sql/page-lookup.ts); +4 GBRA-283 B1 (#8455): initSchema seeds an engine opened from settings with settings.embedding and refuses a mismatch, and its open skips the snapshot fast path (logic in embedded-engine.ts; engine methods cannot move); +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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +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); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)src/core/postgres-engine.ts 3178 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +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); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +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; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +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; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts-src/core/types.ts 2357 ratchet +2 #8664 agent label: WriteAttributionView.agent_label (+ its doc line; the header, record and read live in persistence/attribution.ts and ops/attribution.ts) +3 train R: #7491 SearchOpts identifier-probe field and #7175 keywordPhrase option (interface fields); +2 GBRA-154 #7175: SearchOpts.keywordPhrase (opt-in phrase factor); +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +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); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +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); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +2 GBRA-95 G7a follow-up: Page.withheld_source_path field; +2 #7600: SearchResult.quoted (interface field; logic in search/transcript-quote.ts); +1 #8377: ChronicleTimelineRow.trust_tier (interface field; chronicle reads quote rows by tier); re-summed at the train R merge with v0.60.574.0: 2354 + 1+src/core/types.ts 2361 ratchet +4 #8555 rewrite: SearchResult.qualified_alias_hit and title_mention_boost stamps (one doc line each); +2 #8664 agent label: WriteAttributionView.agent_label (+ its doc line; the header, record and read live in persistence/attribution.ts and ops/attribution.ts) +3 train R: #7491 SearchOpts identifier-probe field and #7175 keywordPhrase option (interface fields); +2 GBRA-154 #7175: SearchOpts.keywordPhrase (opt-in phrase factor); +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +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); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +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); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +2 GBRA-95 G7a follow-up: Page.withheld_source_path field; +2 #7600: SearchResult.quoted (interface field; logic in search/transcript-quote.ts); +1 #8377: ChronicleTimelineRow.trust_tier (interface field; chronicle reads quote rows by tier); re-summed at the train R merge with v0.60.574.0: 2354 + 1src/core/minions/queue.ts 2547 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); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); +3 GBRA-133: the stall sweep deletes a drain-lease holder record whose lease lock is gone or expiredsrc/commands/init.ts 1892 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); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts); +1 GBRA-199: --surface help line names the default verbs listing; +7 GBRA-248 W0b: the implicit-keyless marker on both zero-key fallbacks, the deferred-hint gate on both engine paths and the kept-identity call in both (logic in commands/init-embedding-plane.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -36,12 +36,12 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1996 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear; +1 #8424: hookSessionCwd import (the session directory the hook launcher records; logic in core/setup/hook-launcher.ts); +1 #8424 review: runHook captures the launcher-recorded session directory first (logic in setup/hook-launcher.ts captureHookSessionCwd); +7 #8427: the hook git probes skip core.fsmonitor and run only in the workspace the install receipt namessrc/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 2021 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured)+src/core/config.ts 2023 ratchet +2 #8555 rewrite: search.qualified_aliases / search.title_qualified KNOWN_CONFIG_KEYS rows; +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured)src/core/persistence/sync-run.ts 1697 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move)src/core/bootstrap/harness.ts 2630 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)src/core/oauth-provider.ts 1237 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option; +1 GST-1113 transactional token mintsrc/core/ops/pages.ts 739 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (739 measured)-src/core/search/mode.ts 1730 ratchet +12 #7175 (train R): search.keyword_phrase bundle field, config parse and knobsHash part; +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156 #7593: private-pages grant part in the cache key; +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities) (re-summed at the train M .538 merge: 1717 measured); +1 GBRA-283 B2: import of the embedded engine reranker model (engine-gateway.ts); re-summed at the train R merge with v0.60.574.0: 1721 + 9+src/core/search/mode.ts 1754 ratchet +24 #8555 rewrite: search.qualified_aliases / search.title_qualified bundle fields, overrides, pick, config parse, KNOB_CONFIG_KEY rows and append-only qa=/tq= knobsHash parts; +12 #7175 (train R): search.keyword_phrase bundle field, config parse and knobsHash part; +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured); +5 GBRA-156 #7593: private-pages grant part in the cache key; +7 GBRA-218 A1: append-only xid=/xhp= knobsHash parts (member identity, operator privacy relaxation); +1 GBRA-231: append-only xau= knobsHash part (shared-agent audience identities) (re-summed at the train M .538 merge: 1717 measured); +1 GBRA-283 B2: import of the embedded engine reranker model (engine-gateway.ts); re-summed at the train R merge with v0.60.574.0: 1721 + 9src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)diff --git a/src/core/config.ts b/src/core/config.tsindex aeeea74b96..48a96cce80 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1419,6 +1419,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.collapse', // result-time collapse of twins, redirect stubs and document copies (mode.ts reads; boolean)'search.rank_priors', // rank priors after the reranker (mode.ts reads; boolean)'search.keyword_phrase', // keyword phrase factor, #7175 (mode.ts reads; boolean)+ 'search.qualified_aliases', // qualified alias hop (mode.ts reads; boolean)+ 'search.title_qualified', // qualified title boost (mode.ts reads; boolean)'search.diverse_pool_depth', // session-diverse pool before the reranker (mode.ts reads; `off` | 0..100; 0 = off)// Ranker wave (Phase E2): keyword-arm confidence floor — weak keyword arm fuses at half weight (mode.ts reads; `off` | (0, 1]).'search.keyword_arm_confidence_floor',diff --git a/src/core/search/alias-hop.ts b/src/core/search/alias-hop.tsindex 8e3c2ef51c..987efe9d84 100644--- a/src/core/search/alias-hop.ts+++ b/src/core/search/alias-hop.ts@@ -9,11 +9,17 @@ import { pageLeadSource, projectedLead } from '../page-window/bounded-lead.ts';import { isIdentityEntity } from '../entities/resolve.ts';import { normalizeAlias } from './alias-normalize.ts';import { isPrivatePageForCaller } from './private-visibility.ts';+import { contentTokenCount } from './title-match.ts';// T3 — free-text alias hop tuning.const ALIAS_HOP_PRESENT_BOOST = 1.10; // bounded boost when canonical already in resultsconst MAX_ALIAS_QUERY_TOKENS = 6; // skip long queries (clearly not a chosen name)const MAX_ALIAS_INJECT = 3; // cap injected pages per query (collision safety)+// Opt-in qualified hop (`search.qualified_aliases`): sub-phrase windows of a query up to this many tokens.+const MAX_QUALIFIED_QUERY_TOKENS = 14;+const MIN_QUALIFIED_WINDOW_TOKENS = 3;+const MAX_QUALIFIED_WINDOW_TOKENS = 6;+const MIN_QUALIFIED_CONTENT_TOKENS = 3;/*** T3 — free-text alias hop (retrieval-maxpool incident, the named-thing fix).@@ -27,6 +33,8 @@ const MAX_ALIAS_INJECT = 3; // cap injected pages per query (collision* Precision guards (Codex#7/#10):* - FULL normalized-query exact match only (not substring / not n-grams) —* "light" won't fire unless the whole query normalizes to a stored alias.+ * The opt-in qualified hop (`search.qualified_aliases`) is the one+ * sub-phrase path: one visible claimant, 3+ content tokens, own stamp.* - skip queries longer than MAX_ALIAS_QUERY_TOKENS (clearly prose, not a name).* - bounded: present-boost is 1.10x; inject score is top-of-organic + ε,* never an absolute 1.0 (D3 — aliases are not a ranking sledgehammer).@@ -62,31 +70,60 @@ export function isExcludedIdentity(slug: string, opts: Pick<IdentityTierOpts, 'e/*** A54 — the immutable half of the alias hop: the alias table read for the- * normalized query (plus its tokens under `tokenHop`). It never touches a- * result list, so the rerank gate can read it before reranking and the apply- * step reuses it after, and the alias table is read once per search.+ * normalized query (plus its tokens under `tokenHop`, and its qualified+ * windows under `qualified`). It never touches a result list, so the rerank+ * gate can read it before reranking and the apply step reuses it after, and+ * the alias table is read once per search.* `null` means the hop is a no-op for this query (empty, too long, or the- * table is missing / the read failed — fail-open, D9).+ * table is missing / the read failed — fail-open, D9). `fullQuery` is false+ * for a query over MAX_ALIAS_QUERY_TOKENS: only its qualified windows were+ * probed, so the full-query and token hops (and the rerank gate's alias+ * grades) keep the 6-token cap.*/export interface AliasHopLookup {qNorm: string;+ fullQuery: boolean;tokens: string[];+ qualified: string[];aliasMap: Map<string, Array<{ slug: string; source_id: string }>>;}+/**+ * Sub-phrase windows of the normalized query for the qualified hop: 3 to+ * min(6, n - 1) tokens, longest first, then leftmost, each with at least 3+ * content tokens, for a query of 3 to 14 tokens. At most 42 windows.+ */+export function qualifiedAliasCandidates(qNorm: string): string[] {+ const tokens = qNorm.split(' ');+ const n = tokens.length;+ if (n < MIN_QUALIFIED_WINDOW_TOKENS || n > MAX_QUALIFIED_QUERY_TOKENS) return [];+ const out = new Set<string>();+ for (let len = Math.min(MAX_QUALIFIED_WINDOW_TOKENS, n - 1); len >= MIN_QUALIFIED_WINDOW_TOKENS; len--) {+ for (let i = 0; i + len <= n; i++) {+ const phrase = tokens.slice(i, i + len).join(' ');+ if (contentTokenCount(phrase) >= MIN_QUALIFIED_CONTENT_TOKENS) out.add(phrase);+ }+ }+ return [...out];+}+export async function lookupAliasHop(engine: import('../engine.ts').BrainEngine,query: string,- opts: IdentityTierOpts & { tokenHop?: boolean },+ opts: IdentityTierOpts & { tokenHop?: boolean; qualified?: boolean },): Promise<AliasHopLookup | null> {if (!query) return null;const qNorm = normalizeAlias(query);- if (!qNorm || qNorm.split(' ').length > MAX_ALIAS_QUERY_TOKENS) return null;- const tokens = opts.tokenHop+ if (!qNorm) return null;+ const fullQuery = qNorm.split(' ').length <= MAX_ALIAS_QUERY_TOKENS;+ const qualified = opts.qualified ? qualifiedAliasCandidates(qNorm) : [];+ if (!fullQuery && qualified.length === 0) return null;+ const tokens = fullQuery && opts.tokenHop? [...new Set(qNorm.split(' '))].filter((t) => t.length >= 2 && t !== qNorm): [];+ const probe = fullQuery ? [qNorm, ...tokens, ...qualified] : qualified;try {- return { qNorm, tokens, aliasMap: await engine.resolveAliases([qNorm, ...tokens], opts) };+ return { qNorm, fullQuery, tokens, qualified, aliasMap: await engine.resolveAliases(probe, opts) };} catch {return null; // pre-v110 table-missing OR transient error -> fail-open}@@ -94,6 +131,7 @@ export async function lookupAliasHop(/** The full-query alias canonicals the hop would boost or inject: excludes applied, deterministic order, capped. */export function aliasHopCanonicals(lookup: AliasHopLookup, opts: IdentityTierOpts): Array<{ slug: string; source_id: string }> {+ if (!lookup.fullQuery) return [];return [...(lookup.aliasMap.get(lookup.qNorm) ?? [])].filter(ref => !isExcludedIdentity(ref.slug, opts)).sort((a, b) => (a.source_id === b.source_id ? a.slug.localeCompare(b.slug) : a.source_id.localeCompare(b.source_id)))@@ -104,7 +142,7 @@ export async function applyAliasHop(engine: import('../engine.ts').BrainEngine,results: SearchResult[],query: string,- opts: IdentityTierOpts & { tokenHop?: boolean },+ opts: IdentityTierOpts & { tokenHop?: boolean; qualified?: boolean },): Promise<SearchResult[]> {return applyAliasHopLookup(engine, results, await lookupAliasHop(engine, query, opts), opts);}@@ -117,8 +155,10 @@ export async function applyAliasHopLookup(opts: IdentityTierOpts,): Promise<SearchResult[]> {if (!lookup) return results;- const refs = lookup.aliasMap.get(lookup.qNorm);+ const refs = lookup.fullQuery ? lookup.aliasMap.get(lookup.qNorm) : undefined;if (!refs || refs.length === 0) {+ const led = await applyQualifiedAliasHop(engine, results, lookup, opts);+ if (led) return led;return lookup.tokens.length > 0 ? applyAliasTokenHop(engine, results, lookup.tokens, lookup.aliasMap, opts) : results;}@@ -153,6 +193,47 @@ export async function applyAliasHopLookup(return out;}+/**+ * The page the qualified hop leads with: the first window (longest, then+ * leftmost) that has a claimant after excludes decides. One claimant leads;+ * two or more suppress the hop. Claimants come from the caller's read policy,+ * so a page the caller cannot read never counts.+ */+function qualifiedAliasCanonical(lookup: AliasHopLookup, opts: IdentityTierOpts): { slug: string; source_id: string } | null {+ for (const phrase of lookup.qualified) {+ const refs = (lookup.aliasMap.get(phrase) ?? []).filter((ref) => !isExcludedIdentity(ref.slug, opts));+ if (refs.length > 0) return refs.length === 1 ? refs[0] : null;+ }+ return null;+}++/**+ * Opt-in qualified alias hop (`search.qualified_aliases`): moves the one page+ * whose alias is a sub-phrase of the query to the front at top-of-organic + ε,+ * or injects it when absent, stamped `qualified_alias_hit` (never+ * `alias_hit`: evidence does not read a mention as an identity match).+ * Returns null when it does not fire, so the token hop runs as before.+ */+async function applyQualifiedAliasHop(+ engine: import('../engine.ts').BrainEngine,+ results: SearchResult[],+ lookup: AliasHopLookup,+ opts: IdentityTierOpts,+): Promise<SearchResult[] | null> {+ const ref = qualifiedAliasCanonical(lookup, opts);+ if (!ref) return null;+ const score = topOrganicScore(results) + 1e-6;+ const idx = results.findIndex((r) => r.slug === ref.slug && (r.source_id ?? 'default') === ref.source_id);+ if (idx >= 0) {+ const out = [...results];+ const [hit] = out.splice(idx, 1);+ return [{ ...hit, score, qualified_alias_hit: true }, ...out];+ }+ const page = await fetchAliasCanonical(engine, ref, opts);+ if (!page) return null;+ return [await aliasInjectedRow(engine, page, ref, score, 'qualified_alias_hit'), ...results];+}+/** Cap on pages the single-token alias hop moves or injects per query. */const MAX_ALIAS_TOKEN_HOP = 2;@@ -223,7 +304,10 @@ async function fetchAliasCanonical(return page;}-async function aliasInjectedRow(engine: import('../engine.ts').BrainEngine, page: import('../types.ts').Page, ref: { source_id: string }, score: number): Promise<SearchResult> {+async function aliasInjectedRow(+ engine: import('../engine.ts').BrainEngine, page: import('../types.ts').Page, ref: { source_id: string }, score: number,+ stamp: 'alias_hit' | 'qualified_alias_hit' = 'alias_hit',+): Promise<SearchResult> {return {// #2339-sibling: include page_id. The `as SearchResult` cast hid its// absence, so any consumer reading page_id off an alias-injected result got@@ -240,6 +324,6 @@ async function aliasInjectedRow(engine: import('../engine.ts').BrainEngine, pagechunk_id: 0,score,base_score: score,- alias_hit: true,+ ...(stamp === 'alias_hit' ? { alias_hit: true } : { qualified_alias_hit: true }),} as SearchResult;}diff --git a/src/core/search/config-values.ts b/src/core/search/config-values.tsindex 92436b0b24..bf3dce1d4c 100644--- a/src/core/search/config-values.ts+++ b/src/core/search/config-values.ts@@ -1,6 +1,6 @@/**- * Set-time validation for the `search.*` keys whose value is an enum or a- * bounded number, so `gbrain config set` refuses a value the reader would+ * Set-time validation for the `search.*` keys whose value is an enum, a+ * boolean or a bounded number, so `gbrain config set` refuses a value the reader would* ignore (exit 2, `invalid_params`, nothing written) instead of storing it.*/import { HNSW_ITERATIVE_SCAN_KEY, HNSW_ITERATIVE_SCAN_MODES, hnswIterativeScanValueProblem } from './hnsw-iterative-scan.ts';@@ -8,6 +8,11 @@ import { CJK_KEYWORD_DEADLINE_DEFAULT_MS, CJK_KEYWORD_DEADLINE_KEY, cjkKeywordDeimport { AUTO_PACKING_CONFIG_KEY, DEFAULT_AUTO_PACKING, autoPackingValueProblem } from './evidence-packing.ts';import { DEFAULT_LONG_PAGE_MIN_CHARS, LONG_PAGE_MIN_CHARS_CONFIG_KEY, LONG_PAGE_UNIT_CONFIG_KEY, longPageMinCharsValueProblem, longPageUnitValueProblem } from './evidence-delivery.ts';import { DIVERSE_POOL_DEPTH_KEY, diversePoolDepthValueProblem } from './diverse-pool.ts';+import { parseBoolKnob } from './mode.ts';++/** A `search.*` boolean the mode reader parses with parseBoolKnob (true/false, on/off, 1/0). */+const booleanValueProblem = (key: string) => (value: string): string | null =>+ parseBoolKnob(value) === undefined ? `${key} must be true or false (got '${value}'). Nothing was written.` : null;interface SearchValueRule {problem: (value: string) => string | null;@@ -22,6 +27,8 @@ export const SEARCH_VALUE_RULES: Readonly<Record<string, SearchValueRule>> = {[LONG_PAGE_UNIT_CONFIG_KEY]: { problem: longPageUnitValueProblem, example: 'section' },[LONG_PAGE_MIN_CHARS_CONFIG_KEY]: { problem: longPageMinCharsValueProblem, example: String(DEFAULT_LONG_PAGE_MIN_CHARS) },[DIVERSE_POOL_DEPTH_KEY]: { problem: diversePoolDepthValueProblem, example: '100' },+ 'search.qualified_aliases': { problem: booleanValueProblem('search.qualified_aliases'), example: 'true' },+ 'search.title_qualified': { problem: booleanValueProblem('search.title_qualified'), example: 'true' },};/** The refusal for an invalid value of a validated `search.*` key, or null. */diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.tsindex 449480aea9..66bf97ad83 100644--- a/src/core/search/explain-formatter.ts+++ b/src/core/search/explain-formatter.ts@@ -13,6 +13,7 @@* + salience ×1.05 (mattering) ← when salience_boost > 1* + recency ×1.00 (no decay applied) ← when recency_boost > 1* + exact-match ×1.50 ← when exact_match_boost > 1+ * + title-mention ×1.25 ← when title_mention_boost > 1* + adjacency ×1.05 (hits=3) ← when graph_adjacency_boost set* + cross_source ×1.10 (other_sources=2) ← when graph_cross_source_boost set* - session_demote ×0.95 (prefix=chat/x) ← when session_demote_factor set@@ -81,6 +82,10 @@ export function formatResultExplain(anyBoost = true;lines.push(` + exact-match ×${fmt(result.exact_match_boost)}`);}+ if (result.title_mention_boost !== undefined && result.title_mention_boost !== 1.0) {+ anyBoost = true;+ lines.push(` + title-mention ×${fmt(result.title_mention_boost)}`);+ }if (result.graph_adjacency_boost !== undefined) {anyBoost = true;const hits = result.graph_adjacency_hits ?? '?';@@ -258,6 +263,7 @@ export function buildScoreDetails(result: SearchResult): ScoreDetails {add('recency', result.recency_boost);add('chronicle', result.chronicle_boost);add('title', result.title_match_boost);+ add('title_mention', result.title_mention_boost);add('adjacency', result.graph_adjacency_boost, { hits: result.graph_adjacency_hits });add('cross_source', result.graph_cross_source_boost, { other_sources: result.graph_cross_source_hits });add('session_demote', result.session_demote_factor, { prefix: result.graph_session_prefix });diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.tsindex bbd34b841f..ce68bec6f9 100644--- a/src/core/search/hybrid/rank.ts+++ b/src/core/search/hybrid/rank.ts@@ -461,12 +461,12 @@ export async function sizeReturnPool(minKeep: resolvedMode.autocut_min_keep,minTopScore: resolvedMode.autocut_min_top,},- // Preserve alias-hop exact matches: applyAliasHop injects the canonical+ // Preserve alias-hop matches (exact and qualified): applyAliasHop injects the canonical// page AFTER reranking, so it has no rerank_score. Without this it would// be dropped whenever autocut cuts on the scored set (Codex P1).// #1663: same guarantee for structural exact-lookup tier hits (slug /// exact-title identity matches also arrive post-rerank, unscored).- (x) => x.alias_hit === true || x.exact_lookup !== undefined || x.relational_pinned === true,+ (x) => x.alias_hit === true || x.qualified_alias_hit === true || x.exact_lookup !== undefined || x.relational_pinned === true,);returnPool = r.kept;autocutDecision = r.decision;diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex c123c93b6f..3f5e5b9a62 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -11,7 +11,7 @@ import type { DegradedStageEntry, HybridSearchMeta, SearchOpts, SearchResult } fimport { type GBrainConfig, loadConfigWithEngine } from '../../config.ts';import { type HybridSearchOpts, PRE_FUSION_POOL_FLOOR, compiledTruthFusionBoost } from '../hybrid.ts';import type { IdentityTierOpts } from '../alias-hop.ts';-import { type IntentWeights, applyAliasMentionBoost, applyExactMatchBoost, applyTitleMentionBoost, weightsForIntent } from '../intent-weights.ts';+import { type IntentWeights, applyAliasMentionBoost, applyExactMatchBoost, applyQualifiedTitleBoost, applyTitleMentionBoost, weightsForIntent } from '../intent-weights.ts';import { type QuerySuggestions, classifyQueryWithBrainPatterns } from '../query-intent.ts';import type { ResolveSearchModeInput, ResolvedSearchKnobs } from '../mode.ts';import { normalizeExpansionVariantBudget } from '../fusion-lists.ts';@@ -71,7 +71,7 @@ export interface HybridRequest {ctBoost: boolean | number;searchOpts: SearchOpts;identityTierOpts: IdentityTierOpts;- aliasHopOpts: IdentityTierOpts & { tokenHop: boolean };+ aliasHopOpts: IdentityTierOpts & { tokenHop: boolean; qualified: boolean };/** WP2/T3 degradation stamp, appended by every stage. */degraded: DegradedStageEntry[];/** v0.46.15: max-escalations searchVector exhaustion event, accumulated across vector calls. */@@ -318,6 +318,7 @@ export async function resolveHybridRequest(const aliasHopOpts = {...identityTierOpts,tokenHop: opts?.aliasTokenHop ?? modeInput.aliasTokenHop === 'true',+ qualified: resolvedMode.qualified_aliases,};// WP2/T3 — degradation stamp accumulated across stages. Emitted on EVERY// return path (empty array = clean run) so cache rows always carry the@@ -342,7 +343,8 @@ export async function resolveHybridRequest(}// Intent identity boosts (exact/mentioned title or slug, mentioned alias),- // shared by the fused path and both keyword-only paths. Caller re-sorts.+ // then the opt-in qualified title boost, which skips any row they raised.+ // Shared by the fused path and both keyword-only paths. Caller re-sorts.export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult[], generatedRead?: Promise<GeneratedPage[] | null>): 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 }, generatedRead);@@ -355,12 +357,13 @@ export async function applyIdentityBoosts(req: HybridRequest, list: SearchResultif (intentWeightingOn && suggestions.intent !== 'concept' && !isRelationalQuery(query, resolvedMode.relational_planner)) {applyTitleMentionBoost(list, query);}- return;+ } else {+ applyExactMatchBoost(list, query, intentWeights);+ await applyAliasMentionBoost(list, query, intentWeights, (aliases) => engine.resolveAliases(aliases, {+ sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate,+ }));}- applyExactMatchBoost(list, query, intentWeights);- await applyAliasMentionBoost(list, query, intentWeights, (aliases) => engine.resolveAliases(aliases, {- sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate,- }));+ if (resolvedMode.title_qualified && resolvedMode.title_boost) applyQualifiedTitleBoost(list, query, resolvedMode.title_boost);}// A throwing user callback must never break the search hot path — onMetadiff --git a/src/core/search/intent-weights.ts b/src/core/search/intent-weights.tsindex 7db6327616..9f4cd25833 100644--- a/src/core/search/intent-weights.ts+++ b/src/core/search/intent-weights.ts@@ -32,7 +32,8 @@import type { QueryIntent } from './query-intent.ts';import type { SearchResult } from '../types.ts';-import { containsTokenRun, isTitleMentionedInQuery, titleAsQuerySubject, tokenizeTitle } from './title-match.ts';+import { containsTokenRun, contentTokenCount, isTitleMentionedInQuery, isTitlePhraseMatch, titleAsQuerySubject, titleNameVariants, tokenizeTitle } from './title-match.ts';+import { isIdentityEntity } from '../entities/resolve.ts';/*** Weight adjustments to apply for a classified intent. All factors are@@ -192,6 +193,28 @@ export function applyTitleMentionBoost(results: SearchResult[], query: string):}}+/**+ * Opt-in qualified title boost (`search.title_qualified`): a person or company+ * page whose title (2+ content tokens) is mentioned inside the query, or+ * inside a given-name variant of it, gets `factor` (the title boost) and the+ * `title_mention_boost` stamp. Rows the title-phrase boost would match keep+ * that stage's floor, and a row an identity boost already raised+ * (`exact_match_boost`) is skipped, so boosts never stack. No floor: the row+ * is in the caller's pool already. Caller re-sorts.+ */+export function applyQualifiedTitleBoost(results: SearchResult[], query: string, factor: number): void {+ if (!query || !Number.isFinite(factor) || factor <= 1.0) return;+ const queries = [query, ...titleNameVariants(query)];+ for (const r of results) {+ const title = r.title ?? '';+ if (!title || r.exact_match_boost !== undefined || !Number.isFinite(r.score)) continue;+ if (!isIdentityEntity(r.slug, r.type) || contentTokenCount(title) < 2) continue;+ if (queries.some(q => isTitlePhraseMatch(q, title)) || !queries.some(q => isTitleMentionedInQuery(q, title))) continue;+ r.score *= factor;+ r.title_mention_boost = factor;+ }+}+/** Longest alias n-gram looked up for a query mention (tokens). */const MAX_ALIAS_MENTION_TOKENS = 5;diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 4f4bab07de..da607fa977 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -429,6 +429,10 @@ export interface ModeBundle {rank_priors: boolean;/** #7175: keyword phrase factor (sql-ranking.ts KEYWORD_PHRASE_FACTOR). Off in every bundle (opt-in). Override: `search.keyword_phrase` (boolean). */keyword_phrase: boolean;+ /** Qualified alias hop (alias-hop.ts): a 3-6 token sub-phrase of the query that is one readable page's alias leads. Off in every bundle (opt-in). Override: `search.qualified_aliases` (boolean). */+ qualified_aliases: boolean;+ /** Qualified title boost (intent-weights.ts): a person or company title mentioned inside the query. Off in every bundle (opt-in). Override: `search.title_qualified` (boolean). */+ title_qualified: boolean;/*** Ranker wave (Phase E2, Cat 13) — arm-confidence-weighted fusion of the* LEXICAL arms (arm-confidence.ts). When the keyword arm's scale-free@@ -539,6 +543,8 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =collapse: true,rank_priors: true,keyword_phrase: false,+ qualified_aliases: false,+ title_qualified: false,autocut_jump: 0.2,autocut_min_top: 0.35,autocut_min_keep: 1,@@ -611,6 +617,8 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =collapse: true,rank_priors: true,keyword_phrase: false,+ qualified_aliases: false,+ title_qualified: false,autocut_jump: 0.2,autocut_min_top: 0.35,autocut_min_keep: 1,@@ -683,6 +691,8 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =collapse: true,rank_priors: true,keyword_phrase: false,+ qualified_aliases: false,+ title_qualified: false,autocut_jump: 0.2,autocut_min_top: 0.35,autocut_min_keep: 1,@@ -758,6 +768,8 @@ export interface SearchKeyOverrides {collapse?: boolean;rank_priors?: boolean;keyword_phrase?: boolean;+ qualified_aliases?: boolean;+ title_qualified?: boolean;// Ranker wave (Phase E2) — keyword-arm confidence floor override (null = off; (0, 1]).keyword_arm_confidence_floor?: number | null;// Ranker wave (Phase E3) — metadata boost gate override (`always` | `lexical`).@@ -832,6 +844,8 @@ export interface SearchPerCallOpts {collapse?: boolean;rank_priors?: boolean;keyword_phrase?: boolean;+ qualified_aliases?: boolean;+ title_qualified?: boolean;// Ranker wave (Phase E2) — keyword-arm confidence floor per-call override (null = off; (0, 1]).keyword_arm_confidence_floor?: number | null;// Ranker wave (Phase E3) — metadata boost gate per-call override (`always` | `lexical`).@@ -946,6 +960,8 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearchcollapse: pick('collapse'),rank_priors: pick('rank_priors'),keyword_phrase: pick('keyword_phrase'),+ qualified_aliases: pick('qualified_aliases'),+ title_qualified: pick('title_qualified'),keyword_arm_confidence_floor: pick('keyword_arm_confidence_floor'),metadata_boost_gate: pick('metadata_boost_gate'),resolved_mode,@@ -1307,6 +1323,8 @@ export function knobsHash(...(knobs.collapse === false ? ['col=0'] : []),...(knobs.rank_priors === false ? ['rpr=0'] : []),...(knobs.keyword_phrase === true ? ['kph=1'] : []),+ ...(knobs.qualified_aliases === true ? ['qa=1'] : []),+ ...(knobs.title_qualified === true ? ['tq=1'] : []),];// #5691 (append-only, no version bump): only a non-empty query prefix adds// a part, so every row written without one keeps its key.@@ -1567,6 +1585,10 @@ export function loadOverridesFromConfig(if (rpr !== undefined) out.rank_priors = rpr;const kph = parseBoolKnob(get('search.keyword_phrase'));if (kph !== undefined) out.keyword_phrase = kph;+ const qa = parseBoolKnob(get('search.qualified_aliases'));+ if (qa !== undefined) out.qualified_aliases = qa;+ const tq = parseBoolKnob(get('search.title_qualified'));+ if (tq !== undefined) out.title_qualified = tq;// Ranker wave (Phase E2) — keyword-arm confidence floor: the literal// `off`/`null` pins the knob off (null); a number in (0, 1] is the floor;// anything else falls through to the bundle. ONE range contract with the@@ -1644,6 +1666,8 @@ export const KNOB_CONFIG_KEY: Readonly<Record<keyof ModeBundle, string>> = Objeccollapse: 'search.collapse',rank_priors: 'search.rank_priors',keyword_phrase: 'search.keyword_phrase',+ qualified_aliases: 'search.qualified_aliases',+ title_qualified: 'search.title_qualified',keyword_arm_confidence_floor: 'search.keyword_arm_confidence_floor',metadata_boost_gate: 'search.metadata_boost_gate',});diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex 008bfbb6a7..3e4496d7d9 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -69,6 +69,8 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {collapse: 'Result-time collapse: same-slug twins in other sources, redirect stubs and copies of one document fold into the best row (listed in collapsed)',rank_priors: 'Rank priors after the reranker: organization over person when no person is named, weak OCR matches, dated over undated rows on when-questions',keyword_phrase: 'Keyword phrase factor (opt-in): a chunk holding the query as one contiguous phrase ranks higher in the keyword arm',+ qualified_aliases: 'Qualified alias hop (opt-in): a 3-6 word phrase inside the query that is the alias of exactly one readable page leads with that page',+ title_qualified: 'Qualified title boost (opt-in): a person or company title mentioned inside a longer query gets the title boost',diverse_pool_depth: 'Session-diverse pool before the reranker: each arm fetches at least N candidates, one row per session, the reranker reads at least N (0..100; 0 = off)',// Ranker wave (Phase E2) arm-confidence fusionkeyword_arm_confidence_floor: 'Keyword-arm confidence floor: below this margin ratio the keyword + title lists fuse at half weight (null = off; (0, 1])',diff --git a/src/core/search/remote-page-cap.ts b/src/core/search/remote-page-cap.tsindex 0161d3d9bb..4e95c8cd52 100644--- a/src/core/search/remote-page-cap.ts+++ b/src/core/search/remote-page-cap.ts@@ -49,7 +49,7 @@ export function pageCapLine(retrieval: unknown, how = 'limit'): string | null {}function hasLexicalEvidence(r: SearchResult): boolean {- return r.keyword_hit === true || r.alias_hit === true || r.exact_lookup !== undefined || r.relational_pinned === true;+ return r.keyword_hit === true || r.alias_hit === true || r.qualified_alias_hit === true || r.exact_lookup !== undefined || r.relational_pinned === true;}/** Keeps every lexically matched page and the top vector-only pages up to `cap` distinct pages. */diff --git a/src/core/search/title-match.ts b/src/core/search/title-match.tsindex bc55670ea9..b7d437261f 100644--- a/src/core/search/title-match.ts+++ b/src/core/search/title-match.ts@@ -49,6 +49,11 @@ function contentTokens(tokens: string[]): string[] {return tokens.filter(t => !STOPWORDS.has(t));}+/** Number of non-stopword tokens in `s`. */+export function contentTokenCount(s: string): number {+ return contentTokens(tokenizeTitle(s)).length;+}+/** True iff `needle` appears as a contiguous token run inside `haystack`. */function containsTokenRun(haystack: string[], needle: string[]): boolean {if (needle.length === 0 || needle.length > haystack.length) return false;diff --git a/src/core/types.ts b/src/core/types.tsindex 516c29a4f2..101533a88d 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1089,6 +1089,8 @@ export interface SearchResult {* keys off base_score / evidence, not the boosted score).*/title_match_boost?: number;+ /** Multiplier from the opt-in qualified title boost (`search.title_qualified`); evidence never reads it as an exact title match. */+ title_mention_boost?: number;/*** T3 (retrieval-maxpool incident) — set when this result was surfaced or* boosted by the free-text alias hop (the query exactly matched a page's@@ -1098,6 +1100,8 @@ export interface SearchResult {* decision keys off (T4).*/alias_hit?: boolean;+ /** Opt-in qualified alias hop (`search.qualified_aliases`) led this page; autocut and the remote page cap keep it, evidence ignores it. */+ qualified_alias_hit?: boolean;/*** #3783 — set when this result was surfaced by a LEXICAL arm (chunk-grain* keyword FTS or the page-grain title arm). Stamped pre-fusion bydiff --git a/test/config-set-unread-prefixed-key.test.ts b/test/config-set-unread-prefixed-key.test.tsindex 8d6567ce07..3a42d3fb8b 100644--- a/test/config-set-unread-prefixed-key.test.ts+++ b/test/config-set-unread-prefixed-key.test.ts@@ -14,6 +14,7 @@import { describe, expect, spyOn, test } from 'bun:test';import { KNOWN_CONFIG_KEYS, loadConfigWithEngine } from '../src/core/config.ts';import { runConfig } from '../src/commands/config.ts';+import { searchConfigValueRefusal } from '../src/core/search/config-values.ts';import type { BrainEngine } from '../src/core/engine.ts';function stubEngine(): { engine: BrainEngine; setCalls: Array<[string, string]>; unsetCalls: string[] } {@@ -135,3 +136,24 @@ test('every key loadConfigWithEngine reads under search.* or content_sanity.* isexpect(underPrefix.some((k) => k.startsWith('content_sanity.'))).toBe(true);expect(underPrefix.filter((k) => !KNOWN_CONFIG_KEYS.includes(k))).toEqual([]);});++describe('config set: the qualified search switches take a boolean', () => {+ for (const key of ['search.qualified_aliases', 'search.title_qualified']) {+ test(`${key} maybe: refused (exit 2, invalid_params), nothing written`, async () => {+ const { engine, setCalls } = stubEngine();+ const { errs, exit } = await runConfigCapture(engine, ['set', key, 'maybe']);+ expect(exit).toBe(2);+ expect(setCalls).toEqual([]);+ expect(errs).toContain(`Error [invalid_params]: ${key} must be true or false (got 'maybe'). Nothing was written.`);+ expect(errs).toContain(`Fix: gbrain config get ${key}`);+ expect(searchConfigValueRefusal(key, 'maybe')?.example).toBe('true');+ });++ test(`${key} true is written`, async () => {+ const { engine, setCalls } = stubEngine();+ const { exit } = await runConfigCapture(engine, ['set', key, 'true']);+ expect(exit).toBeNull();+ expect(setCalls).toEqual([[key, 'true']]);+ });+ }+});diff --git a/test/e2e/qualified-alias-visibility-postgres.test.ts b/test/e2e/qualified-alias-visibility-postgres.test.tsnew file mode 100644index 0000000000..3ee5fe6624--- /dev/null+++ b/test/e2e/qualified-alias-visibility-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../search/qualified-alias-visibility.test.ts'));diff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex a7cb18ecd8..613c4c87f1 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -97,6 +97,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {collapse: true,rank_priors: true,keyword_phrase: false,+ qualified_aliases: false,+ title_qualified: false,// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).@@ -149,6 +151,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {collapse: true,rank_priors: true,keyword_phrase: false,+ qualified_aliases: false,+ title_qualified: false,// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).@@ -200,6 +204,8 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {collapse: true,rank_priors: true,keyword_phrase: false,+ qualified_aliases: false,+ title_qualified: false,// ranker wave (Phase E2) — keyword-arm confidence floor OFF in every bundle until the Cat 13 receipt.keyword_arm_confidence_floor: null,// ranker wave (Phase E3) — metadata boost gate `lexical` in every bundle since the Cat 13 held-out receipt (`always` = pre-wave pipeline).@@ -1155,3 +1161,31 @@ describe('multi-hop planner knobs (relational_planner, relational_orient_onehop)expect(new Set([dflt, off, onSlots, orient]).size).toBe(4);});});++describe('qualified_aliases / title_qualified mode knobs', () => {+ test('off in every bundle', () => {+ for (const m of ['conservative', 'balanced', 'tokenmax'] as const) {+ expect(MODE_BUNDLES[m].qualified_aliases).toBe(false);+ expect(MODE_BUNDLES[m].title_qualified).toBe(false);+ }+ });++ test('config parses into the overrides; a bad value is ignored', () => {+ expect(loadOverridesFromConfig({ 'search.qualified_aliases': 'true' }).qualified_aliases).toBe(true);+ expect(loadOverridesFromConfig({ 'search.title_qualified': 'on' }).title_qualified).toBe(true);+ expect(loadOverridesFromConfig({ 'search.qualified_aliases': 'false' }).qualified_aliases).toBe(false);+ expect(loadOverridesFromConfig({ 'search.qualified_aliases': 'maybe' }).qualified_aliases).toBeUndefined();+ expect(loadOverridesFromConfig({ 'search.title_qualified': 'yes please' }).title_qualified).toBeUndefined();+ expect(resolveSearchMode({ mode: 'balanced', overrides: { qualified_aliases: true } }).qualified_aliases).toBe(true);+ });++ test('knobsHash: off keeps every existing key; each knob on segregates the cache on its own', () => {+ const dflt = knobsHash(resolveSearchMode({ mode: 'balanced' }));+ const explicitOff = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { qualified_aliases: false, title_qualified: false } }));+ const qa = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { qualified_aliases: true } }));+ const tq = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { title_qualified: true } }));+ const both = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { qualified_aliases: true, title_qualified: true } }));+ expect(explicitOff).toBe(dflt);+ expect(new Set([dflt, qa, tq, both]).size).toBe(4);+ });+});diff --git a/test/search-remote-page-cap.test.ts b/test/search-remote-page-cap.test.tsindex bb79979f78..1fa3c419d0 100644--- a/test/search-remote-page-cap.test.ts+++ b/test/search-remote-page-cap.test.ts@@ -49,6 +49,11 @@ describe('capVectorOnlyPages', () => {expect(out.meta).toEqual({ cap: 3, kept_pages: 3, dropped_pages: 3 });});+ test('a qualified alias hit is lexical evidence and is kept past the cap', () => {+ const rows = [row('v1'), row('v2'), row('q1', { qualified_alias_hit: true })];+ expect(capVectorOnlyPages(rows, 2).rows.map(r => r.slug)).toEqual(['v1', 'q1']);+ });+test('more lexical pages than the cap are all kept and no vector-only page is added', () => {const rows = [row('k1', { keyword_hit: true }), row('v1'), row('k2', { exact_lookup: 'slug' }), row('k3', { relational_pinned: true }), row('k4', { keyword_hit: true, keyword_relaxed: true })];expect(capVectorOnlyPages(rows, 2).rows.map(r => r.slug)).toEqual(['k1', 'k2', 'k3', 'k4']);diff --git a/test/search/alias-hop.test.ts b/test/search/alias-hop.test.tsindex fdc146626d..02830fa79c 100644--- a/test/search/alias-hop.test.ts+++ b/test/search/alias-hop.test.ts@@ -123,6 +123,115 @@ describe('applyAliasHop', () => {});});+describe('applyAliasHop — qualified alias hop (search.qualified_aliases)', () => {+ const company = async (slug = 'projects/acme-widget-project', alias = 'acme widget project') => {+ await engine.putPage(slug, { type: 'project', title: slug, compiled_truth: 'Widget project notes.' });+ await engine.setPageAliases(slug, 'default', [alias]);+ };+ const on = { sourceId: 'default', qualified: true };++ test('off by default: a 3-token alias inside a longer query does nothing', async () => {+ await company();+ const organic = [res('chats/log', 0.9)];+ const out = await applyAliasHop(engine, organic, 'status of the acme widget project today', { sourceId: 'default' });+ expect(out.map(r => r.slug)).toEqual(['chats/log']);+ });++ test('on: a sole absent claimant is injected, leads, and carries its own stamp', async () => {+ await company();+ const out = await applyAliasHop(engine, [res('chats/log', 0.9), res('notes/x', 0.4)], 'status of the acme widget project today', on);+ expect(out.map(r => r.slug)).toEqual(['projects/acme-widget-project', 'chats/log', 'notes/x']);+ expect(out[0].qualified_alias_hit).toBe(true);+ expect(out[0].alias_hit).toBeUndefined();+ expect(out[0].score).toBeGreaterThan(0.9);+ });++ test('on: a present claimant leads too; the rest keep their order', async () => {+ await company();+ const organic = [res('chats/log', 0.9), res('notes/x', 0.7), res('projects/acme-widget-project', 0.2)];+ const out = await applyAliasHop(engine, organic, 'status of the acme widget project today', on);+ expect(out.map(r => r.slug)).toEqual(['projects/acme-widget-project', 'chats/log', 'notes/x']);+ expect(out[0].qualified_alias_hit).toBe(true);+ expect(out[0].alias_hit).toBeUndefined();+ expect(out[0].score).toBeGreaterThan(0.9);+ });++ test('on: two claimants of the phrase suppress the hop', async () => {+ await company('projects/acme-widget-project');+ await company('projects/acme-widget-project-two');+ const out = await applyAliasHop(engine, [res('chats/log', 0.9)], 'status of the acme widget project today', on);+ expect(out.map(r => r.slug)).toEqual(['chats/log']);+ });++ test('on: an alias with two content tokens ("hall of light") never hops', async () => {+ await company('projects/mingtang', 'hall of light');+ const out = await applyAliasHop(engine, [res('chats/log', 0.9)], 'notes on the hall of light renovation', on);+ expect(out.map(r => r.slug)).toEqual(['chats/log']);+ });++ test('on: a 7-14 token query probes; a 15-token one does not', async () => {+ await company();+ const ten = 'please summarize what we decided about the acme widget project';+ const fourteen = 'please summarize what we decided last week about the acme widget project in detail';+ const fifteen = 'please summarize what we decided last week about the acme widget project in more detail';+ expect(fourteen.split(' ').length).toBe(14);+ expect(fifteen.split(' ').length).toBe(15);+ expect((await applyAliasHop(engine, [], ten, on)).map(r => r.slug)).toEqual(['projects/acme-widget-project']);+ expect((await applyAliasHop(engine, [], fourteen, on)).map(r => r.slug)).toEqual(['projects/acme-widget-project']);+ expect(await applyAliasHop(engine, [], fifteen, on)).toEqual([]);+ });++ test('on: excludeSlugs and a prefix exclude leave the visible claimant to fire', async () => {+ await company('projects/acme-widget-project');+ await company('archive/acme-widget-project');+ const q = 'status of the acme widget project today';+ expect((await applyAliasHop(engine, [], q, { ...on, excludeSlugs: ['archive/acme-widget-project'] })).map(r => r.slug))+ .toEqual(['projects/acme-widget-project']);+ expect((await applyAliasHop(engine, [], q, { ...on, excludeSlugPrefixes: ['archive/'] })).map(r => r.slug))+ .toEqual(['projects/acme-widget-project']);+ });++ test('on: a full-query alias still wins over a qualified one', async () => {+ await company('projects/acme-widget-project', 'acme widget project');+ await company('projects/acme-widget-project-review', 'acme widget project review');+ const out = await applyAliasHop(engine, [], 'acme widget project review', on);+ expect(out.map(r => r.slug)).toEqual(['projects/acme-widget-project-review']);+ expect(out[0].alias_hit).toBe(true);+ expect(out[0].qualified_alias_hit).toBeUndefined();+ });++ test('on: a query over 6 tokens never fires the full-query alias hop or the token hop', async () => {+ const long = 'acme quarterly planning notes and minutes from monday morning';+ await engine.putPage('notes/long-alias', { type: 'note', title: 'Long', compiled_truth: 'x' });+ await engine.setPageAliases('notes/long-alias', 'default', [long]);+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'y' });+ await engine.setPageAliases('companies/acme-example', 'default', ['acme']);+ const out = await applyAliasHop(engine, [res('chats/log', 0.9)], long, { ...on, tokenHop: true });+ expect(out.map(r => r.slug)).toEqual(['chats/log']);+ });++ test('one alias-table read per lookup, holding the qualified windows; off probes exactly what it did before', async () => {+ const calls: string[][] = [];+ const counting = new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'resolveAliases') return (aliases: string[], opts: unknown) => { calls.push(aliases); return target.resolveAliases(aliases, opts as never); };+ return Reflect.get(target, prop, receiver);+ },+ });+ await company();+ const q = 'status of acme widget project today';+ await applyAliasHop(counting, [], q, { sourceId: 'default' });+ expect(calls).toEqual([[q]]);+ calls.length = 0;+ const out = await applyAliasHop(counting, [], q, on);+ expect(calls.length).toBe(1);+ expect(calls[0][0]).toBe(q);+ expect(calls[0]).toContain('acme widget project');+ expect(calls[0].length).toBeLessThanOrEqual(1 + 42);+ expect(out.map(r => r.slug)).toEqual(['projects/acme-widget-project']);+ });+});+describe('ingest projection (importFromContent)', () => {test('frontmatter aliases: land in page_aliases on import', async () => {const md = `---\ntype: note\ntitle: The Mingtang\naliases:\n - Hall of Light\n - 明堂\n---\nIndoor Greek amphitheater.`;diff --git a/test/search/explain-formatter.test.ts b/test/search/explain-formatter.test.tsindex 9399051c07..946ecceca5 100644--- a/test/search/explain-formatter.test.ts+++ b/test/search/explain-formatter.test.ts@@ -12,6 +12,7 @@ import {formatResultsExplain,formatAutocutSummary,formatDegradedSummary,+ buildScoreDetails,} from '../../src/core/search/explain-formatter.ts';import type { AutocutDecision } from '../../src/core/search/autocut.ts';@@ -48,6 +49,14 @@ describe('formatResultExplain — no boosts', () => {});describe('formatResultExplain — every boost type', () => {+ test('title_mention_boost (search.title_qualified) renders apart from the exact title boost', () => {+ const res = r('people/alice-example', 1.25, { base_score: 1.0, title_mention_boost: 1.25 });+ const out = formatResultExplain(res, 1);+ expect(out).toContain('+ title-mention ×1.25');+ expect(out).not.toContain('no boosts applied');+ expect(buildScoreDetails(res).boosts).toEqual({ title_mention: { factor: 1.25 } });+ });+test('backlink_boost renders', () => {const out = formatResultExplain(r('a/b', 1.5, { base_score: 1.0, backlink_boost: 1.5 }),diff --git a/test/search/qualified-alias-visibility.test.ts b/test/search/qualified-alias-visibility.test.tsnew file mode 100644index 0000000000..0b46962d0a--- /dev/null+++ b/test/search/qualified-alias-visibility.test.ts@@ -0,0 +1,96 @@+/**+ * search.qualified_aliases under the read policy, on a repo-less brain+ * (in-memory PGLite; Postgres too when DATABASE_URL is set, and through+ * test/e2e/qualified-alias-visibility-postgres.test.ts).+ *+ * 1. Protects: the qualified alias hop counts and injects only pages the+ * caller can read. A page restricted by `readable_by` or marked+ * `visibility: private` never hops in, never suppresses a readable+ * claimant of the same phrase, and so its existence never shows.+ * 2. Fails when: the claimant read skips the caller's member access or the+ * private predicate, or the inject path skips the private re-check.+ * 3. Real seams: engine.resolveAliases and getPage under withCallerAccess,+ * and the MCP `search` op with remote: true.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { applyAliasHop } from '../../src/core/search/hybrid.ts';+import { withCallerAccess, __resetPrivateVisibilityCacheForTests } from '../../src/core/search/private-visibility.ts';+import { addMember, memberIdentity } from '../../src/core/access/members.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const SRC = 'source-a';+const Q = 'status of the acme widget project today';++for (const kind of testBackends()) {+ describe(`qualified alias hop under the read policy (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ async function put(slug: string, fm: string, alias = 'acme widget project') {+ await importFromContent(engine, slug, `---\ntype: project\ntitle: Codename Falcon\naliases: [${alias}]\n${fm}\n---\nQuarterly figures.`, { sourceId: SRC, noEmbed: true });+ }+ async function hop(member: string | null, excludePrivate = true): Promise<string[]> {+ const run = () => applyAliasHop(engine, [], Q, { sourceId: SRC, excludePrivate, qualified: true });+ if (!member) return (await run()).map(r => r.slug);+ const { identity } = await memberIdentity(engine, member);+ return (await withCallerAccess({ identity, applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] }, run)).map(r => r.slug);+ }++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ await addMember(engine, 'alice-example');+ await addMember(engine, 'bob-example');+ }, 120_000);++ afterAll(async () => {+ resetGateway();+ await close?.();+ }, 60_000);++ test('a sole claimant readable only by bob never hops in for alice', async () => {+ await put('projects/falcon-bob', 'readable_by: [bob-example]');+ expect(await hop('bob-example')).toEqual(['projects/falcon-bob']);+ expect(await hop('alice-example')).toEqual([]);+ }, 60_000);++ test('a claimant alice cannot read does not suppress the one she can', async () => {+ await put('projects/falcon-open', '');+ expect(await hop('alice-example')).toEqual(['projects/falcon-open']);+ expect(await hop('bob-example')).toEqual([]);+ }, 60_000);++ test('a visibility: private claimant is skipped under excludePrivate', async () => {+ await put('projects/falcon-bob', 'readable_by: [bob-example]', 'beta gamma widget');+ await put('projects/falcon-private', 'visibility: private');+ expect(await hop(null)).toEqual(['projects/falcon-open']);+ expect(await hop(null, false)).toEqual([]);+ }, 60_000);++ test('MCP search with remote: true injects only the readable claimant', async () => {+ await importFromContent(engine, 'notes/status-log', '---\ntype: note\ntitle: Status log\n---\nStatus of the week, written today.', { sourceId: SRC, noEmbed: true });+ const before = await dispatchToolCall(engine, 'search', { query: Q }, { remote: true, transport: 'http', sourceId: SRC } as never);+ expect(before.content.map(c => c.text ?? '').join('\n')).not.toContain('projects/falcon-open');+ await engine.setConfig('search.qualified_aliases', 'true');+ try {+ const r = await dispatchToolCall(engine, 'search', { query: Q }, { remote: true, transport: 'http', sourceId: SRC } as never);+ const rows = JSON.parse(r.content[0].text!) as Array<{ slug: string }>;+ const text = r.content.map(c => c.text ?? '').join('\n');+ expect(rows[0]?.slug).toBe('projects/falcon-open');+ expect(text).not.toContain('projects/falcon-private');+ expect(text).not.toContain('projects/falcon-bob');+ } finally {+ await engine.setConfig('search.qualified_aliases', 'false');+ }+ }, 60_000);+ });+}diff --git a/test/search/title-boost-stage.test.ts b/test/search/title-boost-stage.test.tsindex d9ee1928b6..88f1c804fc 100644--- a/test/search/title-boost-stage.test.ts+++ b/test/search/title-boost-stage.test.ts@@ -7,6 +7,8 @@import { describe, test, expect } from 'bun:test';import { applyTitleBoost, DEFAULT_TITLE_BOOST } from '../../src/core/search/hybrid.ts';import type { SearchResult } from '../../src/core/types.ts';+import { applyIdentityBoosts, type HybridRequest } from '../../src/core/search/hybrid/request.ts';+import { weightsForIntent } from '../../src/core/search/intent-weights.ts';function mk(slug: string, title: string, score: number): SearchResult {return {@@ -72,3 +74,80 @@ describe('applyTitleBoost — given-name variants (#7471)', () => {expect(other.title_match_boost).toBeUndefined();});});++describe('qualified title boost (search.title_qualified)', () => {+ const person = (score = 0.5) => ({ ...mk('people/alice-example', 'Alice Example', score), type: 'person' }) as SearchResult;+ const stubEngine = { resolveAliases: async () => new Map(), getConfig: async () => null } as never;+ // intent null: intent weighting off, so only the qualified arm can move a score.+ const run = async (list: SearchResult[], query: string, on: boolean, intent: 'general' | 'entity' | null = null) => {+ const req = {+ engine: stubEngine, query, opts: {}, suggestions: { intent: intent ?? 'general' }, intentWeightingOn: intent !== null,+ intentWeights: weightsForIntent(intent ?? 'general'),+ resolvedMode: { relational_planner: false, title_qualified: on, title_boost: DEFAULT_TITLE_BOOST },+ } as unknown as HybridRequest;+ await applyIdentityBoosts(req, list, Promise.resolve(null));+ return list;+ };+ const Q = 'acme widget team lead alice example';++ test('a person title inside the query is boosted only when on, whatever its score', async () => {+ const off = (await run([person(0.01)], Q, false))[0];+ expect(off.score).toBe(0.01);+ expect(off.title_mention_boost).toBeUndefined();+ const on = (await run([person(0.01)], Q, true))[0];+ expect(on.score).toBeCloseTo(0.01 * DEFAULT_TITLE_BOOST, 8);+ expect(on.title_mention_boost).toBe(DEFAULT_TITLE_BOOST);+ expect(on.title_match_boost).toBeUndefined();+ });++ test('general intent: on, with intent weighting, the person page is boosted once', async () => {+ const r = (await run([person(0.5)], Q, true, 'general'))[0];+ expect(r.title_mention_boost).toBe(DEFAULT_TITLE_BOOST);+ expect(r.score).toBeCloseTo(0.5 * DEFAULT_TITLE_BOOST, 8);+ });++ test('a generic 3-token note title and a one-token company title are not boosted', async () => {+ const note = mk('meetings/weekly-team-sync', 'Weekly Team Sync', 0.5);+ const company = { ...mk('companies/acme', 'Acme', 0.5), type: 'company' } as SearchResult;+ await run([note, company], 'action items and owners from the weekly team sync at acme corp', true);+ expect(note.title_mention_boost).toBeUndefined();+ expect(company.title_mention_boost).toBeUndefined();+ expect(note.score).toBe(0.5);+ expect(company.score).toBe(0.5);+ });++ test('a forward title match keeps the floor: no qualified boost for it', async () => {+ const r = person(0.01);+ await run([r], 'alice example', true);+ expect(r.title_mention_boost).toBeUndefined();+ expect(r.score).toBe(0.01);+ });++ test('a row that already carries exact_match_boost gets no second boost', async () => {+ const r = { ...person(0.5), exact_match_boost: 1.18 } as SearchResult;+ await run([r], Q, true);+ expect(r.title_mention_boost).toBeUndefined();+ expect(r.score).toBe(0.5);+ });++ test('general intent: a title the #4694 subject boost already raised gets no second boost', async () => {+ const r = (await run([person(0.5)], 'acme alice example', true, 'general'))[0];+ expect(r.exact_match_boost).toBeDefined();+ expect(r.title_mention_boost).toBeUndefined();+ expect(r.score).toBeCloseTo(0.5 * r.exact_match_boost!, 8);+ });++ test('under entity intent a mentioned person page gets exactly one multiplier', async () => {+ const r = person(0.5);+ await run([r], 'who is alice example at acme', true, 'entity');+ expect(r.exact_match_boost).toBe(weightsForIntent('entity').exactMatchBoost);+ expect(r.title_mention_boost).toBeUndefined();+ expect(r.score).toBeCloseTo(0.5 * weightsForIntent('entity').exactMatchBoost, 8);+ });++ test('a given-name variant of the query counts as a mention', async () => {+ const r = { ...mk('people/matthew-examplesurname', 'Matthew Examplesurname', 0.5), type: 'person' } as SearchResult;+ await run([r], 'matt examplesurname at acme', true);+ expect(r.title_mention_boost).toBe(DEFAULT_TITLE_BOOST);+ });+});diff --git a/test/search/title-retrieval-arm.test.ts b/test/search/title-retrieval-arm.test.tsindex 900bb4aa06..a0d0e3e8af 100644--- a/test/search/title-retrieval-arm.test.ts+++ b/test/search/title-retrieval-arm.test.ts@@ -390,3 +390,50 @@ describe('hybridSearch wiring — title arm reaches the fused result set', () =>expect(results.map(r => r.slug)).toContain('projects/chronomancer');});});++describe('hybridSearch wiring — search.qualified_aliases and search.title_qualified (keyless, repo-less)', () => {+ async function seed(): Promise<void> {+ await engine.putPage('projects/codename-falcon', { type: 'project', title: 'Codename Falcon', compiled_truth: 'Quarterly figures.' });+ await engine.setPageAliases('projects/codename-falcon', 'default', ['acme widget project']);+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Leads the widget team at acme. Owns the roadmap and the budget.' });+ await engine.putPage('notes/status', { type: 'note', title: 'Status', compiled_truth: 'Widget team status at acme with alice example mentioned, roadmap budget roadmap.' });+ for (const slug of ['projects/codename-falcon', 'people/alice-example', 'notes/status']) {+ const page = await engine.getPage(slug);+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: page!.compiled_truth, chunk_source: 'compiled_truth' }]);+ }+ }+ const off = async () => {+ await engine.setConfig('search.qualified_aliases', 'false');+ await engine.setConfig('search.title_qualified', 'false');+ };++ test('qualified_aliases: off leaves the alias page out; on injects it first, with evidence short of exists', async () => {+ await seed();+ const q = 'status of the acme widget project today';+ try {+ expect((await hybridSearch(engine, q, { limit: 5 })).map(r => r.slug)).not.toContain('projects/codename-falcon');+ await engine.setConfig('search.qualified_aliases', 'true');+ const on = await hybridSearch(engine, q, { limit: 5 });+ expect(on[0].slug).toBe('projects/codename-falcon');+ expect(on[0].qualified_alias_hit).toBe(true);+ expect(on[0].alias_hit).toBeUndefined();+ expect(on[0].evidence).not.toBe('alias_hit');+ expect(on[0].create_safety).not.toBe('exists');+ } finally { await off(); }+ });++ test('title_qualified: a person title inside the query gets title_mention_boost only when on, never an exact-title evidence', async () => {+ await seed();+ const q = 'acme widget team lead alice example roadmap budget';+ try {+ const before = (await hybridSearch(engine, q, { limit: 5 })).find(r => r.slug === 'people/alice-example');+ expect(before?.title_mention_boost).toBeUndefined();+ await engine.setConfig('search.title_qualified', 'true');+ const after = (await hybridSearch(engine, q, { limit: 5 })).find(r => r.slug === 'people/alice-example');+ expect(after?.title_mention_boost).toBe(1.25);+ expect(after?.title_match_boost).toBeUndefined();+ expect(after?.evidence).not.toBe('exact_title_match');+ expect(after?.create_safety).not.toBe('exists');+ } finally { await off(); }+ });+});