Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.15.0 feat(retrieval): lowercase+surname identity recall, ranking fixes, BrainBench production seam (#1663 wave) (#4228)
Garry Tanafe923693ac1
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5813986243..b54af138e2 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.14.0",+ "version": "0.46.15.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/mcp.json b/.codex-plugin/mcp.jsonindex 11633f6167..13a38a285d 100644--- a/.codex-plugin/mcp.json+++ b/.codex-plugin/mcp.json@@ -38,6 +38,7 @@"GBRAIN_PAGE_WARN_BYTES","GBRAIN_REMOTE_CLIENT_SECRET","GBRAIN_RETRIEVAL_REFLEX",+ "GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS","GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS","GBRAIN_SOURCE","GBRAIN_SURFACE",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex c7cddf6b34..d2a220b697 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.14.0",+ "version": "0.46.15.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex f3f1e4e22c..c5b3592bda 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.14.0 -->+<!-- gbrain-runbook-stamp: 0.46.15.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0c6beddb30..a6ba364d73 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,82 @@All notable changes to GBrain will be documented in this file.+## [0.46.15.0] - 2026-08-16++**The brain now recognizes people the way you actually mention them.**+Lowercase first-name mentions ("remind me what alice said") and+surname-only references ("Did Galewright follow up?") now resolve to the+right page and surface a pointer before your agent answers. On the+BrainBench identity suite this took the know-to-ask failure rate from+0.15 to 0.00 across all three harnesses, with push precision held at+1.0 and zero false fires — and the claude-code benchmark row now+exercises the real shipped hook instead of a test contract, so those+numbers measure production behavior.++### Added+- **Lowercase + surname recall arms in the retrieval reflex.** A+ lowercase mention resolves through your documented aliases when the+ match is unique across every source in play; a surname-only reference+ resolves when exactly one person page carries that surname. Ambiguity+ in either arm injects nothing — silence beats a wrong pointer. Kill+ switch: `retrieval_reflex_lexical_arms: false` in config or+ `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS=false` (default on).+- **Aliases now count everywhere identity resolves.** Entity-slug+ resolution (fact writes, recall, trajectory seeds) matches documented+ aliases exactly before falling back to fuzzy matching, and wikilink+ inference recognizes alias mentions in page bodies — both verified+ against live pages so a stale alias can never point at a deleted page.+- **Concept-shaped queries get concept-shaped ranking.** Definitional+ paraphrases ("what is the ownership economy?") are classified as a new+ `concept` intent and ranked vector-lean, so keyword-decoy pages stop+ outranking the page that actually explains the idea. Entity lookups+ keep their existing ranking — a proper noun in the query routes as+ before.+- **`--explain` now prints each result's real cosine similarity** next+ to its blended score.++### Fixed+- **Evidence labels are grounded in real vector similarity.** A result+ is labeled `high_vector_match` only when its actual cosine similarity+ clears the floor (config: `search.evidence_cosine_floor`, default+ 0.80) — previously a keyword-heavy blended score could earn the label+ with no semantic support. Keyless runs degrade to honest+ keyword-based labels.+- **A single dense page can no longer starve vector search.** When one+ page's chunks fill the candidate pool, the engines escalate the pool+ (bounded by the vector index's hard ceiling) until the page count is+ honest; genuine exhaustion is reported in search metadata instead of+ silently returning a short page.+- **Near-duplicate filtering no longer deletes other pages' results.**+ The text-similarity dedup now only collapses chunks within the same+ page, so two legitimately similar pages both survive.+- **Weak-confidence result lists no longer collapse to one result.**+ Autocut skips score-cliff trimming entirely when the top score is+ below a floor (config: `search.autocut_min_top`, default 0.35) —+ low-confidence lists return the full cluster for you to judge.++### Changed+- **BrainBench's claude-code row measures the shipped hook.** The+ adapter drives the production `user-prompt` hook end-to-end (real+ transcript parsing, real IPC resolve path, real injection budget)+ instead of a harness-shaped contract, and the suite's pre-registered+ quality floors are now an executable test — a baseline update can no+ longer bank a threshold violation.+- The query cache key version advanced (new ranking knobs participate),+ so the first re-run of a cached query after upgrade is a one-time+ cache miss and repopulates automatically.++To take advantage of v0.46.15.0:+- `gbrain upgrade` (or rebuild the binary). No migration required; the+ new recall arms and ranking are on by default.+- Expect a one-time query-cache miss spike on first queries after+ upgrade (cache key version bump); the cache rewarms itself.+- If you need to compare against pre-wave identity behavior, set+ `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS=false` — no redeploy needed.+- Add aliases to your people pages (`gbrain alias`) to widen what the+ lowercase arm can catch; it only fires on documented, globally unique+ aliases.+## [0.46.14.0] - 2026-08-16Fix wave: 13 verified issues fixed + 14 community PRs adopted with credit, from adiff --git a/TODOS.md b/TODOS.mdindex 09a96cd20d..7edbf4c54f 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,107 @@# TODOS+## v0.46.15.0 identity/retrieval wave follow-ups (filed at ship; decisions recorded at CEO review + outside voice)++- [ ] **P2 — Codex adapter full production flip.** v0.46.15 integrated the REAL rollout+ parser (`src/core/transcripts/codex.ts`) for turn selection, but fragment DELIVERY+ remains a harness-shaped contract (no shipped codex injection path exists yet). When+ one lands, flip the seam like the claude-code row (run-scoped infra via+ setupRun/teardownRun; bank the baseline in the same commit). Context: outside-voice F5.+- [ ] **P2 — Per-model calibration for `search.evidence_cosine_floor` (0.80) and+ `search.autocut_min_top` (0.35).** Both are provider-scale-dependent; both are+ config-overridable today. The September reranker default flip (zerank-2 →+ voyage:rerank-2.5) MUST re-tune autocut_min_top — add that line to the v0.47+ removal checklist when executing it. Context: outside-voice F16. Ship-review+ addendum (F6): the floor is not purely a label — `create_safety` consumes the+ evidence tier and gates duplicate-page creation, so a floor that never fires on+ a low-cosine-scale embedder degrades `exists`→`probable` and loosens the+ don't-create-a-duplicate contract. Calibrate BEFORE the September embedder+ default flip, and include a per-model floor table, not one global number.+- [ ] **P2 — Cat 3 undocumented-alias enrichment.** The gbrain-evals Cat 3 runner's+ undocumented class (initials, nicknames, typos) needs alias-TABLE growth+ (enrichment writes page_aliases), not resolver changes — the v0.46.15 alias_exact+ arm only helps documented aliases. Pair with the evals-repo runner repair+ (seed page_aliases + route through resolveEntitySlug). Context: outside-voice F1.+- [ ] **P3 — Lowercase bigram alias candidates.** v2 of the weak-candidate pass+ (`entity-salience.ts`): "sable finch" as a two-token weak alias probe. Unigram+ covers the alias-table convention today; bigram needs its own ambiguity study.+- [ ] **P3 — Precomputed name-token index at ingest.** The surname arm's+ `lower(title) LIKE '% <token>'` scan is bounded by the reflex fail-open budgets;+ if reflex latency telemetry creeps on 10K+-page brains, build the token table+ and swap the arm to an indexed lookup.+- [ ] **P3 — Re-eval community #717 (graph-hop wikilink rerank, claimed +2.6/+2.8+ P@5/R@5) against the post-v0.46.15 ranker** — the concept intent + dedup scope fix+ may have absorbed part of its headroom.+- [ ] **P2 — #1663 remainder (issue REOPENED at ship): query-shape routing,+ structural exact-lookup tier, CRAG confidence escalation.** The issue was closed+ with these three unbuilt; the wave shipped the adjacent pieces (concept intent,+ autocut weak-top floor, evidence-on-cosine) but deliberately deferred these.+- [ ] **P3 — Positive underfill-event coverage for searchVector escalation.** The+ two NEGATIVE paths are pinned (no event on genuine short corpus / offset past+ end); the positive fire-at-cap assertion needs a >1000-chunk fixture that pushes+ `innerLimit` to `HNSW_EF_SEARCH_MAX` with the pre-DISTINCT pull full. Pair with+ a >400-chunk second-escalation engine-parity case (both current fixtures stop at+ one escalation). Also cover the exact-scan lane (ship-review): a >2000-dim+ vector column (no HNSW) must keep deep offsets working — the cap now keys on+ `hnswIndexExpected`, pinned only by inspection. From the ship coverage audit+ (C5/T7 partials).+- [ ] **P2 — Reflex IPC version skew: weak candidates against an old `gbrain serve`.**+ An upgraded hook client emits `weak: true` candidates; a not-yet-restarted older+ serve ignores the unknown field and runs lowercase words through ALL arms+ (title/slug-suffix), fabricating pointers during the upgrade window (ship-review+ F4). Options: protocol version tag on ResolveRequest with client-side weak-strip+ when the server doesn't ack; or an upgrade-flow serve restart requirement made+ explicit. Exposure ends at serve restart; kill switch (`GBRAIN_RETRIEVAL_REFLEX_+ LEXICAL_ARMS=false` on the client) also closes it since the client then sends no+ weak candidates.+- [ ] **P3 — Shared wall-clock budget across searchVector escalation attempts.**+ Each escalation retry gets a FRESH 8s statement_timeout on Postgres (worst ~32s+ per vector arm; multiplied under tokenmax multi-query expansion). Share one+ deadline across the loop's attempts (ship-review F8). The loop only fires on+ dense-wall shapes, and per-op timeouts bound the blast radius — hence P3.+- [ ] **P1 — Cat 13 conceptual recall: the concept tilt is NOT enough; the fusion+ itself is the suspect.** Pre-merge receipt (v0.46.15, voyage-4/1024 space, 500+ seeded probes, all adapters on the SAME gateway): bare vector 49.5 nDCG@5,+ grep-only 46.2, vector+grep RRF fusion 40.5, gbrain hybrid 35.6 — and a master+ A/B at the merge-base scored gbrain BYTE-IDENTICAL (35.6, every template), so the+ wave neither regressed nor improved Cat 13. Two honest findings: (a) the+ pre-registered "hybrid ≥ bare vector" target is NOT met — the ±10-20% RRF-k+ concept tilt provably works on a discriminating corpus+ (test/search/concept-weights.test.ts) but is a wash on this probe mix; (b)+ FUSION ITSELF loses to its own best single arm here (40.5 < 46.2 < 49.5) — the+ keyword arm's noise on paraphrase probes drags the merge below either component.+ Next: instrument per-arm rank contributions on the Cat 13 losers+ (synonym 38.7 vs vector 66.4 is the widest), then evaluate arm-confidence-+ weighted fusion (down-weight keyword when its top score is weak) rather than a+ bigger static tilt. Ship with the evals-repo PR (the three uncommitted gateway-+ config patches in gbrain-evals are part of it). Also note: the recorded 47.0-vs-+ 49.1 OpenAI-space numbers cannot be reproduced keylessly; the voyage-space gap+ is WIDER — stronger embedders make hybrid's keyword noise relatively costlier.++## LongMemEval temporal gap — date-proximity signal SPIKE-REJECTED (filed v0.46.15.0, identity/retrieval wave)++- **P2 — Reframe the temporal-reasoning gap (94.7% vs MemPal 96.2%, the only categorical+ public-benchmark loss) around what the questions actually are.** The v0.46.15 wave+ pre-registered a spike gate before building a date-proximity ranking term+ (`COALESCE(effective_date, updated_at)` proximity to query-text-extracted since/until+ bounds, per the outside-voice-amended plan). The spike FIRED the stop condition:+ a 12-question sample of the 133 `temporal-reasoning` questions in `longmemeval_s`+ contained ZERO extractable absolute bounds — they are duration-arithmetic+ ("How many days passed between X and Y?", "how many weeks ago did I …") and+ pairwise-ordering ("which happened first …") questions. A scalar date-proximity+ boost fires on none of them; retrieval for these is EVENT-DESCRIPTION recall+ (find the sessions naming the events), and the date math belongs to the answer+ layer — which is what the existing `findTrajectory` routing already does.+ Next honest hypotheses, in order: (a) measure per-question retrieval recall on the+ temporal slice to locate WHERE the 1.5pt is lost (retrieval vs trajectory coverage+ vs answer extraction); (b) if retrieval: event-phrase recall (the event descriptions+ are long noun phrases — expansion/paraphrase territory, adjacent to the v0.46.15+ concept lane); (c) if trajectory: widen `extractCandidateEntities` coverage on+ event-shaped (non-person) anchors. Do NOT rebuild the date-proximity boost without+ new evidence — this entry is the receipt for why it doesn't exist.+++## chennai fix-wave follow-ups (filed 2026-08-16)- [ ] **P1 — read_latency_under_sync hangs from 6a905a1e (#4143); 6a905a1e's@@ -1059,7 +1161,7 @@ Deferred from the BrainBench wave (eng-reviewed; plan + GSTACK REVIEW REPORT at- [ ] **`--live` agent-in-the-loop know-to-ask.** Replay fixtures with a real model deciding whether to issue retrieval calls; grade the agent, not just the deterministic reflex. Pre-registered in `docs/eval/BRAINBENCH.md` (the v1 metric grades the injection decision, which IS the shipped mechanism). Needs: seeded N-repeat methodology for model stochasticity + budget rails. Priority: P2.- [ ] **Intrusion-budget gating calibration.** `avg_injected_tokens` is reported, non-gating (decision 18) — a wrong threshold is worse than none. After a few weeks of scoreboard data across PRs, pick calibrated per-seam thresholds and promote it to a gated metric. Priority: P2.-- [ ] **Flip contract adapters to production — claude-code half now unblocked.** `adapters/claude-code.ts` exports the UserPromptSubmit hook wire types; the real hook (`gbrain hook user-prompt`, shipped with the bootstrap lane and extended with cross-turn dedupe + the channel feedback loop in the cathedral-3 convergence) swaps the in-process transport for an exec of the hook script and flips `seam: 'contract'` → `'production'` with continuous bench numbers. Note the production hook also exercises transcript-based dedupe, which the memoryless contract row deliberately doesn't. For the codex half: the cathedral-4 transcripts lane shipped a verified codex rollout PARSER (`src/core/transcripts/codex.ts`, structural turn selection pinned against a live sample) — a codex contract adapter can now consume it instead of waiting for a hook integration. Priority: P1 (the claude-code integration has landed; codex parsing has landed; this is now standalone-actionable).+- [x] **Flip contract adapters to production — claude-code half DONE (v0.46.15 identity/retrieval wave).** `adapters/claude-code.ts` now drives the real `gbrain hook user-prompt` path (synthesized Claude Code JSONL transcripts, run-scoped resolve-IPC server with `turn_context` handler, `HookIo` seams) and the scoreboard row is `seam: 'production'`, banked with justification in the same commit. The codex half (real DELIVERY path, not just the parser) is re-filed as the P2 "Codex adapter full production flip" entry in the v0.46.15.0 wave section at the top of this file.- [ ] **Cathedral 1 conformance-kit fixture import.** The memory-verbs conformance scenarios convert to BrainBench fixtures via the published `evals/brainbench/schema/fixture.schema.json` once `garrytan/cathedral-1` merges ("conformance tests double as BrainBench seed fixtures", decision log 2026-06-12). Free corpus growth from already-reviewed scenarios. Blocked by: cathedral-1 on master. Priority: P2.- [ ] **Live-embeddings fidelity mode (`--embeddings`).** Hermetic CI grades the keyword/alias arms only (disclosed); an opt-in mode seeding real embeddings would grade write-back/continuity retrieval through the vector path. Same budget rails as `--llm`. Priority: P3.- [ ] **Community fixture intake + competitor adapters.** The TD1 remainder after the generated corpus absorbed in-PR growth: an `external-authors/`-style intake path for contributed fixtures (validator + privacy guard already gate them) and adapters for non-gbrain memory systems against the published schemas, enabling true head-to-head rows in the gbrain-evals scorecard. Priority: P3.@@ -1696,10 +1798,15 @@ is deterministic + precision-biased. See plan + GSTACK REVIEW REPORT atwave: `extractCandidatesFromWindow` now covers assistant-introduced entities andpronoun follow-ups whose antecedent was NAMED in the rolling window; true pronouncoreference for never-named antecedents remains with the LLM-pass idea.)*-- [ ] **P3 — recall knob: optional fuzzy/prefix-expansion resolution.** The resolver- (`src/core/context/retrieval-reflex.ts`) is exact-only (alias + title + slug-suffix)- for precision. Revisit adding `resolveEntitySlug`'s trgm-fuzzy / prefix-expansion- arm, gated on an unambiguous single hit, if recall telemetry comes back weak.+- [x] **P3 — recall knob: optional fuzzy/prefix-expansion resolution.** RESOLVED+ differently by the v0.46.15 identity wave, with a receipt: trigram fuzzy in the+ reflex is deliberately REJECTED — the BrainBench adversarial near-miss class+ (`"<Name>er"` for a real `<Name>` page) is gold-silent and any usable trigram+ threshold would false-fire on it. The recall gap the fuzzy arm targeted was+ closed by exact NORMALIZED-LEXICAL arms instead: the lowercase weak-alias arm+ + the surname arm (know_to_ask 0.15→0, push_recall +9.6pp, false_fire/precision+ unmoved). Do not re-add trigram here without a fixture that defeats the+ near-miss class first.## gbrain#1972 job-layer follow-up (v0.43+)@@ -3329,14 +3436,12 @@ The original 3 items as filed (kept for traceability):`eval_capture_failures.reason` enum cleanup from the v0.25.0 P1 surgicalhardenings list. Effort: human ~3 days / CC ~3 hours.-- [ ] **P0 — Wire nightly quality probe into autopilot scheduler.** The- phase ships callable (`src/core/cycle/nightly-quality-probe.ts`) with- full DI surface; doctor surfaces outcomes; the audit JSONL rotates- cleanly. What's NOT wired: `src/commands/autopilot.ts` doesn't invoke- `runNightlyQualityProbe(deps)` on its 24h cadence. Add the phase- trigger; honor `autopilot.nightly_quality_probe.enabled` config gate.- Already filed in v0.40.1.0 Track D follow-ups — re-filing here as P0- with explicit D1-wave dependency. Effort: human ~3 hours / CC ~30 min.+- [x] **P0 — Wire nightly quality probe into autopilot scheduler.** DONE —+ and this entry was STALE when the v0.46.15 wave audited it: autopilot's+ tick body already invokes `runNightlyQualityProbe` behind the+ `autopilot.nightly_quality_probe.enabled` gate+ (`src/commands/autopilot.ts:1361-1386`, pinned by+ `test/autopilot-nightly-probe-wiring.test.ts`). Nothing to build.### D2 — Code-indexing promoted to P1 (peer of Cursor/Sourcegraph)@@ -3767,19 +3872,12 @@ contributor traps.vary too much). Estimate: ~2 weeks. Filed during v0.40.1.0 Track D/plan-eng-review (see `~/.claude/plans/system-instruction-you-are-working-whimsical-acorn.md`).-- [ ] **v0.41+: Wire the nightly quality probe into autopilot scheduling.**- v0.40.1.0 Track D shipped the phase (`src/core/cycle/nightly-quality-probe.ts`),- the audit JSONL (`src/core/audit-quality-probe.ts`), the doctor check- (`nightly_quality_probe_health` in doctor.ts), and the 10-question- placeholder fixture. What's NOT yet wired: `src/commands/autopilot.ts`- doesn't yet invoke `runNightlyQualityProbe(deps)` on its 24h cadence —- the phase is callable in isolation (good for testing) but no scheduled- loop calls it. To finish: add a phase trigger to the autopilot cycle loop- that calls the probe with concrete deps wiring (`isEnabled`,- `hasEmbeddingProvider`, `resolveMaxUsd`, `resolveRepoRoot`, real- `runLongMemEval` / `runCrossModalBatch` invocations via subprocess or- direct function call). Honor `autopilot.nightly_quality_probe.enabled`- config gate (already in doctor's read-side; needs autopilot read-side).+- [x] **v0.41+: Wire the nightly quality probe into autopilot scheduling.**+ DONE (stale entry swept by the v0.46.15 wave): autopilot's tick body+ invokes `runNightlyQualityProbe` behind the+ `autopilot.nightly_quality_probe.enabled` gate+ (`src/commands/autopilot.ts:1361-1386`, pinned by+ `test/autopilot-nightly-probe-wiring.test.ts`).Doctor surface is already in place to show outcomes; just need thescheduling lane. Estimate: ~3 hours.diff --git a/VERSION b/VERSIONindex 981510d985..4b663314c1 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.14.0\ No newline at end of file+0.46.15.0\ No newline at end of filediff --git a/docs/TESTING.md b/docs/TESTING.mdindex 29c67b9952..232ce80bc9 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -462,9 +462,9 @@ Unit tests and what they cover:- `test/search.test.ts` — RRF normalization, compiled truth boost, cosine similarity, dedup key.- `test/sql-ranking.test.ts` — source-boost helpers: longest-prefix-match in SQL CASE, `detail=high` temporal-bypass, three-meta-char LIKE escape (`%`, `_`, `\`), single-quote SQL-literal doubling, env override parsing for `GBRAIN_SOURCE_BOOST` + `GBRAIN_SEARCH_EXCLUDE`, `resolveBoostMap` / `resolveHardExcludes` merge semantics.- `test/dedup.test.ts` — source-aware dedup, compiled truth guarantee, layer interactions.-- `test/intent.test.ts` — query intent classification: entity/temporal/event/general.+- `test/query-intent-legacy.test.ts` — query intent classification: entity/temporal/event/general (pre-concept behavior pins). `test/query-intent-concept.test.ts` — the `concept` intent: definitional/landscape cue detection, the proper-noun / quoted-phrase / sub-3-word guards, vector-lean weight routing.- `test/eval.test.ts` — retrieval metrics: `precisionAtK`, `recallAtK`, `mrr`, `ndcgAtK`, `parseQrels`.-- `test/brainbench-fixtures.test.ts` / `test/brainbench-generator.test.ts` / `test/brainbench-metrics.test.ts` / `test/brainbench-continuity.test.ts` / `test/brainbench-writeback.test.ts` / `test/brainbench-adapters.test.ts` / `test/brainbench-scoreboard.test.ts` — the BrainBench memory-conformance unit suites (`src/eval/brainbench/`): fixture loader/validator + the sealed-gold seal (a `gold` key inside a fixture must reject) and committed-corpus integrity; generator determinism (the committed corpus is exactly what `gen.ts` produces, holdout discipline, category counts); metric formulas over hand-built turn rows (zero should-retrieve turns, empty injections, acceptable-vs-gold asymmetry, micro-averaging); cross-harness continuity (writer's decision persists through the production write-back pipeline, reader recalls on the SAME brain); write-back grading the PRODUCTION conversation→facts pipeline via the injected gold extractor; adapter seam contracts over hermetic PGLite (budget caps, suppression modes); scoreboard + gate governance (baseline determinism, count-aware gating, corpus-bless modes, justification flow, isolation gates-at-zero).+- `test/brainbench-fixtures.test.ts` / `test/brainbench-generator.test.ts` / `test/brainbench-metrics.test.ts` / `test/brainbench-continuity.test.ts` / `test/brainbench-writeback.test.ts` / `test/brainbench-adapters.test.ts` / `test/brainbench-scoreboard.test.ts` — the BrainBench memory-conformance unit suites (`src/eval/brainbench/`): fixture loader/validator + the sealed-gold seal (a `gold` key inside a fixture must reject) and committed-corpus integrity; generator determinism (the committed corpus is exactly what `gen.ts` produces, holdout discipline, category counts); metric formulas over hand-built turn rows (zero should-retrieve turns, empty injections, acceptable-vs-gold asymmetry, micro-averaging); cross-harness continuity (writer's decision persists through the production write-back pipeline, reader recalls on the SAME brain); write-back grading the PRODUCTION conversation→facts pipeline via the injected gold extractor; adapter seam contracts over hermetic PGLite (budget caps, suppression modes); scoreboard + gate governance (baseline determinism, count-aware gating, corpus-bless modes, justification flow, isolation gates-at-zero). `test/brainbench-floors.test.ts` — the pre-registered quality floors as executable assertions against the committed baseline (a baseline bless can't bank a threshold violation).- `test/eval-brainbench-e2e.test.ts` — BrainBench CLI end-to-end via subprocess against a small tmp corpus: the literal exit codes (0 pass / 1 regression / 2 error-or-inconclusive — the CI product), `--out` artifact validity incl. `_meta.metric_glossary`, byte-deterministic `--update-baseline`, anti-vacuous-pass, and the `eval run-all` in-process wiring.- `test/check-resolvable.test.ts` — resolver reachability, MECE overlap, gap detection, proximity-based DRY detection, `extractDelegationTargets` coverage.- `test/dry-fix.test.ts` — auto-fix: three shape-aware expander pure-function tests; five guards (working-tree-dirty, no-git-backup, inside-code-fence, already-delegated within 40 lines, ambiguous-multi-match, block-is-callout).diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 2d1911670d..df785bbe9a 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -17,10 +17,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification.- `src/core/background-work.ts` (#1762/#1745/#1775) — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the CLI disconnects." `registerBackgroundWorkDrainer({name, order, drain(timeoutMs), abort?})` + `drainAllBackgroundWorkForCliExit({timeoutMs})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle). Drains in explicit `(order, name)` order — facts FIRST (order 0) so its abort-path DB `logIngest` runs against the freshest live engine — and AWAITS `abort()` only when `drain()` reports `unfinished>0`. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. FIVE sinks register at module import: `facts/queue.ts` (order 0; `abort`=`shutdown()` cancels a hung facts:absorb Haiku via internalAbort), `last-retrieved.ts` (order 1), `search/hybrid.ts` (order 2; `awaitPendingSearchCacheWrites` bounded via `Promise.race`), `eval-capture.ts` (order 3; `captureEvalCandidate` self-tracks its promise via `awaitPendingEvalCaptures`), `context/volunteer-events.ts` (order 4, #2095 — batched volunteer-event INSERTs, drained like the rest). Every cli.ts teardown site reaches it through `finishCliTeardown` (`src/core/cli-force-exit.ts`), which drains the registry before `engine.disconnect()` — closing the PGLite busy-loop where `db.close()` raced an in-flight job and pinned the single-writer lock (#1762). Exports `backgroundWorkSinkCount()` so the teardown helper computes its backstop deadline from the registered sink count. CLI-EXIT-ONLY: the facts `shutdown()` abort is permanent process state, never call in a long-lived `gbrain serve`. Companion changes: `src/core/ai/gateway.ts` `withDefaultTimeout(caller, ms)` bounds every outbound AI call (chat 300s, embed+multimodal 60s; env `GBRAIN_AI_{CHAT,EMBED,MULTIMODAL}_TIMEOUT_MS`; composed with caller signals via `AbortSignal.any`) and the teardown backstop honors an errored op's exit code so a hung disconnect can't mask failure as success (see `cli-force-exit.ts`); `src/core/postgres-engine.ts` `reconnect()` module-mode branch re-establishes via idempotent `db.connect()` + `connectionManager.setReadPool` refresh instead of `db.disconnect()` (no null window for concurrent ops; fail-loud on real connect failure — #1745); `src/core/search/hybrid.ts` `embedQueryBounded` + a shared `QueryEmbedDeadline` (6s, floored 2s per embed via `MIN_QUERY_EMBED_BUDGET_MS`; env `GBRAIN_QUERY_EMBED_TIMEOUT_MS`) bounds the cache-lookup AND inner query embeds so a stalled provider falls back to keyword instead of stalling the whole op (#1775). Incorporates + hardens PR #1763 (@ElliotDrel). Pinned by `test/core/background-work.test.ts`, `test/search/query-embed-deadline.test.ts`, `test/eval-capture-drain.test.ts`, `test/e2e/postgres-reconnect-singleton.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts`, `test/fix-wave-structural.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 regression).-- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. Pinned by `test/search/explain-formatter.test.ts`.-- `src/core/search/mode.ts` — Named search-mode bundles + the search cache key. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds every result-shaping knob into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. Mid-deploy `query_cache` rows from before the upgrade hash differently — natural row segregation, clears within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `SEARCH_MODE_CONFIG_KEYS` carries the corresponding config keys, and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller.+- `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. Pinned by `test/search/explain-formatter.test.ts`.+- `src/core/search/mode.ts` — Named search-mode bundles + the search cache key. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds every result-shaping knob into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. Mid-deploy `query_cache` rows from before the upgrade hash differently — natural row segregation, clears within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `SEARCH_MODE_CONFIG_KEYS` carries the corresponding config keys, and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs `autocut_min_top` (default 0.35 in all three bundles; config `search.autocut_min_top`; folds into `knobsHash` as an `acm=` part) and `evidence_cosine_floor` (default 0.8 in all three bundles; config `search.evidence_cosine_floor`; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain.- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.2.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction.-- `src/core/context/` — Retrieval Reflex (Layer 1, issue #1981). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped) + `extractCandidatesFromWindow(turns)` (#2095: merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (the recall fix: real slugs are namespaced `people/x` but `slugify` drops the prefix); pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (#2095 — `ARM_CONFIDENCE` alias 0.9 / title 0.8 / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' legacy default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = exact legacy behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into `src/mcp/server.ts` (serve binds `<dataDir>/.gbrain-resolve.sock` on PGLite, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`). `volunteer.ts` (#2095): `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts` (#2095): `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`.+- `src/core/context/` — Retrieval Reflex (Layer 1, issue #1981). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (#2095: merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (the recall fix: real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (#2095 — `ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' legacy default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = exact legacy behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into `src/mcp/server.ts` (serve binds `<dataDir>/.gbrain-resolve.sock` on PGLite, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts` (#2095): `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts` (#2095): `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`.- `src/commands/watch.ts` — `gbrain watch` (#2095): the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.- `src/commands/integrations.ts` — recipe install. The resolver-row install fence is keyed by `manifest.recipe` (`gbrain:<recipe>:resolver-rows`), so a second `copy-into-host-repo` recipe no longer writes a block mislabeled with the first recipe's name. Pinned by `test/integrations-install.test.ts`. Health-check DSL includes the staleness-aware `heartbeat_max_age` type (#2787): declares the sense's expected cadence (`max_age: 48h`), and `integrations doctor` FAILS when the newest heartbeat event is older — the only check type that catches a green-but-dead sense (all others are point-in-time). Not embedded-gated (reads only the local heartbeat file). Recipe frontmatter carries `output_paths` (repo-relative dirs the collector writes, e.g. calendar-to-brain → `daily/calendar/`); `getConfiguredCollectorOutputs()` surfaces them for the #2788 db_only-collision check/warning. Pinned by `test/integrations-heartbeat-max-age.test.ts`. Standalone integration recipe management (no DB needed). Exports `getRecipeDirs()` (trust-tagged recipe sources), SSRF helpers (`isInternalUrl`, `parseOctet`, `hostnameToOctets`, `isPrivateIpv4`). Only package-bundled recipes are `embedded=true`; `$GBRAIN_RECIPES_DIR` and cwd `./recipes/` are untrusted and cannot run `command`/`http`/string health checks.- `src/core/audit/audit-writer.ts` — shared JSONL audit primitive consolidating the hand-rolled audit modules. Exports `createAuditWriter({kind, recordSchema})` returning `{log, readRecent}` plus shared helpers `computeIsoWeekFilename(kind, now?)` and `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). ISO-week file rotation; best-effort writes (stderr warn on failure, never throws); read-path scans current-week + previous-week files for boundary spans. Refactored onto it for parity: `src/core/rerank-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/minions/handlers/shell-audit.ts`, `src/core/minions/handlers/supervisor-audit.ts`, `src/core/facts/phantom-audit.ts` (each module's public API preserved bit-for-bit). The `graph-signals-failures` audit (`logGraphSignalsFailure`) uses the same primitive. One hand-rolled audit remains at `src/core/skillpack/audit.ts`. Pinned by `test/audit/audit-writer.test.ts`.@@ -41,7 +41,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Lossless invariant: non-overlapping portions reassemble to the original. Also strips the facts fence via `stripFactsFence({keepVisibility:['world']})` so private fact visibility tiers never reach embeddings.- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries.- `src/core/chunkers/llm.ts` — LLM-guided chunking: pre-splits into 128-word candidates via the recursive chunker, then asks a Haiku-class model "where does the FIRST topic shift occur?" per window.-- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to kept results, (3) no page type exceeds 60% of results, (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.+- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results, (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.- `src/core/audit-slug-fallback.ts` — Weekly ISO-week-rotated audit JSONL at `~/.gbrain/audit/slug-fallback-YYYY-Www.jsonl`. `logSlugFallback(slug, sourcePath)` fires when `importFromFile` falls back to a frontmatter slug because `slugifyPath` returned empty (emoji / Thai / Arabic / non-CJK exotic-script filenames). `readRecentSlugFallbacks(days)` reads the last N days for `gbrain doctor`'s `slug_fallback_audit` check. Honors `GBRAIN_AUDIT_DIR` via the shared `resolveAuditDir()`. Separate surface from `sync-failures.jsonl` — that file carries bookmark-gating semantics that info events shouldn't trigger.- `src/core/embedding-pricing.ts` — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`; EMBEDDINGS only — chat/completion pricing lives in `model-pricing.ts` (different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); ZeroEntropy zembed-1 ($0.05/1M), zerank-2 ($0.025/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M). `voyage-4-nano` is deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0. `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.- `src/core/post-upgrade-reembed.ts` — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est, graceSeconds)` is the stderr-line formatter. `runPostUpgradeReembedPrompt(engine, model, opts)` orchestrates the 10-second Ctrl-C window; TTY-only wait (non-TTY auto-proceeds for CI / cron); `GBRAIN_NO_REEMBED=1` bails with a doctor-warning marker; `GBRAIN_REEMBED_GRACE_SECONDS=0` skips the wait.@@ -77,7 +77,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/code-def.ts` + `src/commands/code-refs.ts` — symbol definition + references lookup. Query `content_chunks.symbol_name` or chunk_text ILIKE with `page_kind='code'` filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard `searchKeyword` `DISTINCT ON (slug)` collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + the `code_def`/`code_refs` MCP ops) carries `status` + `ready` from `src/core/code-graph-readiness.ts` so a `count:0` result is distinguishable as `not_built` (no code indexed) vs `ready` (genuinely no match); human output prints a one-line hint when not ready.- `src/core/code-graph-readiness.ts` — typed readiness signal shared by the four code-* surfaces (`code-def`/`code-refs`/`code-callers`/`code-callees`). `resolveCodeReadiness(engine, {kind:'symbol'|'edge', count, sourceId?, allSources?})` returns `{status:'not_built'|'indexing'|'ready'|'unknown', ready, has_code, pending_edges}`. `count>0` short-circuits to `ready` with no query; on empty it runs `EXISTS` probes against `content_chunks` JOIN `pages` (`page_kind='code'`) — no `page_kind` index needed, and the pending probe rides the partial `idx_content_chunks_edges_backfill`. `kind:'symbol'` (code-def/refs) is 2-state + brain-wide because symbol metadata is set at chunk time; `kind:'edge'` (code-callers/callees) is 3-state + source-scoped, with the pending predicate mirroring the resolver (`edges_backfilled_at IS NULL OR < EDGE_EXTRACTOR_VERSION_TS` from `src/core/chunkers/symbol-resolver.ts`) so a resolver-version bump never falsely reports `ready`. Probe scope matches each command's result-query `deleted_at` posture (def/refs don't filter `deleted_at`, so neither do the probes). Any DB error returns `status:'unknown'` (fail-open; never breaks the command). `readinessHint(r)` renders the human one-liner. Wired into `code-def.ts`/`code-refs.ts` (brain-wide), `code-callers.ts`/`code-callees.ts` (resolved `sourceId`/`allSources`), and all four `code_*` MCP op handlers in `src/core/operations.ts`. Pinned by `test/code-graph-readiness.test.ts` + readiness-envelope cases in `test/e2e/code-intel-mcp-ops-pglite.test.ts`.- `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/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/general → auto-selects detail level, salience/recency/modality axes), `isAmbiguousModalityQuery` (LLM-escalation gate), and the #2416 concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.+- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the #2416 concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.- `src/core/search/llm-intent.ts` — opt-in LLM modality tie-break. `classifyModalityWithLLM(query, fallback)` routes through `gateway.chat()` with a fixed single-word-output system prompt; 1s timeout via AbortController. `parseModality(raw, fallback)` is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by `isAmbiguousModalityQuery` in `query-intent.ts` so the LLM call fires on only a small fraction of queries when on.- `src/core/search/image-loader.ts` — `loadImageInput(input, opts)` accepts a local path, `data:` URI, or `http(s)://` URL. Magic-byte sniff for PNG/JPEG/WebP. Hard size cap (default 10 MB, configurable via `search.image_query.max_bytes`). URLs route through `fetchWithSSRFGuard` so DNS rebinding + redirect chains are defeated; pre-flight Content-Length check + post-fetch size guard for lying servers. `ImageLoadError` with discriminated `code` (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).- `src/core/search/by-image.ts` — `searchByImage(engine, input, opts)`. Always runs the image branch (`embedQueryMultimodalImage` + `searchVector(embedding_image)`). Hybrid intersect: when the caller provides an optional `query`, runs a parallel text branch via `embedQueryMultimodal(query)` and merges via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the resolved mode's refinement weights. Widens to the unified column when `search.unified_multimodal=true` (transparently upgrades retrieval quality post-reindex).@@ -90,12 +90,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `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 let a page lose to a neighbor on ONE weak chunk while its strong chunk sat 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.- `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. Exports `tokenizeTitle` + `__test__` internals.- `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/evidence.ts` — the agent-facing why-it-matched contract (closes the root behavior where an agent read one blended score, decided "no strong match, safe to create", and wrote a duplicate over a fully-developed page). `classifyEvidence(r)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (base ≥ `HIGH_MATCH_FLOOR=0.85`) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent.+- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (closes the root behavior where an agent read one blended score, decided "no strong match, safe to create", and wrote a duplicate over a fully-developed page). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor` — never the blended score, so a keyword+boost pile-up can't earn the label; keyless/hermetic runs have no cosine and degrade to keyword-based labels; legacy `HIGH_MATCH_FLOOR=0.85` stays exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent.- `src/commands/search-diagnose.ts` — `gbrain search diagnose "<query>" --target <slug> [--json] [--source <id>]`: Phase-0 retrieval diagnostic. Traces WHERE a target page surfaces (or fails to) across keyword / vector (per-page max-pool) / alias / hybrid layers and names the layer responsible for an incident, so an operator can pin whether the fix is max-pool/innerLimit (vector) vs title/alias. The verdict names the layer that DOES surface the target (or "none"). Pinned by `test/search/search-diagnose.test.ts`.- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.- `src/eval/retrieval-quality/harness.ts` + `src/commands/eval-retrieval-quality.ts` + `test/fixtures/retrieval-quality/namedthing.jsonl` — NamedThingBench, the retrieval-quality eval that makes the named-thing-miss incident impossible to reintroduce silently. Seven query families, each a distinct failure class: `title-substring` (the direct regression), `generic-to-named` (tourist label → named thing), `alias-synonym` (declared alias / romanization → canonical), `multi-chunk-dilution` (one strong chunk among many weak — stresses max-pool), `short-vs-rich`, `graph-relationship` (guardrail), `hard-negative` (precision guard, must NOT return a page). `gbrain eval retrieval-quality <fixture.jsonl>` runs it with hard gates (e.g. title-substring Hit@1 ≥ 0.95, alias Hit@1 ≥ 0.98, multi-chunk-dilution Hit@3 = 1.0). Pure: caller injects a `SearchFn` (CLI uses `hybridSearch`, tests stub) so it's engine-agnostic. Metric glossary entries (`hit@1`/`hit@3`) added to `src/core/eval/metric-glossary.ts`. Pinned by `test/eval-retrieval-quality.test.ts` + `test/retrieval-quality-harness.test.ts`.- `docs/architecture/RETRIEVAL.md` + `docs/architecture/RETRIEVAL_MAXPOOL_INCIDENT.md` — retrieval-pipeline architecture reference + the named-thing-miss incident write-up (root cause, the five-layer fix, the eval that pins it).-- `src/eval/brainbench/` + `src/commands/eval-brainbench.ts` — BrainBench, the cross-harness memory conformance suite (`gbrain eval brainbench`; methodology in `docs/eval/BRAINBENCH.md`). `types.ts` carries the PUBLISHED interchange shapes (fixture/gold/result/baseline — mirrored as JSON Schemas in `evals/brainbench/schema/`; breaking changes bump the schema versions). `fixtures.ts`: strict loader/validator + corpus `fixtures_hash` (covers fixture AND gold files); a `gold` key inside a fixture turn is a validation error — gold is SEALED in the gold dir and adapters only ever see sanitized `PublicTurn`s. `seed.ts`: fail-fast hermetic seeding (`importFromContent` noEmbed + NULL-embedding `insertFact`; any non-`imported` status ⇒ `SeedError` ⇒ fixture `seed_failed` ⇒ run exit 2). `adapters/shared.ts`: ONE `runReflexPipeline` all three adapters drive with declarative config (pointer budget, suppression mode) — cross-harness comparability is structural; `openclaw.ts` (seam `production`, the shipped pipeline), `claude-code.ts` (seam `contract`; exports the UserPromptSubmit hook wire types a future integration implements; no conversation memory by contract), `codex.ts` (seam `contract`; static entity-index preamble whose slugs deliberately don't count as injections + ≤1 per-turn fragment). `metrics/`: know-to-ask (+false-fire anti-gaming companion), push (micro-averaged P/R), write-back (drives the PRODUCTION conversation→facts pipeline via the injectable-extractor seam; gold extractor in CI, real extractor under `--llm`), continuity (writer→reader pairs on a shared brain through DIFFERENT adapters; pointer-injection OR stored-fact keyword probe). `harness.ts`: ONE in-memory PGLite per run + `resetTables` between fixtures (longmemeval engine-sharing pattern); read-only suites share one seeding across all adapters; emits per-(harness×suite) cells + re-scoreable turn rows; `source_isolation_violations` counted per turn and gated at zero. `scoreboard.ts`: markdown render, canonical diff-stable committed baseline (4-decimal rounding, sorted keys, receipts excluded), `compareBaselines` with main-baseline governance — same-hash count-aware gate vs corpus-bless mode (the committed baseline must byte-match the run; regressions vs main require a `justification`). The CLI brings its own PGLite (cli.ts routes before connectEngine), writes `--out` as the canonical CI artifact, and terminates via an explicit grace-tick `process.exit(verdict)` (0 pass / 1 regression / 2 error) because PGLite stomps `process.exitCode` and Bun discards queued stdout on exit. `runBrainBenchCore()` is the in-process entry `eval run-all` uses (one record per sweep, `EvalRunRecord` schema_version 3, `mode: 'n/a'`). Pinned by `test/brainbench-*.test.ts` + `test/eval-brainbench-e2e.test.ts`.+- `src/eval/brainbench/` + `src/commands/eval-brainbench.ts` — BrainBench, the cross-harness memory conformance suite (`gbrain eval brainbench`; methodology in `docs/eval/BRAINBENCH.md`). `types.ts` carries the PUBLISHED interchange shapes (fixture/gold/result/baseline — mirrored as JSON Schemas in `evals/brainbench/schema/`; breaking changes bump the schema versions). `fixtures.ts`: strict loader/validator + corpus `fixtures_hash` (covers fixture AND gold files); a `gold` key inside a fixture turn is a validation error — gold is SEALED in the gold dir and adapters only ever see sanitized `PublicTurn`s. `seed.ts`: fail-fast hermetic seeding (`importFromContent` noEmbed + NULL-embedding `insertFact`; any non-`imported` status ⇒ `SeedError` ⇒ fixture `seed_failed` ⇒ run exit 2). `adapters/shared.ts`: ONE `runReflexPipeline` all three adapters drive with declarative config (pointer budget, suppression mode) — cross-harness comparability is structural; `openclaw.ts` (seam `production`, the shipped pipeline), `claude-code.ts` (seam `production`; drives the shipped `gbrain hook user-prompt` path end-to-end — fixture turns become `UserPromptSubmit` stdin JSON, synthesized Claude Code JSONL transcripts feed the real window parse + cross-turn dedupe, and resolution rides a run-scoped resolve-IPC server with the real shared secret; bench-pinned deviations disclosed in `docs/eval/BRAINBENCH.md`: generous `userPromptDeadlineMs`, push-failure banner suppressed), `codex.ts` (seam `contract`; static entity-index preamble whose slugs deliberately don't count as injections + ≤1 per-turn fragment; fixture conversations round-trip through the real rollout format + the shipped parser `src/core/transcripts/codex.ts` for turn selection — fragment DELIVERY remains harness-shaped until a shipped codex injection path lands). `metrics/`: know-to-ask (+false-fire anti-gaming companion), push (micro-averaged P/R), write-back (drives the PRODUCTION conversation→facts pipeline via the injectable-extractor seam; gold extractor in CI, real extractor under `--llm`), continuity (writer→reader pairs on a shared brain through DIFFERENT adapters; pointer-injection OR stored-fact keyword probe). `harness.ts`: ONE in-memory PGLite per run + `resetTables` between fixtures (longmemeval engine-sharing pattern); read-only suites share one seeding across all adapters; emits per-(harness×suite) cells + re-scoreable turn rows; `source_isolation_violations` counted per turn and gated at zero. `scoreboard.ts`: markdown render, canonical diff-stable committed baseline (4-decimal rounding, sorted keys, receipts excluded), `compareBaselines` with main-baseline governance — same-hash count-aware gate vs corpus-bless mode (the committed baseline must byte-match the run; regressions vs main require a `justification`). The CLI brings its own PGLite (cli.ts routes before connectEngine), writes `--out` as the canonical CI artifact, and terminates via an explicit grace-tick `process.exit(verdict)` (0 pass / 1 regression / 2 error) because PGLite stomps `process.exitCode` and Bun discards queued stdout on exit. `runBrainBenchCore()` is the in-process entry `eval run-all` uses (one record per sweep, `EvalRunRecord` schema_version 3, `mode: 'n/a'`). Pinned by `test/brainbench-*.test.ts` + `test/eval-brainbench-e2e.test.ts`.- `evals/brainbench/` — the committed BrainBench corpus: 141 fixtures (135 generated + 6 hand-authored spike) / 241 gold-annotated turns across 7 categories (kta-pos/kta-neg/push/write-back/continuity/multi-source/adversarial), ~15% holdout (excluded from the CI gate, scored in published `--include-holdout` runs). `generator/gen.ts` rebuilds the corpus byte-identically (Mulberry32, seed 42; whole-cloth fictional universe from curated synthetic name pools so scenario privacy is structural; prose is template-synthesized with PRNG-selected variants — deliberately no LLM pass, difficulty stays controlled; several know-to-ask variants intentionally exercise documented v1 reflex limits so the baseline measures the roadmap). `gold/` is sealed; `schema/` is the foreign-runner contract (gbrain-evals drives the suite as a subprocess via `--fixtures DIR --gold DIR --json --out FILE`); `baselines/main.json` is the committed gate baseline; `_ledger.json` records counts/seed/rebuild command. CI: the `.github/workflows/test.yml` `brainbench` job + `scripts/ci-brainbench-gate.sh` (fetches MAIN's baseline via `git show origin/master:…` — a PR cannot rewrite what it's compared against; first-landing path runs ungated) + `scripts/render-brainbench-delta.ts` (compact step-summary/PR-body delta block from the `--out` artifact). Privacy: `scripts/check-synthetic-corpus-privacy.sh` scans `evals/brainbench/{fixtures,gold}` in `bun run verify`.- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval cathedral. `SearchResult` gains `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` adds the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` extends the rollup with the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).@@ -122,7 +122,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `docs/eval-bench.md` — contributor guide for using captured data to benchmark retrieval changes before merging. Linked from CONTRIBUTING.md under "Running real-world eval benchmarks (touching retrieval code)".- `src/core/eval-capture.ts` — op-layer capture wrapper called from `src/core/operations.ts` `query` + `search` handlers (catches MCP + CLI + subagent tool-bridge from one site). Fire-and-forget; failures route to `engine.logEvalCaptureFailure` so `gbrain doctor` sees drops cross-process. Capture is off by default — `isEvalCaptureEnabled` resolution: explicit `config.eval.capture` (true/false) wins, else `process.env.GBRAIN_CONTRIBUTOR_MODE === '1'`, else off. Contributors set `export GBRAIN_CONTRIBUTOR_MODE=1`. PII scrubber gate is independent and defaults to true regardless of CONTRIBUTOR_MODE.- `src/core/eval-capture-scrub.ts` — zero-deps PII scrubber: emails, phones, SSN, Luhn-verified credit cards, JWT-shaped tokens, bearer tokens.-- `src/core/search/hybrid.ts` — Cathedral II `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; existing callers 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, behavior is byte-for-byte unchanged, 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` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`. 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`; `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. 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}` (new 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.+- `src/core/search/hybrid.ts` — Cathedral II `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; existing callers 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, behavior is byte-for-byte unchanged, 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` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` is the engines' out-channel for searchVector's bounded pagination escalation (one dense page filling the inner candidate pool escalates the pool ×4 up to 3 times; HNSW-backed columns additionally cap at the `ef_search` ceiling, while exact-scan columns above the index dim ceiling are bounded by the escalation count alone); hybrid passes the collector and owns the emit, fired when the loop ends with the pre-DISTINCT pool still full — at the substrate cap or after the escalation budget. 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`; `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. 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}` (new 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.- `docs/eval-capture.md` — stable NDJSON schema reference for gbrain-evals consumers.- `test/public-exports.test.ts` — runtime contract test (R2). Imports each of the 17 public subpaths via package name and pins a canary symbol per module. Paired with `scripts/check-exports-count.sh`.- `src/core/embedding.ts` — OpenAI text-embedding-3-large, batch, retry, backoff. `BATCH_SIZE=100` (per-recipe pre-split + recursive halving + adaptive shrink-on-miss live in the gateway; the outer paginator is for progress-callback granularity, not batch protection). `estimateEmbeddingCostUsd(tokens)` prices against the currently-configured model's rate via `currentEmbeddingPricePerMTok()` (resolves the per-1M-token rate via `lookupEmbeddingPrice(gatewayGetModel())` from `embedding-pricing.ts`, falling back to the OpenAI 3-large rate 0.13 only when the gateway is unconfigured or the model is unknown to the pricing table). `EMBEDDING_COST_PER_1K_TOKENS` retained for back-compat with direct importers/tests. `currentEmbeddingSignature(): string` returns the embedding-provenance signature `<provider:model>:<dims>` (e.g. `openai:text-embedding-3-large:1536`) stamped onto `pages.embedding_signature` at every embed-write site; DELIBERATELY excludes the chunker version (tracked separately via `pages.chunker_version`) — this signature is strictly the EMBEDDING space, so a model OR dimension swap makes the stored signature differ from current and a page becomes stale. Same unconfigured-gateway fallback as the cost helpers. (See `src/core/sync-delta.ts` + `src/core/spend-posture.ts` for the #2139 cost-gate supporting modules.) `willEmbedSynchronously({v2Enabled, serialFlag, noEmbed}): SyncEmbedMode` is the single source of truth for whether `gbrain sync --all` embeds at sync time (`'inline'`) or defers to per-source `embed-backfill` minion jobs (`'deferred'`) — mirrors `sync.ts`'s `effectiveNoEmbed` resolution exactly (`v2Enabled && !serialFlag && !noEmbed → deferred`) so cost gate and embed decision can't drift. `shouldBlockSync(costUsd, floorUsd, mode, posture='gated'): boolean` is the pure cost-gate decision: blocks ONLY when `mode === 'inline' && costUsd > floorUsd` — deferred mode never blocks (the backfill's $X/source/24h cap is the real money gate), and `posture === 'tokenmax'` never blocks (the operator declared cost isn't the constraint; an `off`/`unlimited` floor is `Infinity` and so is never exceeded). Pinned by `test/sync-cost-preview.test.ts` + `test/embedding-signature-stale.test.ts`.@@ -138,8 +138,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check reads `search.reranker.enabled` first so "no events in window" is interpreted correctly (disabled → ok; enabled → ok). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Pinned by `test/search/embedding-column.test.ts` (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison).- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged. Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network.-- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap. A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).-- `src/core/search/autocut.ts` (default ON in reranked modes) — Weaviate-style autocut: score-discontinuity result-sizing on the cross-encoder rerank separatrix. `applyAutocut(results, scoreOf, cfg)` normalizes the reranker scores, finds the largest consecutive gap, and cuts there when it clears `jumpRatio` (default 0.20); robust to unsorted provider output (cuts on a sorted copy, keeps items in INPUT order via a score threshold), guards `top<=0`/non-finite, never returns empty, and no-ops when <2 results carry a finite `rerank_score` (covers the reranker fail-open path). WHY rerank_score and NOT RRF/cosine: gbrain measured (see `return-policy.ts`) that the RRF rank1→rank2 gap is ~flat whether rank-1 is right or wrong — not a separatrix; the cross-encoder score IS. So autocut runs ONLY where the reranker ran (the floor reaches `balanced`+`tokenmax`; `conservative` is a documented no-op). Exports `AutocutConfig`, `DEFAULT_AUTOCUT` (frozen: `enabled=true, jumpRatio=0.20, minKeep=1`), `AutocutDecision` (`{applied, signal:'rerank'|'none', cut, kept, total, gapRatio}`), `AutocutInput`, `autocutFromConfig`, `resolveAutocut`, `applyAutocut`. Cache-key integration (clean path, not the adaptive-return cache-skip hack): enable+sensitivity flow through `ModeBundle` → `ResolvedSearchKnobs` → `knobsHash` exactly like `graph_signals`. `mode.ts` adds `autocut`/`autocut_jump` (conservative false, balanced/tokenmax [email protected]) AND sets `reranker_top_n_in = searchLimit` for reranked modes (so the reranker scores the full returned set; there is no un-scored tail for autocut to wrongly drop — closes the load-bearing recall finding). Autocut folds into `knobsHash` as its own parts entry (`mode.ts:KNOBS_HASH_VERSION` is the single source of truth for the current hash version; every bump is a one-time global cache cold-miss on upgrade). Wired into `hybridSearch` AFTER adaptive-return, BEFORE the limit slice, first page only; emits `HybridSearchMeta.autocut`. BOTH the cache-miss `finalMeta` and cache-HIT `cachedMeta` rebuilds carry `autocut`+`adaptive_return`+`mode`+`embedding_column`. Preserves alias-hop exact matches: `applyAutocut` takes an optional `preserve` predicate; hybrid passes `r => r.alias_hit === true` so a canonical page injected by `applyAliasHop` after reranking (no `rerank_score`) is never cut. Agent surface: `query` op `autocut` boolean (ceiling override — `false` forces full top-K); `SearchOpts.autocut`; `--explain` shows per-result `rerank_score`, `formatAutocutSummary` renders the decision when search meta is threaded; `gbrain search modes` attribution; metric glossary `autocut.signal`/`autocut.gap_ratio`. Config: `search.autocut`, `search.autocut_jump`. Default-ON backed by an in-repo eval gate — `test/search/autocut-eval.test.ts` (also `bun run eval:autocut`) measures precision-lift-without-recall-regression over labeled qrels fixtures with modeled cross-encoder distributions (no API key, no sibling repo; runs in CI): mean precision 0.33→0.94, recall 1.00→0.95, ZERO recall regression on enumeration queries. Env-overridable floors. Pinned by `test/search/autocut.test.ts` (pure-fn), `test/search/query-op-autocut.test.ts` (agent surface), `test/search/autocut-integration.serial.test.ts` (IRON-RULE behavioral via `rerankerFn` DI seam: cliff trims, flat doesn't, no-reranker no-ops, `autocut:false` ceiling, composes with adaptive-return), `test/search/autocut-eval.test.ts` (the precision/recall gate), and the knobsHash assertions in `test/search-mode.test.ts`.+- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).+- `src/core/search/autocut.ts` (default ON in reranked modes) — Weaviate-style autocut: score-discontinuity result-sizing on the cross-encoder rerank separatrix. `applyAutocut(results, scoreOf, cfg)` normalizes the reranker scores, finds the largest consecutive gap, and cuts there when it clears `jumpRatio` (default 0.20); robust to unsorted provider output (cuts on a sorted copy, keeps items in INPUT order via a score threshold), guards `top<=0`/non-finite, never returns empty, and no-ops when <2 results carry a finite `rerank_score` (covers the reranker fail-open path). WHY rerank_score and NOT RRF/cosine: gbrain measured (see `return-policy.ts`) that the RRF rank1→rank2 gap is ~flat whether rank-1 is right or wrong — not a separatrix; the cross-encoder score IS. So autocut runs ONLY where the reranker ran (the floor reaches `balanced`+`tokenmax`; `conservative` is a documented no-op). Weak-top floor: when the top rerank score is below `minTopScore` (default 0.35; config `search.autocut_min_top`; scale-calibrated to the current default reranker — the September reranker default flip must re-tune it), cliff trimming is skipped entirely so a low-confidence list returns the full cluster instead of collapsing to one result. Exports `AutocutConfig`, `DEFAULT_AUTOCUT` (frozen: `enabled=true, jumpRatio=0.20, minKeep=1, minTopScore=0.35`), `AutocutDecision` (`{applied, signal:'rerank'|'none', cut, kept, total, gapRatio}`), `AutocutInput`, `autocutFromConfig`, `resolveAutocut`, `applyAutocut`. Cache-key integration (clean path, not the adaptive-return cache-skip hack): enable+sensitivity flow through `ModeBundle` → `ResolvedSearchKnobs` → `knobsHash` exactly like `graph_signals`. `mode.ts` adds `autocut`/`autocut_jump` (conservative false, balanced/tokenmax [email protected]) AND sets `reranker_top_n_in = searchLimit` for reranked modes (so the reranker scores the full returned set; there is no un-scored tail for autocut to wrongly drop — closes the load-bearing recall finding). Autocut folds into `knobsHash` as its own parts entry (`mode.ts:KNOBS_HASH_VERSION` is the single source of truth for the current hash version; every bump is a one-time global cache cold-miss on upgrade). Wired into `hybridSearch` AFTER adaptive-return, BEFORE the limit slice, first page only; emits `HybridSearchMeta.autocut`. BOTH the cache-miss `finalMeta` and cache-HIT `cachedMeta` rebuilds carry `autocut`+`adaptive_return`+`mode`+`embedding_column`. Preserves alias-hop exact matches: `applyAutocut` takes an optional `preserve` predicate; hybrid passes `r => r.alias_hit === true` so a canonical page injected by `applyAliasHop` after reranking (no `rerank_score`) is never cut. Agent surface: `query` op `autocut` boolean (ceiling override — `false` forces full top-K); `SearchOpts.autocut`; `--explain` shows per-result `rerank_score`, `formatAutocutSummary` renders the decision when search meta is threaded; `gbrain search modes` attribution; metric glossary `autocut.signal`/`autocut.gap_ratio`. Config: `search.autocut`, `search.autocut_jump`. Default-ON backed by an in-repo eval gate — `test/search/autocut-eval.test.ts` (also `bun run eval:autocut`) measures precision-lift-without-recall-regression over labeled qrels fixtures with modeled cross-encoder distributions (no API key, no sibling repo; runs in CI): mean precision 0.33→0.94, recall 1.00→0.95, ZERO recall regression on enumeration queries. Env-overridable floors. Pinned by `test/search/autocut.test.ts` (pure-fn), `test/search/query-op-autocut.test.ts` (agent surface), `test/search/autocut-integration.serial.test.ts` (IRON-RULE behavioral via `rerankerFn` DI seam: cliff trims, flat doesn't, no-reranker no-ops, `autocut:false` ceiling, composes with adaptive-return), `test/search/autocut-eval.test.ts` (the precision/recall gate), and the knobsHash assertions in `test/search-mode.test.ts`.- `src/core/ai/recipes/voyage.ts` — Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declares `default_model: 'voyage-4'` + `default_dims: 1024` — the canonical pick for every "choose a model for the user" surface (`models[0]` stays `voyage-4-large` in quality order; the new-install default is `voyage-4` for price/quality balance and the shared v4 embedding space — see `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` in `ai/defaults.ts`). Reranker touchpoint (the recommended `zerank-2` replacement, same `VOYAGE_API_KEY` as embeddings): `rerank-2.5` flagship ($0.05/M) + `rerank-2.5-lite` ($0.02/M; prices verified 2026-08-15), `path: '/rerank'`, `top_param: 'top_k'` (Voyage's response wire matches ZE's `{results: [{index, relevance_score}]}`; only the request's top-N key differs), 5MB byte-proxy payload cap matching the ZE-era pre-flight. Declares `chars_per_token=1` + `safety_factor=0.5` so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), avoiding the backfill loop where tiktoken-grounded budgeting undercounted Voyage's actual token usage. Declares `multimodal_models: ['voyage-multimodal-3']` so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear `AIConfigError` instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept `output_dimension` live in `VOYAGE_OUTPUT_DIMENSION_MODELS` in `src/core/ai/dims.ts` (v4 trio, `voyage-code-4`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3`; valid widths 256/512/1024/2048); `voyage-4-nano` is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative regression assertion in `test/ai/gateway.test.ts`: `dimsProviderOptions` returns `undefined` for `voyage-4-nano`). `voyage-code-3` is the recommended embedding model for gstack per-worktree code brains (Topology 3 in `docs/architecture/topologies.md`; `voyage-code-4` is the newer hosted code model, flexible dims, $0.12/M); discoverability surfaces: decision-tree branch in `docs/integrations/embedding-providers.md`, Topology 3 "Recommended embedding model" subsection, runtime nudge from `gbrain reindex --code` against non-code-tuned models. Recipe-shape regression pinned by `test/ai/voyage-code-3-recipe.test.ts`.- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe-shape regression pinned by `test/anthropic-model-ids.test.ts`.- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor. Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.@@ -332,13 +332,13 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/worker-pool.ts` — Canonical sliding-pool + bounded-semaphore primitive (extracted from `src/commands/embed.ts` sliding-pool sites and `src/commands/eval-cross-modal.ts` `runWithLimit` semaphore). Two exports: `runSlidingPool<T>({items, workers, onItem, signal?, onError?, failureLabel?, onProgress?})` + `runWithLimit<TIn, TOut>({items, limit, fn, signal?})`. Atomicity invariant: `const idx = nextIdx++` is one synchronous JS statement (no `await` between read and write — guaranteed by the single-threaded event loop), documented in the module header AND enforced by `scripts/check-worker-pool-atomicity.sh` (wired into `bun run verify`), which rejects importing `worker_threads` in any consuming file and inserting `await` between the `nextIdx` read and write. `MUST_ABORT_ERROR_TAGS` set is seeded with `BUDGET_EXHAUSTED` from `src/core/budget/budget-tracker.ts`; tagged errors (matched via `err.tag === 'BUDGET_EXHAUSTED'` to avoid cross-module import) bypass `onError` and hard-abort the pool via `AbortController.abort()` to in-flight `onItem` — the budget cap is a structural ceiling under concurrency. `failures[]` shape is `{idx, label, error}` records (NOT full items; callers supply `failureLabel(item) => string`) for bounded memory under huge brains. Pinned by `test/worker-pool.test.ts` + `test/scripts/check-worker-pool-atomicity.test.ts`. Drives every `--workers N` bulk command.- `src/core/embedding-dim-check.ts` — facts.embedding dim drift surface. `readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>` covers both `vector(N)` and `halfvec(N)` shapes (migration v40 falls back to `vector` on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive `/vector/i` would shadow). `buildFactsAlterRecipe(dims, configured, type)` emits the paste-ready `DROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...` flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change). `assertFactsEmbeddingDimMatchesConfig(engine)` is the preflight — throws `FactsEmbeddingDimMismatchError` (tagged `tag: 'FACTS_EMBEDDING_DIM_MISMATCH'` for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via `WeakMap`; PGLite engines silently skip. Doctor check `facts_embedding_width_consistency` (registered after `embedding_width_consistency`) reuses the same helpers with an identical ALTER recipe. Pinned by `test/embedding-dim-check-facts.test.ts`.- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).-- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (#1586: threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out (#2194/#2227): `PHASE_SCOPE` partitions `ALL_PHASES` into `GLOBAL_PHASES` (brain-wide: embed/orphans/purge/resolve_symbol_edges/grade_takes/calibration_profile/synthesize_concepts/skillopt) and `NON_GLOBAL_PHASES` (source + mixed). Per-source `autopilot-cycle` jobs run only `NON_GLOBAL_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `GLOBAL_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (no longer a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). Future phase wrappers (sync, extract, embed, orphans, extract_facts, resolve_symbol_edges, recompute_emotional_weight) land as additional describes in the same file. with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops fixes. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) replaces the per-hash loop (7K individual queries) with one batched SQL roundtrip returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (regression pin on `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (#2163: the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). #1737: the cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.+- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (#1586: threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out (#2194/#2227): `PHASE_SCOPE` partitions `ALL_PHASES` into `GLOBAL_PHASES` (brain-wide: embed/orphans/purge/resolve_symbol_edges/grade_takes/calibration_profile/synthesize_concepts/skillopt) and `NON_GLOBAL_PHASES` (source + mixed). Per-source `autopilot-cycle` jobs run only `NON_GLOBAL_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `GLOBAL_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (no longer a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). Future phase wrappers (sync, extract, embed, orphans, extract_facts, resolve_symbol_edges, recompute_emotional_weight) land as additional describes in the same file. with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops fixes. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) replaces the per-hash loop (7K individual queries) with one batched SQL roundtrip returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (regression pin on `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (#2163: the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). #1737: the cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade (#4152) where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. The gate `score >= dream.triage.threshold` (default 0.5) is applied at READ time in the fan-out filter, so retuning the threshold re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is byte-identical to the pre-cascade shape) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace — #2415 — and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped (#1586): cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold) + `details.synthesis` (jobs/avg_turns/max_turns_config) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` (#2569) additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — completed legacy rows are read via `loadSuccessfulLegacySynthesisKeys` so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported, replacing `makeHaikuClient()`) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary (lines 395-404) a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock no longer stacks one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`.- `scripts/check-gateway-routed-no-direct-anthropic.sh` — CI guard that fails the build if `src/core/cycle/synthesize.ts` or `src/core/think/index.ts` reintroduces a runtime `new Anthropic()` constructor call or a value-shaped `import Anthropic from '@anthropic-ai/sdk'` import. Type-only imports (`import type Anthropic from '@anthropic-ai/sdk'`) stay allowed for adapter types; comment lines (`//` or ` *` prefixes) are excluded so historical JSDoc doesn't false-fire. Mirrors `scripts/check-jsonb-pattern.sh`. Wired into `bun run verify`. Extend `GUARDED_FILES` when migrating another file off direct SDK construction.- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — #2415: the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh.- `src/core/cycle/extract-facts.ts` — extract_facts cycle phase. Fence is canonical: per-page wipe (`deleteFactsForPage`) + reinsert from `parseFactsFence` + `extractFactsFromFenceText` + `engine.insertFacts`. #1928: the per-page wipe passes `excludeSourcePrefixes: ['cli:']` so conversation facts (written by `extract-conversation-facts`, on pages with NO `## Facts` fence to recreate them from) survive the reconcile instead of being deleted-with-nothing-to-reinsert. The destructive phase no longer inherits a failed sync's full-brain walk: `slugs: []` (a real incremental no-op) is distinguished from `slugs: undefined` (full-walk intent) by presence, not length. `runPhaseExtractFacts` (cycle.ts) surfaces a `warn` (`net_fact_deletion`) when the reconcile deletes at least `NET_DELETION_WARN_FLOOR` (50) more facts than it reinserts — the exact signature of the conversation-facts wipe, which previously read as a silent `ok`. Empty-fence guard refuses when legacy rows (`row_num IS NULL AND entity_slug IS NOT NULL`) pend backfill (status: warn, hint: `gbrain apply-migrations --yes`). A phantom-redirect pre-pass runs AFTER the legacy-row guard, BEFORE the main reconcile loop: when `opts.brainDir` is set, `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun)` walks unprefixed-slug pages capped by `GBRAIN_PHANTOM_REDIRECT_LIMIT` (default 50). The pass returns `touched_canonicals` — canonical slugs whose disk fence merged with phantom rows; `runExtractFacts` UNIONs them into the main reconcile slug set so canonical's DB facts derive from the merged fence in the same cycle (handles phantom-had-only-on-disk-fence). `ExtractFactsResult` gains six phantom fields: `phantomsScanned`, `phantomsRedirected`, `phantomsAmbiguous`, `phantomsSkippedDrift`, `phantomsLockBusy`, `phantomsMorePending`. Three bubble to `CycleReport.totals` (`phantoms_redirected`, `phantoms_ambiguous`, `phantoms_skipped_drift`).- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` → high-specificity fuzzy match for multi-token input (pg_trgm @ 0.7 threshold) → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence; shared-token company names below the threshold remain unresolved. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` → high-specificity fuzzy match for multi-token input (pg_trgm @ 0.7 threshold) → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence; shared-token company names below the threshold remain unresolved. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1; zero residue = phantom). Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match) → `findPrefixCandidates` ambiguity check → `fenceDbDrift` bi-directional check → dry-run early exit → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to canonical's disk fence with `(claim, valid_from)` dedup-guard + row_num continuation → `engine.refreshPageBody` with SHA-256 content_hash recomputed via the import-file shape → `engine.migrateFactsToCanonical` (lossless) → `engine.rewriteLinks` (DB FK rewrite; wiki-link text rewrite is a documented follow-up) → `engine.softDeletePage` + `engine.deleteFactsForPage(phantom)` + `fs.unlinkSync(phantomPath)`. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.- `src/core/facts/phantom-audit.ts` — JSONL audit at `${resolveAuditDir()}/phantoms-YYYY-Www.jsonl`. Pattern copy of `src/core/audit-slug-fallback.ts` (ISO-week rotation, honors `GBRAIN_AUDIT_DIR`). Exports `logPhantomEvent(record)` + `readRecentPhantomEvents(days)` + `computePhantomAuditFilename(now?)`. Records every outcome: `redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy`. Best-effort writes — stderr warn on failure, never throws. Separate file from `stub-guard-audit.ts` (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future `phantoms_pending` doctor check).- `src/core/cycle/emotional-weight.ts` — Pure function `computeEmotionalWeight({tags, takes}, {highEmotionTags?, userHolder?})`. Deterministic 0..1 score: tag-emotion boost (max 0.5, case-insensitive match against `HIGH_EMOTION_TAGS` seed list), take density (0.1/take, capped at 0.3), take avg weight (0..0.1), user-holder ratio (0..0.1 over active takes; default holder `'garry'`). Total clamped to [0..1]. Anglocentric / personal-life-biased seed list intentional; override via config `emotional_weight.high_tags` (JSON array). `userHolder` overridable via `emotional_weight.user_holder`.diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex 7a31743b16..b7e0095682 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -71,7 +71,13 @@ more than embedding proximity. Four layers, added after the incident incandidates to the best chunk per page (`DISTINCT ON (slug)`) over the fullcandidate set before the user `LIMIT`, via the shared `buildBestPerPagePoolCte`in `sql-ranking.ts`. The vector side returns N distinct pages by best chunk,- not N chunks that collapse to fewer pages downstream.+ not N chunks that collapse to fewer pages downstream. When one dense page's+ chunks fill the inner candidate pool, the engines escalate the pool in a+ bounded loop (×4 per step, at most 3 escalations; HNSW-backed columns+ additionally cap at the `ef_search` ceiling) until the page count is honest;+ a loop that ends still underfilled surfaces `vector_pool_underfilled` on the+ hybrid layer's `HybridSearchMeta` (the op-layer capture channel) instead of+ silently returning a short page.- **Title-phrase boost** — when the normalized query is a contiguous token-runinside `page.title` (or an exact full-title match), a floor-ratio-gated,bounded multiplier fires (`applyTitleBoost`, `search.title_boost` knob). A@@ -86,7 +92,12 @@ more than embedding proximity. Four layers, added after the incident in(`alias_hit | exact_title_match | high_vector_match | keyword_exact |weak_semantic`) and `create_safety` (`exists | probable | unknown`). An agentdeciding "is this page already here, safe to NOT write a duplicate?" keys off- `create_safety`, not a raw blended score.+ `create_safety`, not a raw blended score. `high_vector_match` is grounded in+ the result's real query↔chunk cosine (`SearchResult.cosine` at/above+ `search.evidence_cosine_floor`, default 0.80) — never the blended score, so a+ keyword+boost pile-up can't read as semantic support; keyless runs have no+ cosine and degrade to honest keyword-based labels. `gbrain search --explain`+ prints each result's raw cosine next to its blended score.**Extraction quarantine lane (issue #160):** pages carrying the unverifiedauto-extracted markers (frontmatter `provenance: auto-extracted` +@@ -108,11 +119,12 @@ specific miss with `gbrain search diagnose "<q>" --target <slug>`.## Intent-aware query rewriting-`src/core/search/query-intent.ts` classifies queries into `entity`, `temporal`, `event`, or `general`. Each routes through different ranking knobs:+`src/core/search/query-intent.ts` classifies queries into `entity`, `temporal`, `event`, `concept`, or `general`. Each routes through different ranking knobs:- **Entity** queries ("who works at X?") apply a higher graph-traversal weight.- **Temporal** queries ("what happened last week?") bypass source-boost so chat/daily pages surface.- **Event** queries ("Acme AI Series A") engage the timeline index.+- **Concept** queries ("what is the ownership economy?", "find all the companies doing offshore wind" — definitional paraphrases and landscape/quantifier phrasings with no proper noun) rank vector-lean, so keyword-decoy pages stop outranking the page that actually explains the idea. Proper nouns, quoted phrases, and sub-3-word queries never classify as concept — they keep their existing routing.- **General** queries hit the standard hybrid stack.The classifier is deterministic (no LLM call). Wrong classification degrades gracefully — the hybrid stack still works without it.@@ -147,7 +159,7 @@ hybrid recall + fusion:graph augment (optional two-pass structural expansion — walkDepth > 0)│▼-deduplication (4-layer: per-page cap, Jaccard, type diversity)+deduplication (4-layer: per-page cap, same-page Jaccard, type diversity)│▼reranker (cross-encoder — balanced/tokenmax; fail-open)@@ -180,8 +192,12 @@ reranker and therefore no trustworthy cliff signal). `applyAutocut`cross-encoder rerank-score cliff, before the limit slice, first page only.Never-empty failsafe (`minKeep`), no-op when fewer than 2 results carry afinite rerank score (covers the fail-open reranker path), and alias-hop exact-matches are preserved through the cut. Knobs: per-call `SearchOpts.autocut` →-`search.autocut` / `search.autocut_jump` config → mode bundle.+matches are preserved through the cut. Weak-top floor: when the top rerank+score is below `minTopScore` (default 0.35, config `search.autocut_min_top`),+cliff trimming is skipped entirely — a low-confidence list returns the full+cluster for the caller to judge instead of collapsing to one result. Knobs:+per-call `SearchOpts.autocut` → `search.autocut` / `search.autocut_jump` /+`search.autocut_min_top` config → mode bundle.Each stage is testable in isolation. Each stage is replaceable. The whole pipeline is < 1ms of orchestration cost; the latency budget goes to the upstream HTTP calls (embedding, rerank) and the index scans.diff --git a/docs/eval-bench.md b/docs/eval-bench.mdindex 0f16686114..32a3a50bb0 100644--- a/docs/eval-bench.md+++ b/docs/eval-bench.md@@ -588,9 +588,10 @@ gbrain config set autopilot.nightly_quality_probe.enabled truegbrain config set autopilot.nightly_quality_probe.max_usd 5.00 # optional override```-Note: `--phase nightly_quality_probe` wiring into the autopilot scheduler is-deferred to a v0.41+ follow-up (see TODOS.md). For now the phase is callable-in isolation; the test harness exercises it via DI stubs.+The autopilot scheduler invokes the probe on its tick cadence when the+config gate is on (`src/commands/autopilot.ts`, pinned by+`test/autopilot-nightly-probe-wiring.test.ts`); the phase also stays+callable in isolation, and the test harness exercises it via DI stubs.```bash# Manual smoke (exercises the path via DI stubs, no real API spend).diff --git a/docs/eval/BRAINBENCH.md b/docs/eval/BRAINBENCH.mdindex daf70c46d5..2f10934a07 100644--- a/docs/eval/BRAINBENCH.md+++ b/docs/eval/BRAINBENCH.md@@ -21,17 +21,13 @@ Every scoreboard row carries a `seam` column:| Harness | Seam | What the row actually measures ||---|---|---|| `openclaw` | **production** | The shipped OpenClaw context-engine pipeline, byte-for-byte (`extractCandidates` → `resolveEntitiesToPointers`, 3-pointer budget, prior-context suppression, markdown pointer block). |-| `claude-code` | **contract** | gbrain's memory primitives driven through the UserPromptSubmit hook wire contract (`{prompt, session_id, cwd}` in → `{hookSpecificOutput.additionalContext}` out, exported from `src/eval/brainbench/adapters/claude-code.ts`). 2-pointer budget; NO conversation memory — this row deliberately models the memoryless wire contract (suppression off), so the re-injection cost is visible as `false_fire_rate`; the shipped `gbrain hook user-prompt` layers transcript-based cross-turn dedupe on top of this same contract. |-| `codex` | **contract** | The fragments model: a static entity-index preamble (computed once, slugs not counted as injections) + at most ONE per-turn fragment. Measures how much push quality degrades when injection is mostly static. |+| `claude-code` | **production** (v0.46.15) | The shipped Claude Code integration end-to-end: fixture turns become `UserPromptSubmit` stdin JSON; `gbrain hook user-prompt` executes for real (stdin parse → synthesized-transcript window parse → cross-turn dedupe via `hook_additional_context` attachments → IPC `turn_context` over a real unix socket with the real shared secret → `additionalContext`). The row now measures the shipped pointer budget, the volunteer layer, and the transcript dedupe — not a memoryless contract sim. Bench-pinned deviations (disclosed): generous `userPromptDeadlineMs` (10s vs 800ms — CI-load flake control; deadline behavior is hook-suite territory), the push-failure banner suppressed, heartbeat telemetry writes disabled, and the hook's config pointed at the run-scoped bench brain (operator-environment isolation; parallel-test safe). |+| `codex` | **contract** | The fragments model: a static entity-index preamble (computed once, slugs not counted as injections) + at most ONE per-turn fragment. v0.46.15: fixture conversations round-trip through the REAL rollout format + the shipped parser (`src/core/transcripts/codex.ts`) for turn selection — parser drift now tanks the row visibly. Fragment DELIVERY remains a harness-shaped assumption (no shipped codex injection path yet); the full production flip is a filed follow-up. |**Contract rows do NOT measure third-party harness behavior.** They measuregbrain's primitives under each harness's injection-shape constraints. The rowsare comparable because fixtures, brain, and gold are identical — only the seam-contract varies. The real Claude Code integration has landed (`gbrain hook-user-prompt`, registered by `gbrain bootstrap`); flipping this adapter to exec-the real hook and report `production` numbers is a filed follow-up (TODOS.md —-"Flip contract adapters to production"). Same for codex fragments when that-integration lands. Also not graded, by design: the production orchestrator's+varies. Also not graded, by design: the production orchestrator'sconfig gate, integration heartbeat, and 1500 ms timeout wrapper.All three adapters drive ONE shared pipeline (`adapters/shared.ts`) with@@ -66,20 +62,31 @@ grading is faked in v1.### Difficulty is stratified on purpose-Several know-to-ask variants exercise documented v1 reflex limits (lowercase-mentions, surname-only references — `src/core/context/entity-salience.ts`).-Gold records what SHOULD happen; the committed baseline records what the-current system does (`know_to_ask_failure_rate` ≈ 0.15 at v1). The gap is the-measured roadmap, not a bug in the bench.+Several know-to-ask variants exercise what were documented v1 reflex limits+(lowercase mentions, surname-only references —+`src/core/context/entity-salience.ts`). Gold records what SHOULD happen; the+committed baseline records what the current system does. At v1 that gap read+`know_to_ask_failure_rate` ≈ 0.15 — "the measured roadmap, not a bug in the+bench." The v0.46.15 identity wave closed it (weak-alias + surname lexical+arms): the rate is 0.00 on all three harnesses, with `false_fire_rate` and+`push_precision` unmoved — the roadmap framing worked exactly as designed.## Pre-registered expectations (v1, recorded before the first published run)-1. The production seam (openclaw) leads `push_recall` strictly: 3-pointer > 2-pointer > 1-fragment budgets. *(Observed at landing: 0.81 / 0.65 / 0.45.)*-2. The no-suppression contract (claude-code) is the only seam with `false_fire_rate` > 0. *(Observed: 0.02–0.03.)*+1. The production seam (openclaw) leads `push_recall` strictly: 3-pointer > 2-pointer > 1-fragment budgets. *(Observed at landing: 0.81 / 0.65 / 0.45. v0.46.15 identity wave + seam flip: 0.90 / 1.00 / 0.54 — the claude-code row now measures the shipped hook path, whose turn_context assembly (pointers + volunteered pages + real dedupe) outruns the raw pointer budget; the ordering hypothesis applied to the CONTRACT rows and is superseded for flipped rows.)*+2. The no-suppression contract (claude-code) is the only seam with `false_fire_rate` > 0. *(Observed: 0.02–0.03. v0.46.15: 0 — the production seam's real transcript dedupe removes the re-injection cost the contract row deliberately exposed.)*3. `write_back_fidelity` = 1.0 and `provenance_accuracy` = 1.0 in deterministic mode — the production pipeline must not lose or mis-attribute gold facts it was handed. Anything below 1.0 is a pipeline bug, not benchmark noise.4. `source_isolation_violations` = 0 everywhere.5. `push_precision` = 1.0 at v1 (exact-match resolution arms cannot inject an irrelevant page on this corpus); expected to dip below 1.0 when fuzzy/semantic resolution lands — that dip is the precision/recall trade made visible.+The quality floors derived from these expectations are an **executable test**+(`test/brainbench-floors.test.ts`), asserted against the committed baseline on+every suite run: `know_to_ask_failure_rate` ≤ 0.05, `false_fire_rate` ≤ 0.03,+`push_precision` ≥ 0.95, `push_recall` ≥ 0.88 / 0.72 / 0.52+(openclaw / claude-code / codex), `source_isolation_violations` = 0 in every+cell. A baseline update that violates a floor fails the suite — a threshold+violation can no longer be banked by blessing a new baseline.+## Determinism & statistical postureThe harness is deterministic end-to-end: regex extraction + SQL resolutiondiff --git a/docs/guides/push-context.md b/docs/guides/push-context.mdindex 37ef60c324..52ca0db067 100644--- a/docs/guides/push-context.md+++ b/docs/guides/push-context.md@@ -20,9 +20,15 @@ The push channels share one zero-LLM core (`src/core/context/volunteer.ts`):merged with recency / frequency / user-role salience. Assistant-introducedentities and "what did she invest in?" follow-ups whose antecedent was namedin the window now resolve.-2. **Resolve** through the alias table, exact titles, and slug suffixes — each- arm carries an honest confidence: alias 0.9, exact title 0.8, slug-suffix 0.6,- +0.05 when mentioned in ≥2 turns or the newest turn.+2. **Resolve** through the alias table, exact titles, surnames, and slug+ suffixes — each arm carries an honest confidence: alias 0.9, exact title+ 0.8, surname 0.72, slug-suffix 0.6, +0.05 when mentioned in ≥2 turns or the+ newest turn. Lowercase mentions ("remind me what alice said") probe the+ alias table only, and only when the alias is unique across every source in+ play; a surname-only reference ("Did Galewright follow up?") resolves when+ exactly one person page carries that surname. Ambiguity in either arm+ injects nothing — silence beats a wrong pointer. Kill switch for both:+ `retrieval_reflex_lexical_arms` (default on).3. **Gate** at `min_confidence` (default 0.7 — slug-suffix matches need anexplicit lower gate), suppress pages already surfaced (slug-presence only),cap at 3 pages (hard cap 5).@@ -97,6 +103,7 @@ Kill switch: `GBRAIN_HOOKS=0`. Install/uninstall: `docs/guides/bootstrap.md`.| `retrieval_reflex_window_turns` | 4 | turns the ambient reflex extracts from; 1 = legacy current-turn-only (file/env plane: `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`) || `retrieval_reflex` | true | the ambient channel's master switch || `retrieval_reflex_max_pointers` | 3 | pointer cap per turn |+| `retrieval_reflex_lexical_arms` | true | the lowercase-alias + surname recall arms (env: `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`); off = pre-v0.46.15 arm set |Per-call knobs: `max_pages` + `min_confidence` on both the op and `gbrain watch`(`--max-pages` / `--min-confidence`, plus `--window-turns` / `--source` on watch);diff --git a/evals/brainbench/baselines/main.json b/evals/brainbench/baselines/main.jsonindex 324366876b..6815f6168f 100644--- a/evals/brainbench/baselines/main.json+++ b/evals/brainbench/baselines/main.json@@ -16,23 +16,23 @@"write-back"]},- "justification": "ms-002-nondefault-active added (hand-authored): exercises the cross-source leak detector's non-default active_source arm — active_source=teambrain with a twin slug seeded into default+teambrain, a teambrain-only page, and a default-only leak canary. +3 know-to-ask gold turns and +2 push gold turns per harness, all passing on all three harnesses; every gated metric moved favorably or held, source_isolation_violations stays 0.",+ "justification": "Identity-resolution wave (lowercase-alias + surname lexical arms) + claude-code production seam, re-banked after merging master's expanded fixture corpus (v0.46.12.3–v0.46.14.0 waves): kta 0.1452→0 on all three harnesses, push_recall 0.8125/0.6667/0.4583→0.9063/1.0/0.5521 on the 96-gold corpus.","cells": {"claude-code/continuity": {- "avg_injected_tokens": 75.3333,+ "avg_injected_tokens": 59.9167,"continuity_rate": 1,"source_isolation_violations": 0},"claude-code/know-to-ask": {- "avg_injected_tokens": 31.2416,- "false_fire_rate": 0.023,- "know_to_ask_failure_rate": 0.1452,+ "avg_injected_tokens": 37.8389,+ "false_fire_rate": 0,+ "know_to_ask_failure_rate": 0,"source_isolation_violations": 0},"claude-code/push": {- "avg_injected_tokens": 39.028,+ "avg_injected_tokens": 50.1963,"push_precision": 1,- "push_recall": 0.6667,+ "push_recall": 1,"source_isolation_violations": 0},"claude-code/write-back": {@@ -45,15 +45,15 @@"source_isolation_violations": 0},"codex/know-to-ask": {- "avg_injected_tokens": 41,+ "avg_injected_tokens": 45.2215,"false_fire_rate": 0,- "know_to_ask_failure_rate": 0.1452,+ "know_to_ask_failure_rate": 0,"source_isolation_violations": 0},"codex/push": {- "avg_injected_tokens": 48.7664,+ "avg_injected_tokens": 54.6449,"push_precision": 1,- "push_recall": 0.4583,+ "push_recall": 0.5521,"source_isolation_violations": 0},"codex/write-back": {@@ -66,15 +66,15 @@"source_isolation_violations": 0},"openclaw/know-to-ask": {- "avg_injected_tokens": 34.0537,+ "avg_injected_tokens": 38.2752,"false_fire_rate": 0,- "know_to_ask_failure_rate": 0.1452,+ "know_to_ask_failure_rate": 0,"source_isolation_violations": 0},"openclaw/push": {- "avg_injected_tokens": 44.2056,+ "avg_injected_tokens": 50.0841,"push_precision": 1,- "push_recall": 0.8125,+ "push_recall": 0.9063,"source_isolation_violations": 0},"openclaw/write-back": {@@ -89,11 +89,11 @@},"claude-code/know-to-ask": {"gold_total": 149,- "gold_failed": 11+ "gold_failed": 0},"claude-code/push": {"gold_total": 96,- "gold_failed": 32+ "gold_failed": 0},"claude-code/write-back": {"gold_total": 58,@@ -105,11 +105,11 @@},"codex/know-to-ask": {"gold_total": 149,- "gold_failed": 9+ "gold_failed": 0},"codex/push": {"gold_total": 96,- "gold_failed": 52+ "gold_failed": 43},"codex/write-back": {"gold_total": 58,@@ -121,11 +121,11 @@},"openclaw/know-to-ask": {"gold_total": 149,- "gold_failed": 9+ "gold_failed": 0},"openclaw/push": {"gold_total": 96,- "gold_failed": 18+ "gold_failed": 9},"openclaw/write-back": {"gold_total": 58,diff --git a/llms-full.txt b/llms-full.txtindex 04da7c4c66..1ac35d23bf 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -4019,9 +4019,15 @@ The push channels share one zero-LLM core (`src/core/context/volunteer.ts`):merged with recency / frequency / user-role salience. Assistant-introducedentities and "what did she invest in?" follow-ups whose antecedent was namedin the window now resolve.-2. **Resolve** through the alias table, exact titles, and slug suffixes — each- arm carries an honest confidence: alias 0.9, exact title 0.8, slug-suffix 0.6,- +0.05 when mentioned in ≥2 turns or the newest turn.+2. **Resolve** through the alias table, exact titles, surnames, and slug+ suffixes — each arm carries an honest confidence: alias 0.9, exact title+ 0.8, surname 0.72, slug-suffix 0.6, +0.05 when mentioned in ≥2 turns or the+ newest turn. Lowercase mentions ("remind me what alice said") probe the+ alias table only, and only when the alias is unique across every source in+ play; a surname-only reference ("Did Galewright follow up?") resolves when+ exactly one person page carries that surname. Ambiguity in either arm+ injects nothing — silence beats a wrong pointer. Kill switch for both:+ `retrieval_reflex_lexical_arms` (default on).3. **Gate** at `min_confidence` (default 0.7 — slug-suffix matches need anexplicit lower gate), suppress pages already surfaced (slug-presence only),cap at 3 pages (hard cap 5).@@ -4096,6 +4102,7 @@ Kill switch: `GBRAIN_HOOKS=0`. Install/uninstall: `docs/guides/bootstrap.md`.| `retrieval_reflex_window_turns` | 4 | turns the ambient reflex extracts from; 1 = legacy current-turn-only (file/env plane: `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`) || `retrieval_reflex` | true | the ambient channel's master switch || `retrieval_reflex_max_pointers` | 3 | pointer cap per turn |+| `retrieval_reflex_lexical_arms` | true | the lowercase-alias + surname recall arms (env: `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`); off = pre-v0.46.15 arm set |Per-call knobs: `max_pages` + `min_confidence` on both the op and `gbrain watch`(`--max-pages` / `--min-confidence`, plus `--window-turns` / `--source` on watch);diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex e013c6abce..2b2ffcccf3 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.14.0",+ "version": "0.46.15.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 58c4a34e28..2bd1cd1028 100644--- a/package.json+++ b/package.json@@ -170,7 +170,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.14.0",+ "version": "0.46.15.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin/README.md b/plugin/README.mdindex e0e698196f..3dd005c46f 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.14.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.15.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 7463d6959c..9be585aaf0 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -5,8 +5,8 @@# Columns: path max_lines policy notesrc/commands/doctor.ts 4270 ratchet peel target: containment sprint C8-C13; grown v0.46.11.0 five-issue wavesrc/core/operations.ts 303 ratchet peel target: containment sprint C4-C7-src/core/postgres-engine.ts 5770 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave-src/core/pglite-engine.ts 5660 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave+src/core/postgres-engine.ts 5807 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave + retrieval wave+src/core/pglite-engine.ts 5691 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave + retrieval wavesrc/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratchetedsrc/commands/sync.ts 4300 ratchet peel target: containment sprint C13-C14; grown v0.46.11.0 five-issue wavesrc/core/ai/gateway.ts 4168 ratchet watchlist@@ -14,7 +14,7 @@ src/cli.ts 3453 ratchet watchlist; +21 gap-closure wave thin-client routing; +casrc/core/cycle.ts 3024 ratchetsrc/commands/serve-http.ts 2978 ratchet grown cathedral-6 multi-agent wave (admin register route composes registerScopedClient in one tx under the name advisory lock; ttl validation + brain_too_old preflight) + chennai no-grant federated scopesrc/commands/jobs.ts 2950 ratchet grown v0.46.11.0 five-issue wave-src/core/search/hybrid.ts 2479 ratchet+src/core/search/hybrid.ts 2500 ratchetsrc/core/engine.ts 2345 ratchetsrc/commands/autopilot.ts 2301 ratchetsrc/commands/extract.ts 2161 ratchet@@ -22,7 +22,7 @@ src/commands/extract-conversation-facts.ts 1968 ratchetsrc/core/import-file.ts 2000 ratchet grown v0.46.11.0 five-issue wavesrc/core/cycle/synthesize.ts 2685 ratchet grown v0.46.11.0 five-issue wavesrc/commands/embed.ts 1963 ratchet-src/core/types.ts 1851 ratchet+src/core/types.ts 1863 ratchetsrc/commands/skillpack.ts 1763 ratchetsrc/core/minions/queue.ts 2130 ratchet grown v0.46.11.0 five-issue wavesrc/commands/init.ts 1932 ratchet@@ -32,4 +32,4 @@ src/commands/bootstrap.ts 1923 ratchet grandfathered at merge (grew past the 150src/core/minions/worker.ts 1560 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wavesrc/commands/sources.ts 1676 ratchetsrc/core/bootstrap/harness.ts 1947 ratchet-src/commands/hook.ts 1525 ratchet+src/commands/hook.ts 1551 ratchetdiff --git a/scripts/run-eval-canary.ts b/scripts/run-eval-canary.tsindex 912b0e95fa..e564e6baa9 100644--- a/scripts/run-eval-canary.ts+++ b/scripts/run-eval-canary.ts@@ -204,7 +204,15 @@ async function main(): Promise<number> {// dotfiles and Bun-auto-loaded .env files can't reroute the brain.const child = spawnSync(process.execPath,- [join(ROOT, 'src', 'cli.ts'), 'eval', 'gate', '--qrels', QRELS_PATH, '--embedder', 'deterministic', '--json'],+ [+ join(ROOT, 'src', 'cli.ts'), 'eval', 'gate', '--qrels', QRELS_PATH, '--embedder', 'deterministic', '--json',+ // v0.46.8: the corpus grew concept-paraphrase queries (q13/q14) and+ // the pre-wave observed rate was 10/12 — raise the expected_top1+ // floor from the loose default (0.50) to 0.85 so a single-query+ // top-1 regression (incl. a concept-weight regression) actually+ // FAILS the gate instead of coasting on the old floor.+ '--threshold-expected-top1', '0.85',+ ],{cwd: tmpHome,env: childEnv as NodeJS.ProcessEnv,diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 8609495803..0d151cd1a3 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -158,6 +158,27 @@ export interface HookIo {spawnPush?: (root: string) => void;/** TEST SEAM: user-prompt deadline override (wall-clock flake control). */userPromptDeadlineMs?: number;+ /**+ * TEST SEAM (v0.46.15, BrainBench production seam): config override for+ * hookUserPrompt — `undefined` = load the real file-plane config;+ * `null`/object = use as-is. Lets the bench point the hook at a throwaway+ * brain WITHOUT mutating process-global GBRAIN_HOME (parallel-test safe).+ */+ configOverride?: GBrainConfig | null;+ /**+ * TEST SEAM (v0.46.15): suppress the pending-push failure banner. The+ * banner reads the OPERATOR's real push-status files — on a bench run+ * that's environmental contamination (a locally-failing push would inject+ * a banner on stay-silent turns and read as a false fire).+ */+ disablePushBanner?: boolean;+ /**+ * TEST SEAM (v0.46.15, codex ship-review): suppress hook telemetry WRITES+ * (heartbeat JSONL). Telemetry paths resolve from GBRAIN_HOME/homedir —+ * NOT from configOverride — so a hermetic bench replay would otherwise+ * append every fixture turn to the operator's real hook-health history.+ */+ disableTelemetry?: boolean;/*** Feedback-loop attribution channel (`--harness <claude-code|codex|opencode>`).* Default 'claude-code' — the only harness bootstrap registers hooks for@@ -429,7 +450,12 @@ const HEARTBEAT_COMPACT_CHECK_BYTES = 2 * HEARTBEAT_MAX_LINES * 40;* check says the file exceeds ~2x the cap. Fields are copied EXPLICITLY — the* schema allowlist is enforced by construction, not by trust. Never throws.*/-async function writeHeartbeat(entry: HookHeartbeatEntry): Promise<void> {+async function writeHeartbeat(io: HookIo, entry: HookHeartbeatEntry): Promise<void> {+ // TEST SEAM (codex ship-review): a BrainBench replay drives the REAL hook+ // in-process without redirecting GBRAIN_HOME — without this gate every+ // fixture turn would append to the OPERATOR's real hook-health history and+ // skew doctor/failure-notice reads. Benches are hermetic; telemetry is not.+ if (io.disableTelemetry) return;try {const p = await heartbeatPath();const line = JSON.stringify({@@ -576,7 +602,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {outcome = 'error';reason = errorCode(e); // fail-open: empty stdout, exit 0}- await writeHeartbeat({+ await writeHeartbeat(io, {ts: new Date().toISOString(),event: 'session-start',outcome,@@ -1051,7 +1077,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {let wrotePayload = false;const work = (async (): Promise<UserPromptOutcome> => {- banner = pendingPushFailureBanner();+ banner = io.disablePushBanner ? null : pendingPushFailureBanner();const j = await readStdinJson(io, 300);if (!j) return { outcome: 'degraded', reason: 'no_stdin' };@@ -1103,7 +1129,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {if (prompt.trim()) turns = [...turns, { role: 'user', text: prompt }];if (turns.length === 0) return { outcome: 'ok', reason: 'empty_window' };- const cfg = loadConfig();+ const cfg = io.configOverride !== undefined ? io.configOverride : loadConfig();if (!cfg?.database_path) {// No config, or a Postgres brain (no PGLite data dir → no IPC socket).// ENGINE-FREE means no direct-engine fallback here; pull-mode covers it.@@ -1203,7 +1229,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {);pendingBanner.record();}- await writeHeartbeat({+ await writeHeartbeat(io, {ts: new Date().toISOString(),event: 'user-prompt',outcome: result.outcome,@@ -1291,7 +1317,7 @@ async function hookCompact(io: HookIo): Promise<number> {outcome = 'error';reason = errorCode(e); // fail-open: exit 0}- await writeHeartbeat({+ await writeHeartbeat(io, {ts: new Date().toISOString(),event: 'compact',outcome,@@ -1334,7 +1360,7 @@ async function hookStop(io: HookIo): Promise<number> {} catch {pushReason = 'push_unavailable';}- await writeHeartbeat({+ await writeHeartbeat(io, {ts: new Date().toISOString(),event: 'stop',outcome,@@ -1511,7 +1537,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {/* best effort */}- await writeHeartbeat({+ await writeHeartbeat(io, {ts: new Date().toISOString(),event: 'session-end',outcome,diff --git a/src/commands/watch.ts b/src/commands/watch.tsindex 9c990e7d27..cd10bfefba 100644--- a/src/commands/watch.ts+++ b/src/commands/watch.ts@@ -39,7 +39,7 @@ import {VOLUNTEER_DEFAULT_MIN_CONFIDENCE,} from '../core/context/volunteer.ts';import type { WindowTurn } from '../core/context/entity-salience.ts';-import { DEFAULT_WINDOW_TURNS, windowTurnCount } from '../core/context/reflex.ts';+import { DEFAULT_WINDOW_TURNS, windowTurnCount, lexicalArmsEnabled } from '../core/context/reflex.ts';import { loadConfig } from '../core/config.ts';import { logVolunteerEventsFireAndForget, volunteerEventRowsFrom } from '../core/context/volunteer-events.ts';@@ -161,6 +161,7 @@ export async function runWatch(engine: BrainEngine, args: string[], deps: WatchI// Session dedupe: skipped inside the core BEFORE the gate + cap// (O(1) per pointer) so a recurring slug can't starve new pages.excludeSlugs: pushedSlugs,+ lexicalArms: lexicalArmsEnabled(loadConfig()),});} catch {continue; // fail-open per turn: a transient DB error never kills the streamdiff --git a/src/core/by-mention.ts b/src/core/by-mention.tsindex bf5c11107d..31eff4462e 100644--- a/src/core/by-mention.ts+++ b/src/core/by-mention.ts@@ -27,6 +27,7 @@*/import type { BrainEngine } from './engine.ts';+import { isUndefinedTableError } from './utils.ts';import { CJK_SLUG_CHARS } from './cjk.ts';import { stripCodeBlocks } from './link-extraction.ts';@@ -40,6 +41,8 @@ export const LINKABLE_ENTITY_TYPES = ['person', 'company', 'organization', 'enti* pack-aware follow-up (TODO-1) can let users opt specific 3-char entity* types in.*/+let aliasGazetteerWarned = false;+const MIN_NAME_LENGTH = 4;const MIN_CJK_NAME_LENGTH = 2;@@ -390,6 +393,12 @@ export async function buildGazetteer(if (!row.title) continue;if (!hasCJK(row.title) && row.title.length < MIN_NAME_LENGTH) continue;if (hasCJK(row.title) && cjkCharCount(row.title) < MIN_CJK_NAME_LENGTH) continue;+ // NOTE (v0.46.15, deliberately preserved): for TITLES this condition is+ // intentionally vacuous — every row here IS a real page, so an+ // ignore-listed name the user explicitly created a page for is always+ // allowed (documented CK12 policy). The ignore list bites only via+ // opts.extraIgnore names that have no page, and — with real teeth — on+ // the ALIAS entries below, which are not user-created pages.if (ignoreSet.has(row.title) && !existingTitles.has(row.title)) continue;const tokens = tokenizeTitle(row.title);@@ -408,6 +417,78 @@ export async function buildGazetteer(else gazetteer.set(key, [entry]);}+ // ── Alias entries (v0.46.15 identity wave, #3801) ────────────────────────+ // page_aliases rows joined to LIVE entity-typed pages become additional+ // gazetteer entries, so a body mention of "saoirse" links to+ // people/saoirse-x. Guards (stricter than titles — aliases are not+ // user-created pages):+ // - ignore-list applies CASE-INSENSITIVELY with NO existing-page escape+ // (aliases store normalized lowercase; DEFAULT_IGNORE_LIST is cased)+ // - aliases mapping to >1 slug within a source are skipped (ambiguous)+ // - aliases colliding with any existing page TITLE in the SAME source+ // are skipped (the title entry wins; per-source scoping per R2-9)+ // - MIN_NAME_LENGTH applies to the alias string+ try {+ const aliasRows = await engine.executeRaw<{+ alias_norm: string;+ slug: string;+ source_id: string | null;+ title: string | null;+ }>(+ `SELECT pa.alias_norm, pa.slug, pa.source_id, p.title+ FROM page_aliases pa+ JOIN pages p ON p.slug = pa.slug AND p.source_id = pa.source_id+ WHERE p.type IN (${typeList})+ AND p.deleted_at IS NULL`,+ [],+ );+ const ignoreLc = new Set(Array.from(ignoreSet, (s) => s.toLowerCase()));+ // Per-source title index for alias-vs-title collision checks.+ const titleBySource = new Set<string>();+ for (const r of rows) {+ if (r.title) titleBySource.add(`${r.source_id ?? 'default'} ${r.title.toLowerCase()}`);+ }+ // Ambiguity: same (source, alias) → multiple slugs.+ const bySourceAlias = new Map<string, Set<string>>();+ for (const a of aliasRows) {+ const k = `${a.source_id ?? 'default'} ${a.alias_norm}`;+ const set = bySourceAlias.get(k) ?? new Set<string>();+ set.add(a.slug);+ bySourceAlias.set(k, set);+ }+ const seenAliasEntry = new Set<string>();+ for (const a of aliasRows) {+ const alias = a.alias_norm?.trim();+ if (!alias || !a.title) continue;+ const src = a.source_id ?? 'default';+ if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) continue;+ if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) continue;+ if (ignoreLc.has(alias.toLowerCase())) continue;+ if ((bySourceAlias.get(`${src} ${alias}`)?.size ?? 0) > 1) continue;+ if (titleBySource.has(`${src} ${alias.toLowerCase()}`)) continue;+ const dedupeKey = `${src} ${alias} ${a.slug}`;+ if (seenAliasEntry.has(dedupeKey)) continue;+ seenAliasEntry.add(dedupeKey);+ const tokens = tokenizeTitle(alias);+ if (tokens.length === 0) continue;+ if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) continue;+ const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens };+ const key = tokens[0]!;+ const bucket = gazetteer.get(key);+ if (bucket) bucket.push(entry);+ else gazetteer.set(key, [entry]);+ }+ } catch (err) {+ // pre-v110 brains: no page_aliases table — titles-only gazetteer.+ // Any OTHER failure (connection blip, permission) warns once per process+ // (adversarial F12): a silently titles-only gazetteer under-links every+ // page processed until restart, and nobody would know why.+ if (!isUndefinedTableError(err) && !aliasGazetteerWarned) {+ aliasGazetteerWarned = true;+ console.error(`[gbrain] gazetteer alias load degraded (titles-only): ${err instanceof Error ? err.message : String(err)}`);+ }+ }+// Sort each bucket by token-count DESC so maximal-munch walks longest-first.for (const bucket of gazetteer.values()) {bucket.sort((a, b) => b.tokens.length - a.tokens.length);diff --git a/src/core/config.ts b/src/core/config.tsindex 4afccffd87..6b60e74616 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -265,6 +265,15 @@ export interface GBrainConfig {* reflex knobs.*/retrieval_reflex_window_turns?: number;+ /**+ * v0.46.15 (identity wave) — kill switch for the reflex's lexical recall+ * arms (lowercase weak-candidate alias arm + surname arm). Default ON+ * (absent = enabled); `false` reproduces pre-wave resolution exactly.+ * File-plane / env (GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS) only — same+ * plane as the other reflex knobs; a false-fire regression in production+ * reverts on the next turn with a config edit, no redeploy.+ */+ retrieval_reflex_lexical_arms?: boolean;embedding_image_ocr?: boolean;embedding_image_ocr_model?: string;@@ -667,6 +676,15 @@ export function loadConfig(): GBrainConfig | null {Number.isFinite(Number(process.env.GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS))? { retrieval_reflex_window_turns: Number(process.env.GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS) }: {}),+ ...(process.env.GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS+ ? {+ // Case-insensitive + common negatives — incident escape hatch;+ // mirrors reflex.ts:lexicalArmsEnabled (adversarial F11).+ retrieval_reflex_lexical_arms: !/^(false|0|off|no)$/i.test(+ process.env.GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS.trim(),+ ),+ }+ : {}),...(process.env.GBRAIN_REMOTE_CLIENT_SECRET && fileConfig?.remote_mcp? { remote_mcp: { ...fileConfig.remote_mcp, oauth_client_secret: process.env.GBRAIN_REMOTE_CLIENT_SECRET } }: {}),diff --git a/src/core/context/entity-salience.ts b/src/core/context/entity-salience.tsindex 91082a0dc7..a80ad7b025 100644--- a/src/core/context/entity-salience.ts+++ b/src/core/context/entity-salience.ts@@ -28,11 +28,29 @@ export interface EntityCandidate {display: string;/** Text fed to alias-normalize / slugify for resolution (no leading @, no possessive). */query: string;+ /**+ * Lowercase weak candidate (v0.46.15 identity wave). Emitted by the+ * lowercase pass for turns like "remind me what saoirse said" — the v1+ * capitalization-biased extractor was blind to these (the documented+ * know-to-ask limit). Weak candidates are resolution-restricted: the+ * resolver may probe them against the ALIAS table only (exact, unique,+ * live-page-verified) — never title/slug/suffix arms — so ordinary+ * lowercase words cannot fabricate pointers.+ */+ weak?: true;}-/** Max candidates returned per turn — bounds downstream DB work regardless of pointer cap. */+/** Max STRONG candidates returned per turn — bounds downstream DB work regardless of pointer cap. */export const MAX_CANDIDATES = 12;+/**+ * Max lowercase WEAK candidates per turn. Separate budget from+ * MAX_CANDIDATES (weak tokens never evict or crowd out strong ones); the+ * resolver caps on alias HITS, not raw tokens, so this only bounds the+ * batched alias probe size.+ */+export const MAX_WEAK_CANDIDATES = 32;+/*** HARD stopwords — function words that are never an entity, even capitalized* mid-sentence. Pronouns, articles/determiners, auxiliaries, conjunctions,@@ -99,6 +117,11 @@ function isPureNumber(s: string): boolean {return /^[0-9][0-9.,]*$/.test(s);}+// Lowercase-initial word of ≥3 chars, whole-word (lookarounds instead of \b —+// \b misbehaves with unicode property classes). The lookbehind also excludes+// @handles (step 1 owns those) and the lowercase TAIL of a capitalized word.+const WEAK_TOKEN_RE = /(?<![\p{L}\p{N}'’@-])\p{Ll}[\p{L}\p{N}'’-]{2,}(?![\p{L}\p{N}'’-])/gu;+/*** Extract candidate entity surface-forms from one turn's text.* Deterministic, precision-biased, capped at MAX_CANDIDATES. Deduped on the@@ -153,6 +176,22 @@ export function extractCandidates(text: string): EntityCandidate[] {const surface = m[0];const idx = m.index ?? 0;consider(surface, surface, !isAtSentenceStart(text, idx));+ // Leading-stopword trim (v0.46.15 identity wave): a sentence-start+ // auxiliary glues into the run — "Did Galewright ever…" extracts+ // "Did Galewright", which resolves to nothing. ALSO consider the+ // remainder with the leading hard-stopword tokens shed. The trimmed+ // token is positionally mid-sentence (it follows the stopword), which+ // is exactly the strong "this is a real name" signal. Keep the+ // original run too — "Will Smith" must still resolve whole.+ const tokens = surface.split(/\s+/);+ let firstKept = 0;+ while (firstKept < tokens.length && STOPWORDS.has(stripPossessive(tokens[firstKept]).toLowerCase())) {+ firstKept++;+ }+ if (firstKept > 0 && firstKept < tokens.length) {+ const trimmed = tokens.slice(firstKept).join(' ');+ consider(trimmed, trimmed, true);+ }}// 3. Filter for precision.@@ -173,6 +212,35 @@ export function extractCandidates(text: string): EntityCandidate[] {out.push({ display: c.display, query: c.query });if (out.length >= MAX_CANDIDATES) break;}++ // 2.5→3.5. Lowercase WEAK pass (v0.46.15 identity wave, documented v1 limit).+ // Users type names lowercase ("remind me what saoirse said"); the alias+ // table stores normalized forms, so an exact unique alias hit is the same+ // evidence class regardless of source casing. Weak candidates ride a+ // SEPARATE budget (never evict strong), and the resolver restricts them to+ // the alias arm — a generic lowercase word only fabricates a pointer if it+ // is literally a unique registered alias.+ // Built from the EMITTED strong list, not the raw accumulator (adversarial+ // F10): a strong candidate the precision filter REJECTED (e.g. a common+ // word seen only at sentence start) must not shadow the same norm's weak+ // alias probe — that's exactly the name-collides-with-a-common-word case+ // the alias table exists to disambiguate.+ const strongNorms = new Set(out.map((c) => normalizeAlias(c.query)).filter(Boolean));+ const weakSeen = new Set<string>();+ let weakCount = 0;+ for (const m of text.matchAll(WEAK_TOKEN_RE)) {+ if (weakCount >= MAX_WEAK_CANDIDATES) break;+ const raw = stripPossessive(m[0]);+ if (raw.length < 3) continue;+ const lc = raw.toLowerCase();+ if (STOPWORDS.has(lc) || COMMON_WORDS.has(lc)) continue;+ const norm = normalizeAlias(raw);+ if (!norm) continue;+ if (strongNorms.has(norm) || weakSeen.has(norm)) continue; // covered by a strong candidate / dup+ weakSeen.add(norm);+ weakCount++;+ out.push({ display: raw, query: raw, weak: true });+ }return out;}@@ -226,6 +294,14 @@ export function extractCandidatesFromWindow(turns: WindowTurn[]): WindowEntityCaexisting.occurrences += 1;existing.lastTurnIdx = i;existing.inNewestTurn = existing.inNewestTurn || i === lastIdx;+ // A strong sighting upgrades a weak-born candidate: the weak flag+ // clears (it may now use all resolution arms) and the capitalized+ // surface beats the lowercase one (unless a user-said label already+ // won and this sighting is assistant-only).+ if (existing.weak && !c.weak) {+ delete existing.weak;+ if (!existing.userMention || turn.role === 'user') existing.display = c.display;+ }if (turn.role === 'user' && !existing.userMention) {// First USER-said surface form beats an assistant-introduced one// for the display label.@@ -236,6 +312,7 @@ export function extractCandidatesFromWindow(turns: WindowTurn[]): WindowEntityCaacc.set(norm, {display: c.display,query: c.query,+ ...(c.weak ? { weak: true as const } : {}),occurrences: 1,lastTurnIdx: i,inNewestTurn: i === lastIdx,@@ -247,11 +324,15 @@ export function extractCandidatesFromWindow(turns: WindowTurn[]): WindowEntityCa}// Salience weight: recency dominates, then frequency, then user-role.- // Deterministic tie-break on first-seen order.+ // Deterministic tie-break on first-seen order. Strong candidates rank+ // STRICTLY above weak ones (separate budgets too) — recent weak noise can+ // never evict an older strong candidate.const weight = (c: WAcc) =>(c.lastTurnIdx + 1) / turns.length + Math.min(c.occurrences, 4) * 0.1 + (c.userMention ? 0.15 : 0);- return Array.from(acc.values())- .sort((a, b) => weight(b) - weight(a) || a.order - b.order)- .slice(0, MAX_CANDIDATES)- .map(({ lastTurnIdx: _l, order: _o, ...rest }) => rest);+ const sorted = Array.from(acc.values()).sort(+ (a, b) => (a.weak ? 1 : 0) - (b.weak ? 1 : 0) || weight(b) - weight(a) || a.order - b.order,+ );+ const strong = sorted.filter((c) => !c.weak).slice(0, MAX_CANDIDATES);+ const weak = sorted.filter((c) => c.weak).slice(0, MAX_WEAK_CANDIDATES);+ return [...strong, ...weak].map(({ lastTurnIdx: _l, order: _o, ...rest }) => rest);}diff --git a/src/core/context/reflex.ts b/src/core/context/reflex.tsindex 188dbea21b..a511bd757a 100644--- a/src/core/context/reflex.ts+++ b/src/core/context/reflex.ts@@ -39,6 +39,8 @@ export interface ResolveEntitiesOpts {maxPointers?: number;/** v0.43 (#2095): 'slug-only' under windowing — see ResolvePointersOpts. */suppression?: 'slug-and-title' | 'slug-only';+ /** v0.46.15: lexical-arms kill switch — see ResolvePointersOpts.lexicalArms. */+ lexicalArms?: boolean;}/**@@ -106,6 +108,21 @@ export function reflexEnabled(cfg: GBrainConfig | null): boolean {return cfg?.retrieval_reflex !== false;}+/**+ * v0.46.15 identity wave — kill switch for the lexical recall arms+ * (weak-candidate alias arm + surname arm). Default ON; same env-direct+ * pattern as reflexEnabled/windowTurnCount so a config-less environment+ * still honors the escape hatch.+ */+export function lexicalArmsEnabled(cfg: GBrainConfig | null): boolean {+ const env = process.env.GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS;+ // Case-insensitive + common negatives (adversarial F11): this is the+ // incident escape hatch — an operator typing FALSE/off/no mid-incident must+ // not get a silent no-op. (Sibling gates keep the stricter legacy parse.)+ if (env != null && env !== '') return !/^(false|0|off|no)$/i.test(env.trim());+ return cfg?.retrieval_reflex_lexical_arms !== false;+}+function maxPointers(cfg: GBrainConfig | null): number {const n = cfg?.retrieval_reflex_max_pointers;return typeof n === 'number' && n > 0 ? n : DEFAULT_MAX_POINTERS;@@ -135,6 +152,7 @@ export async function buildReflexAddition(params: ReflexParams): Promise<stringpriorContextText: params.priorContextText,maxPointers: maxPointers(cfg),suppression: windowed ? 'slug-only' : 'slug-and-title',+ lexicalArms: lexicalArmsEnabled(cfg),};const block = await withTimeout(resolve(params, cfg, candidates, opts), TIMEOUT_MS);if (!block || !block.pointers.length) return null;diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.tsindex bd2e350247..51b98c3f78 100644--- a/src/core/context/resolve-ipc.ts+++ b/src/core/context/resolve-ipc.ts@@ -90,6 +90,11 @@ export interface ResolveRequest {sourceId?: string;/** v0.43 (#2095, codex D7): suppression mode — 'slug-only' under windowing. */suppression?: 'slug-and-title' | 'slug-only';+ /**+ * v0.46.15: lexical-arms kill switch. Either side may disable: a client+ * `false` wins; otherwise the server applies its own file-config gate.+ */+ lexicalArms?: boolean;}export interface TurnContextRequest {diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.tsindex 2d6c19f278..ae80b6e264 100644--- a/src/core/context/retrieval-reflex.ts+++ b/src/core/context/retrieval-reflex.ts@@ -25,6 +25,7 @@import type { BrainEngine } from '../engine.ts';import { normalizeAlias } from '../search/alias-normalize.ts';+import { escapeLikePattern } from '../search/sql-ranking.ts';import { slugify } from '../entities/resolve.ts';import { stripTakesFence } from '../takes-fence.ts';import { stripFactsFence } from '../facts-fence.ts';@@ -35,17 +36,23 @@ export const DEFAULT_MAX_POINTERS = 3;const SYNOPSIS_MAX = 160;/** Which resolution arm produced a pointer (provenance → honest confidence). */-export type ResolveArm = 'alias' | 'title' | 'slug-suffix';+export type ResolveArm = 'alias' | 'title' | 'slug-suffix' | 'title-surname';/*** v0.43 (#2095) — arm → confidence. Lives HERE, next to the arm definitions,* so arm identity and its score can't drift apart (eng-review note). The* volunteer layer imports these; small deterministic boosts (multi-turn /* newest-turn mention) are added on top there.+ *+ * 'title-surname' (v0.46.15 identity wave) sits at 0.72 — deliberately ABOVE+ * the volunteer layer's 0.70 default gate (a 0.6x score would be silently+ * discarded there) and below 'title' (an exact-title hit is stronger+ * evidence than a surname-tail match).*/export const ARM_CONFIDENCE: Record<ResolveArm, number> = {alias: 0.9,title: 0.8,+ 'title-surname': 0.72,'slug-suffix': 0.6,};@@ -104,6 +111,15 @@ export interface ResolvePointersOpts {* arm uses source_id = ANY(...) in one query.*/sourceIds?: string[];+ /**+ * v0.46.15 identity wave — kill switch for the two new lexical arms (the+ * weak-candidate alias arm and the surname arm). Default ON (undefined =+ * enabled); `false` reproduces pre-wave resolution exactly. Threaded from+ * the file-plane config `retrieval_reflex_lexical_arms` / env+ * `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS` by callers that own a loaded+ * config — the resolver itself never touches config (sync hot path).+ */+ lexicalArms?: boolean;}export interface PageRow {@@ -131,6 +147,10 @@ export async function resolveEntitiesToPointers(const maxPointers = opts.maxPointers ?? DEFAULT_MAX_POINTERS;const priorLc = (opts.priorContextText ?? '').toLowerCase();+ // v0.46.15 identity wave: the two new lexical arms (weak-alias + surname)+ // share one kill switch. Default ON; `false` reproduces pre-wave behavior.+ const lexicalArms = opts.lexicalArms !== false;+// display lookup keyed by normalized query, so resolved slugs can recover a// human surface form for the pointer label.const displayByNorm = new Map<string, string>();@@ -138,11 +158,33 @@ export async function resolveEntitiesToPointers(const titlesLc: string[] = [];const exactSlugs: string[] = [];const slugSuffixes: string[] = [];+ // Weak candidates resolve through the ALIAS arm only (exact, unique). Their+ // norms are tracked so the alias fold can apply the stricter cross-source+ // uniqueness rule to them.+ const weakNorms = new Set<string>();+ // Surname arm inputs: strong single-token capitalized candidates ≥3 chars.+ const surnamePatterns: string[] = [];+ const surnameTokens: string[] = []; // lower(token), parallel to patterns+ const surnameTokenToNorm = new Map<string, string>();// Reverse maps for arm-2 provenance (which candidate produced a row) —// populated in this same pass so the derivations happen exactly once.const titleToNorm = new Map<string, string>();const slugToNorm = new Map<string, string>();for (const c of candidates) {+ // Lowercase WEAK candidates (entity-salience step 2.5) may probe the+ // alias table ONLY — never the title/slug/suffix arms, where ordinary+ // lowercase words would fabricate pointers. Gated by the kill switch.+ if (c.weak) {+ if (!lexicalArms) continue;+ const wnorm = normalizeAlias(c.query);+ if (!wnorm) continue;+ if (!displayByNorm.has(wnorm)) displayByNorm.set(wnorm, c.display);+ if (!weakNorms.has(wnorm)) {+ weakNorms.add(wnorm);+ aliasNorms.push(wnorm);+ }+ continue;+ }const norm = normalizeAlias(c.query);if (!norm) continue;if (!displayByNorm.has(norm)) displayByNorm.set(norm, c.display);@@ -156,6 +198,18 @@ export async function resolveEntitiesToPointers(slugSuffixes.push(`%/${s}`);if (!slugToNorm.has(s)) slugToNorm.set(s, norm);}+ // Surname arm (v0.46.15, kta-pos variant 4): a strong single capitalized+ // token ≥3 chars may be a surname-only reference ("Did Galewright ever…").+ // Escaped for LIKE (backslash is Postgres' default escape char — no+ // ESCAPE clause, which the `LIKE ANY(array)` form doesn't accept).+ if (lexicalArms && !/\s/.test(c.query) && c.query.length >= 3 && /^\p{Lu}/u.test(c.query)) {+ const tokenLc = c.query.toLowerCase();+ if (!surnameTokenToNorm.has(tokenLc)) {+ surnameTokenToNorm.set(tokenLc, norm);+ surnameTokens.push(tokenLc);+ surnamePatterns.push(`% ${escapeLikePattern(tokenLc)}`);+ }+ }}if (!aliasNorms.length) return null;@@ -188,12 +242,72 @@ export async function resolveEntitiesToPointers(const aliasResults = await Promise.allSettled(sourceIds.map((src) => engine.resolveAliases(aliasNorms, { sourceId: src })),);+ const anyAliasSourceFailed = aliasResults.some((r) => r.status !== 'fulfilled');+ // Liveness BEFORE uniqueness: page_aliases has no FK, so a norm's hit list+ // can carry rows for deleted/renamed pages. Deciding uniqueness on raw hits+ // lets a stale row veto the sole live target (hits.length becomes 2), or+ // conversely leaves a phantom looking unique. One batched live-check over+ // every hit slug; result rows carry their true (source_id, slug) so the+ // ANY(sources) × ANY(slugs) over-match cannot mis-key. If the check itself+ // fails, strong arms fall back to raw-hit uniqueness (phantom pointers are+ // still dropped by the downstream hydration) and the weak fold goes+ // fail-closed.+ const liveAliasKeys = new Set<string>();+ let liveCheckOk = false;+ {+ const hitSlugs = new Set<string>();+ for (const r of aliasResults) {+ if (r.status !== 'fulfilled') continue;+ for (const hits of r.value.values()) for (const h of hits) hitSlugs.add(h.slug);+ }+ if (hitSlugs.size) {+ try {+ const liveRows = await engine.executeRaw<{ slug: string; source_id: string }>(+ `SELECT slug, source_id FROM pages+ WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND slug = ANY($2::text[])`,+ [sourceIds, [...hitSlugs]],+ );+ for (const r of liveRows) liveAliasKeys.add(keyOf(r.source_id, r.slug));+ liveCheckOk = true;+ } catch {+ /* fall back below */+ }+ } else {+ liveCheckOk = true;+ }+ }+ const liveHitsFor = (+ r: PromiseSettledResult<Map<string, Array<{ slug: string; source_id: string }>>>,+ src: string,+ norm: string,+ ): Array<{ slug: string; source_id: string }> => {+ if (r.status !== 'fulfilled') return [];+ const hits = r.value.get(norm) ?? [];+ return liveCheckOk ? hits.filter((h) => liveAliasKeys.has(keyOf(h.source_id || src, h.slug))) : hits;+ };for (let i = 0; i < sourceIds.length; i++) {- const r = aliasResults[i];- if (r.status !== 'fulfilled') continue;for (const norm of aliasNorms) {- const hits = r.value.get(norm);- if (hits && hits.length === 1) push(hits[0].slug, sourceIds[i], 'alias', norm);+ if (weakNorms.has(norm)) continue; // weak norms fold below (stricter rule)+ const hits = liveHitsFor(aliasResults[i], sourceIds[i], norm);+ if (hits.length === 1) push(hits[0].slug, sourceIds[i], 'alias', norm);+ }+ }+ // Weak norms: GLOBAL uniqueness across all considered sources (v0.46.15,+ // stricter than the strong per-source rule) — a lowercase word that is a+ // registered alias in two sources injects nothing. FAIL-CLOSED on partial+ // visibility (adversarial F2): if any source's alias lookup failed, or the+ // live-check did, uniqueness cannot be decided globally — a transient DB+ // blip must not make an ambiguous alias look unique. Skip the fold; the+ // next turn retries with full visibility.+ if (weakNorms.size && !anyAliasSourceFailed && liveCheckOk) {+ for (const norm of weakNorms) {+ const all: Array<{ slug: string; source_id: string }> = [];+ for (let i = 0; i < sourceIds.length; i++) {+ for (const h of liveHitsFor(aliasResults[i], sourceIds[i], norm)) {+ all.push({ slug: h.slug, source_id: sourceIds[i] });+ }+ }+ if (all.length === 1) push(all[0].slug, all[0].source_id, 'alias', norm);}}@@ -201,17 +315,34 @@ export async function resolveEntitiesToPointers(// Example" slugifies to alice-example, but the real page is people/alice-example,// so a plain slug = ANY() misses. Match lower(title) exactly or the slug suffix.let rows: PageRow[] = [];+ const useSurnameArm = surnamePatterns.length > 0;try {- rows = await engine.executeRaw<PageRow>(- `SELECT slug, source_id, title, type, frontmatter, compiled_truth- FROM pages- WHERE deleted_at IS NULL- AND source_id = ANY($1::text[])- AND ( lower(title) = ANY($2::text[])+ // The surname predicate rides the SAME query when armed: person pages+ // whose lower(title) ends with " <token>". Patterns are pre-escaped for+ // LIKE (backslash default escape); type='person' kills the company-tail+ // class ("Labs", "Systems" as pseudo-surnames).+ rows = useSurnameArm+ ? await engine.executeRaw<PageRow>(+ `SELECT slug, source_id, title, type, frontmatter, compiled_truth+ FROM pages+ WHERE deleted_at IS NULL+ AND source_id = ANY($1::text[])+ AND ( lower(title) = ANY($2::text[])+ OR slug = ANY($3::text[])+ OR slug LIKE ANY($4::text[])+ OR (lower(title) LIKE ANY($5::text[]) AND type = 'person') )`,+ [sourceIds, titlesLc, exactSlugs, slugSuffixes, surnamePatterns],+ )+ : await engine.executeRaw<PageRow>(+ `SELECT slug, source_id, title, type, frontmatter, compiled_truth+ FROM pages+ WHERE deleted_at IS NULL+ AND source_id = ANY($1::text[])+ AND ( lower(title) = ANY($2::text[])OR slug = ANY($3::text[])OR slug LIKE ANY($4::text[]) )`,- [sourceIds, titlesLc, exactSlugs, slugSuffixes],- );+ [sourceIds, titlesLc, exactSlugs, slugSuffixes],+ );} catch {rows = [];}@@ -234,17 +365,61 @@ export async function resolveEntitiesToPointers(}// Title/slug matches that weren't alias hits, appended after alias hits.// Arm provenance per row is classified in JS (codex D8) — the combined OR- // can't report which predicate matched: an exact lower(title) hit is the- // 'title' arm; anything else got in via slug / slug-suffix.+ // can't report which predicate matched. Classification is per-(row,+ // matching-set) with exact-arm precedence (eng review): a row can+ // title-match candidate X AND surname-match candidate Y — the exact hit+ // wins. Rows matched by NO exact set fall through to the surname check.const titleSet = new Set(titlesLc);+ // token → surname-matched rows; pushed only when the token is UNAMBIGUOUS+ // (exactly one page across the considered sources — mirror of the alias+ // arm's posture; an ambiguous surname injects nothing).+ //+ // Ambiguity is counted over ALL person rows carrying the surname,+ // INDEPENDENT of which arm claims a row (adversarial F1): classification+ // precedence (title/slug win) would otherwise remove a title-claimed+ // namesake from the surname count — with "Jane Galewright" resolved by+ // title and a bare "Galewright" in the same window, the OTHER Galewright+ // would look unique and inject the wrong person. The SQL OR fetches every+ // surname-matching person row regardless of later classification, so this+ // coverage count is complete.+ const surnameCoverage = new Map<string, number>();+ if (useSurnameArm) {+ for (const r of rows) {+ if (r.type !== 'person') continue;+ const titleLc = (r.title ?? '').toLowerCase();+ const token = surnameTokens.find((t) => titleLc.endsWith(` ${t}`));+ if (token) surnameCoverage.set(token, (surnameCoverage.get(token) ?? 0) + 1);+ }+ }+ const surnameHits = new Map<string, Array<{ slug: string; source_id: string }>>();for (const r of rows) {const titleLc = (r.title ?? '').toLowerCase();if (titleSet.has(titleLc)) {push(r.slug, r.source_id, 'title', titleToNorm.get(titleLc));- } else {- // Slug arm: exact slugified-candidate match, else suffix scan.- const tail = r.slug.includes('/') ? r.slug.slice(r.slug.lastIndexOf('/') + 1) : r.slug;- push(r.slug, r.source_id, 'slug-suffix', slugToNorm.get(r.slug) ?? slugToNorm.get(tail));+ continue;+ }+ // Slug arm: exact slugified-candidate match, else suffix scan.+ const tail = r.slug.includes('/') ? r.slug.slice(r.slug.lastIndexOf('/') + 1) : r.slug;+ const slugNorm = slugToNorm.get(r.slug) ?? slugToNorm.get(tail);+ if (slugNorm !== undefined) {+ push(r.slug, r.source_id, 'slug-suffix', slugNorm);+ continue;+ }+ // Surname arm (v0.46.15): this row got in via the surname predicate only.+ if (useSurnameArm && r.type === 'person') {+ const token = surnameTokens.find((t) => titleLc.endsWith(` ${t}`));+ if (token) {+ const list = surnameHits.get(token) ?? [];+ list.push({ slug: r.slug, source_id: r.source_id });+ surnameHits.set(token, list);+ }+ }+ }+ for (const [token, hits] of surnameHits) {+ // hits counts rows the surname arm alone claimed; coverage counts every+ // holder including title/slug-claimed namesakes. Both must be 1.+ if (hits.length === 1 && (surnameCoverage.get(token) ?? 0) === 1) {+ push(hits[0].slug, hits[0].source_id, 'title-surname', surnameTokenToNorm.get(token));}}diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex a6616c20e4..823957ae59 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -128,6 +128,8 @@ export interface AssembleTurnContextOpts {/** Opaque session identity — keys the hot-memory cache (CX2-11). */sessionId?: string;maxBytes?: number;+ /** v0.46.15: lexical-arms kill switch — see ResolvePointersOpts.lexicalArms. */+ lexicalArms?: boolean;// ── v0.45.7 ambient recall ──────────────────────────────────────────────/** Assembly mode. Default 'turn' (existing behavior). */mode?: ContextMode;@@ -204,6 +206,7 @@ export async function assembleTurnContext(priorContextText: opts.priorContextText,suppression: 'slug-only',maxPointers: DEFAULT_MAX_POINTERS,+ lexicalArms: opts.lexicalArms,});pointers = block?.pointers ?? [];}@@ -222,6 +225,9 @@ export async function assembleTurnContext(priorContext: opts.priorContextText,excludeSlugs,maxPages: MAX_VOLUNTEERED_PAGES,+ // v0.46.15+ lexical-arms kill switch rides the same threading as the+ // pointer arm above (ResolvePointersOpts.lexicalArms).+ lexicalArms: opts.lexicalArms,});}} catch {diff --git a/src/core/context/volunteer.ts b/src/core/context/volunteer.tsindex 64a31c466c..fee658394d 100644--- a/src/core/context/volunteer.ts+++ b/src/core/context/volunteer.ts@@ -69,6 +69,8 @@ export interface VolunteerOpts {excludeSlugs?: ReadonlySet<string>;maxPages?: number;minConfidence?: number;+ /** v0.46.15: lexical-arms kill switch — see ResolvePointersOpts.lexicalArms. */+ lexicalArms?: boolean;}/** Shared wire protocol for window turns — watch.ts imports this so the two@@ -113,6 +115,7 @@ function rationaleFor(arm: ResolveArm, display: string, c: WindowEntityCandidateconst armText =arm === 'alias' ? `alias match "${display}"`: arm === 'title' ? `exact title match "${display}"`+ : arm === 'title-surname' ? `surname match "${display}"`: `slug match "${display}"`;if (!c) return armText;const parts = [armText];@@ -204,6 +207,7 @@ export async function volunteerContext(priorContextText: opts.priorContext,suppression: 'slug-only',maxPointers: VOLUNTEER_MAX_PAGES_CAP * 2,+ lexicalArms: opts.lexicalArms,});if (!block) return [];diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex 7305b21b81..288b458f8d 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -22,6 +22,8 @@*/import type { BrainEngine } from '../engine.ts';+import { normalizeAlias } from '../search/alias-normalize.ts';+import { isUndefinedTableError } from '../utils.ts';/*** Canonicalize a free-form entity reference to a page slug.@@ -55,6 +57,13 @@ export async function resolveEntitySlug(if (exact) return exact;}+ // 1.5. Alias-exact (v0.46.15 identity wave, #3730): an unambiguous+ // page_aliases hit resolves BEFORE prefix expansion / fuzzy — the+ // alias table is curated ground truth ("saoirse" → people/saoirse-x)+ // while fuzzy is a guess. Live-page verified (page_aliases has no FK).+ const aliased = await tryAliasExact(engine, source_id, trimmed);+ if (aliased) return aliased;+// 2. Prefix-expansion match: when the input looks like a bare first name// (no slash, no prefix, slugifies to a single short token), try// `people/<token>-%` then `companies/<token>-%`. Short bare names@@ -92,6 +101,38 @@ function fallbackSlugify(trimmed: string): string {return slugify(trimmed);}+/**+ * Alias-exact arm (v0.46.15, #3730): unambiguous single-slug page_aliases hit,+ * verified against LIVE pages — page_aliases has no FK to pages, so stale+ * alias rows for deleted/renamed pages linger (outside-voice R2-8).+ * Liveness is filtered BEFORE uniqueness (codex ship-review): a stale sibling+ * row must not veto the sole live target — that fall-through would land on+ * fuzzy/slugify and could recreate a phantom slug on a WRITE path.+ * Fail-open on undefined-table (pre-v110 brains have no page_aliases table);+ * other errors warn once per process so degradation isn't silent.+ */+let aliasExactWarned = false;+async function tryAliasExact(engine: BrainEngine, source_id: string, raw: string): Promise<string | null> {+ const norm = normalizeAlias(raw);+ if (!norm) return null;+ try {+ const hits = (await engine.resolveAliases([norm], { sourceId: source_id })).get(norm) ?? [];+ if (!hits.length) return null;+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[])`,+ [source_id, [...new Set(hits.map((h) => h.slug))]],+ );+ const live = [...new Set(rows.map((r) => r.slug))];+ return live.length === 1 ? live[0] : null;+ } catch (err) {+ if (!isUndefinedTableError(err) && !aliasExactWarned) {+ aliasExactWarned = true;+ console.error(`[gbrain] alias-exact resolution degraded (falling through to fuzzy): ${err instanceof Error ? err.message : String(err)}`);+ }+ return null;+ }+}+/*** "Bare name" detector — true when the input is a single word with no* slash, no embedded prefix marker, and slugifies to a non-empty token.@@ -126,7 +167,7 @@ const PREFIX_EXPANSION_DIRS = ['people', 'companies'] as const;* The original `resolveEntitySlug` keeps its existing contract (returns* just the slug) for all pre-v0.40 call sites — no caller-side churn.*/-export type ResolutionSource = 'exact_page' | 'fuzzy_match' | 'fallback_slugify';+export type ResolutionSource = 'exact_page' | 'alias_exact' | 'fuzzy_match' | 'fallback_slugify';export interface ResolveResult {slug: string;@@ -148,6 +189,9 @@ export async function resolveEntitySlugWithSource(if (exact) return { slug: exact, source: 'exact_page' };}+ const aliased = await tryAliasExact(engine, source_id, trimmed);+ if (aliased) return { slug: aliased, source: 'alias_exact' };+if (isBareName(trimmed)) {const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, slugify(trimmed));if (expanded) return { slug: expanded, source: 'fuzzy_match' };diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex 2dcbac8cfa..73e95dee90 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -77,11 +77,16 @@ const volunteer_context: Operation = {);}const turns = parseWindow(p.window);+ const { loadConfig: loadCfgForArms } = await import('../config.ts');+ const { lexicalArmsEnabled } = await import('../context/reflex.ts');const pages = await volunteerContext(ctx.engine, turns, {sourceIds,priorContext: typeof p.prior_context === 'string' ? p.prior_context : undefined,maxPages: typeof p.max_pages === 'number' ? p.max_pages : undefined,minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,+ // v0.46.15+ kill switch for the lexical recall arms (weak-alias ++ // surname) — file-plane gate, threaded per ResolvePointersOpts.+ lexicalArms: lexicalArmsEnabled(loadCfgForArms()),});// Feedback-loop logging: fire-and-forget batched INSERT through thediff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 27438b5fa4..ffe59c05cd 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -43,7 +43,7 @@ import {} from './chronicle/ontology.ts';import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';import { runMigrations } from './migrate.ts';-import { hnswEfSearchFor } from './vector-index.ts';+import { hnswEfSearchFor, hnswIndexExpected, HNSW_EF_SEARCH_MAX } from './vector-index.ts';import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { DELETE_BATCH_SIZE } from './engine-constants.ts';@@ -2567,9 +2567,22 @@ export class PGLiteEngine implements BrainEngine {const sourceFactorCaseOnSlug = buildSourceFactorCase('slug', boostMap, opts?.detail, 'unverified_stub');const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- const innerLimit = offset + Math.max(limit * 5, 100);+ // v0.46.15 (retrieval-cathedral P1): bounded escalation — see+ // postgres-engine.ts searchVector for the full rationale; the logic here+ // is IDENTICAL (engine-parity pinned). Cap policy (R2-10 + codex ship+ // review): the ef_search ceiling applies only to HNSW-backed columns;+ // above-ceiling columns fall back to exact scans where capping the SQL+ // LIMIT would make offset >= 1000 permanently empty — those stay bounded+ // by the escalation count instead. (Hoisted resolvedColEarly: same+ // descriptor the cast fragment uses below.)+ const resolvedColEarly = normalizeEngineColumn(opts?.embeddingColumn);+ const innerCap = hnswIndexExpected(resolvedColEarly.type, resolvedColEarly.dimensions)+ ? HNSW_EF_SEARCH_MAX+ : Number.MAX_SAFE_INTEGER;+ const innerLimit = Math.min(offset + Math.max(limit * 5, 100), innerCap);const params: unknown[] = [vecStr, innerLimit, limit, offset];+ const innerLimitIdx = 1; // mutated by the escalation looplet extraFilter = '';if (opts?.language) {params.push(opts.language);@@ -2619,7 +2632,7 @@ export class PGLiteEngine implements BrainEngine {// v0.36 Phase 3: 'embedding_multimodal' is the unified column populated// by `gbrain reindex --multimodal`. No modality filter — the column// itself is the discriminator (only re-embedded rows have non-NULL).- const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);+ const resolvedCol = resolvedColEarly;const { col, castSql } = buildVectorCastFragment(resolvedCol);let modalityFilter: string;if (resolvedCol.name === 'embedding_image') {@@ -2634,8 +2647,8 @@ export class PGLiteEngine implements BrainEngine {// 40), so LIMIT $2 past 40 was silently unreachable — see hnswEfSearchFor.// SET LOCAL semantics need a transaction (PGLite autocommits bare// queries); scoping it locally keeps the engine's single session clean.- const { rows } = await this.db.transaction(async (tx) => {- await tx.query(`SELECT set_config('hnsw.ef_search', $1, true)`, [String(hnswEfSearchFor(innerLimit))]);+ const runOnce = async (il: number) => (await this.db.transaction(async (tx) => {+ await tx.query(`SELECT set_config('hnsw.ef_search', $1, true)`, [String(hnswEfSearchFor(il))]);return tx.query(`WITH hnsw_candidates AS (SELECT@@ -2673,7 +2686,8 @@ export class PGLiteEngine implements BrainEngine {bpp.score,CASE WHEN bpp.updated_at < (SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = bpp.page_id- ) THEN true ELSE false END AS stale+ ) THEN true ELSE false END AS stale,+ (SELECT count(*) FROM hnsw_candidates)::int AS candidate_poolFROM best_per_page bpp-- v0.41.13: stable tiebreaker. When two chunks share a score (same-- source-prefix boost + same cosine distance, the basis-vector + same-@@ -2686,7 +2700,33 @@ export class PGLiteEngine implements BrainEngine {OFFSET $4`,params);- });+ })).rows;++ // v0.46.15 bounded escalation loop — IDENTICAL logic to postgres-engine+ // (parity-pinned): retry ×4 up to 3 times while the PAGE set is short+ // but the pre-collapse candidate pool was full; a short page with a+ // non-full pool is a genuine final page. Zero rows with offset>0+ // escalates (deep pagination) but never emits — pool unknowable there.+ let escalations = 0;+ let rows = await runOnce(innerLimit);+ for (;;) {+ const il = params[innerLimitIdx] as number;+ if (rows.length >= limit) break;+ const pool = rows.length > 0+ ? Number((rows[0] as { candidate_pool?: number }).candidate_pool ?? 0)+ : null;+ const shouldEscalate = pool !== null ? pool >= il : offset > 0;+ if (!shouldEscalate) break;+ if (il >= innerCap || escalations >= 3) {+ if (pool !== null && pool >= il) {+ opts?.onVectorPoolMeta?.({ underfilled: true, escalations, innerLimit: il });+ }+ break;+ }+ params[innerLimitIdx] = Math.min(il * 4, innerCap);+ escalations++;+ rows = await runOnce(params[innerLimitIdx] as number);+ }return (rows as Record<string, unknown>[]).map(rowToSearchResult);}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex d44fce9f0f..5bd42be2a9 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -43,7 +43,7 @@ import { sanitizeForJsonb, buildLinkRows, buildTimelineRows } from './batch-rowsimport { runMigrations } from './migrate.ts';import { SCHEMA_SQL } from './schema-embedded.ts';import { verifySchema } from './schema-verify.ts';-import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, hnswEfSearchFor } from './vector-index.ts';+import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, hnswEfSearchFor, hnswIndexExpected, HNSW_EF_SEARCH_MAX } from './vector-index.ts';import {normalizeEngineColumn,buildVectorCastFragment,@@ -2333,7 +2333,29 @@ export class PostgresEngine implements BrainEngine {const sourceFactorCaseOnSlug = buildSourceFactorCase('slug', boostMap, opts?.detail, 'unverified_stub');const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- const innerLimit = offset + Math.max(limit * 5, 100);+ // v0.36 (D11): column routing via resolved descriptor. Engine doesn't+ // read config — caller (hybrid/op) resolved it and passed it in.+ // normalizeEngineColumn accepts the legacy union (string literals,+ // ResolvedColumn, undefined) and produces a canonical descriptor.+ // (Hoisted above innerLimit so the escalation cap can key off the+ // column's index eligibility.)+ const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);+ // v0.46.15 (retrieval-cathedral P1): innerLimit counts CHUNKS before the+ // best-per-page DISTINCT collapse — one dense page (150+ chunks near the+ // query) could consume the whole pool and underfill the PAGE result. The+ // execution below runs a bounded escalation loop (×4, ≤3 times) when the+ // page set comes back short while the candidate pool was FULL (more+ // candidates existed). Cap policy (outside-voice R2-10 + codex ship+ // review): for HNSW-backed columns the scan returns at most ef_search+ // rows and the GUC ceilings at 1000, so inner limits beyond that are+ // fictitious. Columns ABOVE the index dim ceiling (e.g. vector >2000d)+ // fall back to exact scans where ef_search is irrelevant — capping their+ // SQL LIMIT would make offset >= 1000 permanently empty; they stay+ // bounded by the escalation count instead.+ const innerCap = hnswIndexExpected(resolvedCol.type, resolvedCol.dimensions)+ ? HNSW_EF_SEARCH_MAX+ : Number.MAX_SAFE_INTEGER;+ const innerLimit = Math.min(offset + Math.max(limit * 5, 100), innerCap);const params: unknown[] = [vecStr];let typeClause = '';@@ -2388,6 +2410,7 @@ export class PostgresEngine implements BrainEngine {sourceClause = `AND p.source_id = $${params.length}`;}params.push(innerLimit);+ const innerLimitIdx = params.length - 1; // mutated by the escalation loopconst innerLimitParam = `$${params.length}`;params.push(limit);const limitParam = `$${params.length}`;@@ -2400,16 +2423,10 @@ export class PostgresEngine implements BrainEngine {// wasting candidate slots on hidden rows.const visibilityClause = buildVisibilityClause('p', 's');- // v0.36 (D11): column routing via resolved descriptor. Engine doesn't- // read config — caller (hybrid/op) resolved it and passed it in.- // normalizeEngineColumn accepts the legacy union (string literals,- // ResolvedColumn, undefined) and produces a canonical descriptor.- //// v0.36 Phase 3: 'embedding_multimodal' is the unified column populated// by `gbrain reindex --multimodal`. Carries BOTH text and image content// in Voyage multimodal-3 space — no modality filter; the column itself// is the discriminator (rows without embedding_multimodal aren't searched).- const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);const { col, castSql } = buildVectorCastFragment(resolvedCol);let modalityFilter: string;if (resolvedCol.name === 'embedding_image') {@@ -2467,7 +2484,8 @@ export class PostgresEngine implements BrainEngine {message_id, thread_id, source_subject,chunk_id, chunk_index, chunk_text, chunk_source,score,- false AS stale+ false AS stale,+ (SELECT count(*) FROM hnsw_candidates)::int AS candidate_poolFROM best_per_page-- v0.41.13: stable tiebreaker for tied scores. See pglite-engine for-- rationale (basis-vector test fixtures, planner-dependent ordering).@@ -2484,11 +2502,37 @@ export class PostgresEngine implements BrainEngine {// 40), so the inner CTE's LIMIT past 40 was silently unreachable — see// hnswEfSearchFor. Transaction-local (is_local=true); non-HNSW plans// (seq scan, or corpora without the index) ignore the GUC.- const rows = await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {- await tx`SET LOCAL statement_timeout = '8s'`;- await tx`SELECT set_config('hnsw.ef_search', ${String(hnswEfSearchFor(innerLimit))}, true)`;- return await tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]);- }, { alwaysTransaction: true });+ //+ // v0.46.15 bounded escalation (identical logic in pglite-engine —+ // engine-parity pinned): retry ×4 up to 3 times while the PAGE set is+ // short but the pre-collapse candidate pool was FULL. A short page with+ // a non-full pool is a genuine final page (corpus/filter exhausted) —+ // no retry, no event. Zero rows with offset>0 escalates (deep+ // pagination) but never emits: pool state is unknowable there.+ const runOnce = async (il: number) =>+ await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {+ await tx`SET LOCAL statement_timeout = '8s'`;+ await tx`SELECT set_config('hnsw.ef_search', ${String(hnswEfSearchFor(il))}, true)`;+ return await tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]);+ }, { alwaysTransaction: true });+ let escalations = 0;+ let rows = await runOnce(innerLimit);+ for (;;) {+ const il = params[innerLimitIdx] as number;+ if (rows.length >= limit) break;+ const pool = rows.length > 0 ? Number((rows[0] as { candidate_pool?: number }).candidate_pool ?? 0) : null;+ const shouldEscalate = pool !== null ? pool >= il : offset > 0;+ if (!shouldEscalate) break;+ if (il >= innerCap || escalations >= 3) {+ if (pool !== null && pool >= il) {+ opts?.onVectorPoolMeta?.({ underfilled: true, escalations, innerLimit: il });+ }+ break;+ }+ params[innerLimitIdx] = Math.min(il * 4, innerCap);+ escalations++;+ rows = await runOnce(params[innerLimitIdx] as number);+ }return rows.map(rowToSearchResult);}diff --git a/src/core/search/autocut.ts b/src/core/search/autocut.tsindex 2cd84fe35c..14edfe0b8d 100644--- a/src/core/search/autocut.ts+++ b/src/core/search/autocut.ts@@ -33,6 +33,19 @@ export interface AutocutConfig {jumpRatio: number;/** Failsafe: never return fewer than this when candidates exist (≥1). */minKeep: number;+ /**+ * v0.46.15 (#1863) — weak-top floor. When the TOP rerank score is below this+ * absolute value, the whole list is low-confidence and gap normalization is+ * meaningless (a 0.317 top makes ordinary decay look like a confident+ * cliff → spurious 1-result collapse on rare cross-source queries). Below+ * the floor autocut no-ops and the full cluster survives.+ *+ * SCALE CAVEAT: 0.35 is calibrated for the current default reranker's+ * relevance scale. The September reranker default flip (zerank-2 →+ * voyage rerank-2.5) MUST re-tune this knob — see the v0.47 removal+ * checklist. Config: `search.autocut_min_top`.+ */+ minTopScore: number;}/**@@ -44,6 +57,7 @@ export const DEFAULT_AUTOCUT: AutocutConfig = Object.freeze({enabled: true,jumpRatio: 0.2,minKeep: 1,+ minTopScore: 0.35,});export interface AutocutDecision {@@ -79,6 +93,10 @@ export function autocutFromConfig(typeof search.autocut_min_keep === 'number' ? Math.floor(search.autocut_min_keep) : Number.NaN;if (Number.isFinite(n) && n >= 1) out.minKeep = n;}+ if (search.autocut_min_top !== undefined) {+ const n = typeof search.autocut_min_top === 'number' ? search.autocut_min_top : Number.NaN;+ if (Number.isFinite(n) && n >= 0 && n <= 1) out.minTopScore = n;+ }return out;}@@ -159,6 +177,9 @@ export function applyAutocut<T>(const top = Math.max(...scores);if (!Number.isFinite(top) || top <= 0) return noOp(results);+ // v0.46.15 (#1863): a weak top means the whole list is low-confidence — gap+ // normalization by a weak top manufactures spurious cliffs. Never collapse.+ if (top < cfg.minTopScore) return noOp(results);// Sort a copy descending (A2: don't trust upstream order) and normalize.const sorted = [...scores].sort((a, b) => b - a);diff --git a/src/core/search/dedup.ts b/src/core/search/dedup.tsindex 4688107343..3ee76e124a 100644--- a/src/core/search/dedup.ts+++ b/src/core/search/dedup.ts@@ -93,18 +93,28 @@ function dedupBySource(results: SearchResult[]): SearchResult[] {}/**- * Layer 2: Remove chunks that are too similar to already-kept results.- * Uses Jaccard similarity on word sets as a proxy for cosine similarity.+ * Layer 2: Remove chunks that are too similar to already-kept results+ * FROM THE SAME PAGE. Uses Jaccard similarity on word sets as a proxy for+ * cosine similarity.+ *+ * v0.46.15 (#3983): the comparison is scoped to the same pageKey. The+ * unscoped version dropped a chunk because a DIFFERENT page's chunk was+ * textually similar — on near-duplicate-record corpora (many similar deal+ * memos, weekly reports, boilerplate-heavy notes) that silently deleted+ * whole PAGES from the result set. Distinct pages are distinct answers;+ * only intra-page near-dups are redundant.*/function dedupByTextSimilarity(results: SearchResult[], threshold: number): SearchResult[] {const kept: SearchResult[] = [];+ const keptWordsByPage = new Map<string, Set<string>[]>();for (const r of results) {const rWords = new Set(r.chunk_text.toLowerCase().split(/\s+/));+ const k = pageKey(r);+ const samePageKept = keptWordsByPage.get(k) ?? [];let tooSimilar = false;- for (const k of kept) {- const kWords = new Set(k.chunk_text.toLowerCase().split(/\s+/));+ for (const kWords of samePageKept) {const intersection = new Set([...rWords].filter(w => kWords.has(w)));const union = new Set([...rWords, ...kWords]);const jaccard = intersection.size / union.size;@@ -117,6 +127,8 @@ function dedupByTextSimilarity(results: SearchResult[], threshold: number): Searif (!tooSimilar) {kept.push(r);+ samePageKept.push(rWords);+ keptWordsByPage.set(k, samePageKept);}}diff --git a/src/core/search/evidence.ts b/src/core/search/evidence.tsindex 2792737452..c636ff946c 100644--- a/src/core/search/evidence.ts+++ b/src/core/search/evidence.ts@@ -37,16 +37,41 @@ export type Evidence =export type CreateSafety = 'exists' | 'probable' | 'unknown';-/** base_score (pre-boost) at/above this is a confident vector/keyword match. */+/**+ * Legacy pre-v0.46.15 floor — kept exported for back-compat, but+ * `high_vector_match` no longer keys off it: base_score is a blended+ * RRF/keyword/title/alias composite, NOT a cosine, so a generic+ * high-scoring page could read as a confident vector match (#3963,+ * TODOS retrieval-cathedral P1).+ */export const HIGH_MATCH_FLOOR = 0.85;/** base_score at/above this is a solid (not weak) match. */export const SOLID_MATCH_FLOOR = 0.6;+/**+ * v0.46.15 — `high_vector_match` fires ONLY on a real query↔chunk cosine at/+ * above this floor (SearchResult.cosine, hydrated from the active embedding+ * column). Config-overridable via `search.evidence_cosine_floor`; the default+ * is calibrated for the current default embedding columns — per-model+ * calibration is a filed follow-up. Keyless/hermetic runs have no cosine and+ * honestly fall through to keyword_exact/weak_semantic (create_safety+ * degrades exists→probable, the safe direction for the don't-duplicate+ * contract).+ */+export const DEFAULT_HIGH_COSINE_FLOOR = 0.8;-export function classifyEvidence(r: SearchResult): Evidence {+export interface EvidenceOpts {+ /** Cosine floor for high_vector_match (default DEFAULT_HIGH_COSINE_FLOOR). */+ cosineFloor?: number;+}++export function classifyEvidence(r: SearchResult, opts: EvidenceOpts = {}): Evidence {if (r.alias_hit) return 'alias_hit';if (r.title_match_boost && r.title_match_boost > 1.0) return 'exact_title_match';+ const floor = typeof opts.cosineFloor === 'number' ? opts.cosineFloor : DEFAULT_HIGH_COSINE_FLOOR;+ if (typeof r.cosine === 'number' && Number.isFinite(r.cosine) && r.cosine >= floor) {+ return 'high_vector_match';+ }const base = typeof r.base_score === 'number' ? r.base_score : r.score;- if (Number.isFinite(base) && base >= HIGH_MATCH_FLOOR) return 'high_vector_match';if (Number.isFinite(base) && base >= SOLID_MATCH_FLOOR) return 'keyword_exact';return 'weak_semantic';}@@ -69,9 +94,9 @@ export function createSafetyFor(evidence: Evidence): CreateSafety {* the end of the hybrid pipeline (after the alias hop, before slice) so the* agent-facing result carries the contract. Idempotent.*/-export function stampEvidence(results: SearchResult[]): void {+export function stampEvidence(results: SearchResult[], opts: EvidenceOpts = {}): void {for (const r of results) {- const e = classifyEvidence(r);+ const e = classifyEvidence(r, opts);r.evidence = e;r.create_safety = createSafetyFor(e);}diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.tsindex 41e3181680..488ac39339 100644--- a/src/core/search/explain-formatter.ts+++ b/src/core/search/explain-formatter.ts@@ -48,6 +48,11 @@ export function formatResultExplain(// final score and label "no boosts applied" downstream.const base = result.base_score ?? result.score;lines.push(` base=${fmt(base)} (rrf+cosine)`);+ // v0.46.15: raw query↔chunk cosine (the calibrated semantic signal evidence+ // keys off). Absent on keyword-only / no-embedding paths.+ if (typeof result.cosine === 'number') {+ lines.push(` cosine=${fmt(result.cosine)} (raw query↔chunk similarity)`);+ }let anyBoost = false;diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex ca7c793d3f..01b54538a2 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -1096,7 +1096,18 @@ export async function hybridSearch(// Direct searchKeyword consumers (countMentions, link-extraction, eval)// do NOT set this and keep the strict-AND contract.orFallback: true,+ // v0.46.15: collect searchVector's bounded-escalation exhaustion signal —+ // engines have no telemetry sink (R2-10); hybrid owns the meta emit.+ // ACCUMULATES across vector calls (adversarial F8): expansion runs N+ // sub-queries through this one opts object — last-write-wins would+ // under-report multi-query exhaustion. Keep the max-escalations event.+ onVectorPoolMeta: (m) => {+ if (!vectorPoolUnderfill || m.escalations >= vectorPoolUnderfill.escalations) {+ vectorPoolUnderfill = { escalations: m.escalations, innerLimit: m.innerLimit };+ }+ },};+ let vectorPoolUnderfill: { escalations: number; innerLimit: number } | undefined;// Track what actually ran for the optional onMeta callback (v0.25.0).// Caller leaves onMeta undefined → these flags are computed but never// surfaced. Capture wrapper passes a closure to receive the meta and@@ -1309,7 +1320,7 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,});- stampEvidence(noEmbedHopped);+ stampEvidence(noEmbedHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });const noEmbedSliced = noEmbedHopped.slice(offset, offset + limit);// v0.32.3 search-lite: budget enforcement on the no-embedding-provider path.const { results: noEmbedBudgeted, meta: noEmbedBudgetMeta } = enforceTokenBudget(noEmbedSliced, resolvedMode.tokenBudget);@@ -1658,7 +1669,7 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,});- stampEvidence(kwHopped);+ stampEvidence(kwHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });const kwSliced = kwHopped.slice(offset, offset + limit);// v0.32.3 search-lite: budget enforcement on the keyword-fallback path too.const { results: kwBudgeted, meta: kwBudgetMeta } = enforceTokenBudget(kwSliced, resolvedMode.tokenBudget);@@ -1858,7 +1869,7 @@ export async function hybridSearch(// decision keys off WHY a page matched, not a raw blended score. Stamp on// the full alias-hopped set before any adaptive trim so the kept results// carry evidence regardless of where the cap lands.- stampEvidence(aliasHopped);+ stampEvidence(aliasHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });// v0.42 — intent-aware adaptive return-sizing (opt-in, default off). Trim// the ranked candidate set to an intent-driven cap BEFORE the limit slice,@@ -1873,7 +1884,12 @@ export async function hybridSearch(let returnPool = aliasHopped;let adaptiveDecision: AdaptiveReturnDecision | undefined;if (adaptiveCfg.enabled && offset === 0) {- const r = applyAdaptiveReturn(aliasHopped, suggestions.intent, adaptiveCfg);+ // v0.46.15: 'concept' maps to the recall-preserving 'general' cap for+ // adaptive return — the narrower AdaptiveQueryIntent union predates the+ // concept intent, and concept queries are exactly the ones that want+ // breadth (widening the union is the adaptive-ablation wave's call).+ const adaptiveIntent = suggestions.intent === 'concept' ? 'general' : suggestions.intent;+ const r = applyAdaptiveReturn(aliasHopped, adaptiveIntent, adaptiveCfg);returnPool = r.kept;adaptiveDecision = r.decision;}@@ -1894,7 +1910,9 @@ export async function hybridSearch(const r = applyAutocut(returnPool,(x) => x.rerank_score,- { enabled: true, jumpRatio: resolvedMode.autocut_jump, minKeep: 1 },+ // v0.46.15 (#1863): minTopScore is the weak-top floor — below it the+ // cliff signal is untrustworthy and autocut no-ops.+ { enabled: true, jumpRatio: resolvedMode.autocut_jump, minKeep: 1, minTopScore: resolvedMode.autocut_min_top },// Preserve alias-hop exact matches: 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).@@ -1926,6 +1944,7 @@ export async function hybridSearch(...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0? { token_budget: budgetMeta }: {}),+ ...(vectorPoolUnderfill ? { vector_pool_underfilled: vectorPoolUnderfill } : {}),...(adaptiveDecision ? { adaptive_return: adaptiveDecision } : {}),...(autocutDecision ? { autocut: autocutDecision } : {}),});@@ -2463,7 +2482,9 @@ async function cosineReScore(console.error(`[search-debug] ${r.slug}:${r.chunk_id} cosine=${cosine.toFixed(4)} norm_rrf=${normRrf.toFixed(4)} blended=${blended.toFixed(4)}`);}- return { ...r, score: blended };+ // v0.46.15: stamp the raw cosine — evidence + --explain read it (the+ // hydration map is already paid for; zero extra probes).+ return { ...r, score: blended, cosine };}).sort((a, b) => b.score - a.score);}diff --git a/src/core/search/intent-weights.ts b/src/core/search/intent-weights.tsindex 182a4ac5ff..4944168fad 100644--- a/src/core/search/intent-weights.ts+++ b/src/core/search/intent-weights.ts@@ -87,6 +87,17 @@ const INTENT_WEIGHTS: Record<QueryIntent, IntentWeights> = {suggestedRecency: 'on',exactMatchBoost: 1.10,},+ concept: {+ // v0.46.15 (Cat 13): definitional/landscape paraphrases — the user asks+ // what an IDEA means, in their own words. The vector arm wins here; the+ // entity keyword tilt made hybrid LOSE to its own vector component+ // (47.0 vs 49.1 nDCG@5 on 500 paraphrase probes). Inverse of the+ // entity tilt; no exact-match boost (paraphrases don't exact-match).+ keywordWeight: 0.9,+ vectorWeight: 1.2,+ suggestedRecency: null,+ exactMatchBoost: 1.0,+ },general: DEFAULT_WEIGHTS,};diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 6dfd0fc909..c0718492b2 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -156,6 +156,15 @@ export interface ModeBundle {*/title_boost: number | undefined;+ /**+ * v0.46.15 — cosine floor for evidence's `high_vector_match` (see+ * evidence.ts DEFAULT_HIGH_COSINE_FLOOR). Config `search.evidence_cosine_floor`.+ * Deliberately EXCLUDED from knobsHash: it shapes the evidence LABEL, not+ * the result set — a floor change serves TTL-bounded stale labels on cached+ * rows, which is acceptable for an operator tuning knob.+ */+ evidence_cosine_floor: number | undefined;+// v0.36 cross-modal wave knobs (D2 + D3 + D6 + D8 + D13 + LLM-intent).// All three mode bundles default these to the same values — cross-modal// is opt-in per-call (D6 weighting), opt-in per-brain (D8 unified flags),@@ -267,6 +276,13 @@ export interface ModeBundle {* run. Override: `search.autocut_jump` config → mode bundle.*/autocut_jump: number;+ /**+ * v0.46.15 (#1863) — weak-top floor: when the TOP rerank score is below+ * this, autocut no-ops (gap normalization by a weak top manufactures+ * spurious cliffs). Scale-dependent on the reranker — the September+ * reranker default flip must re-tune it. Config: `search.autocut_min_top`.+ */+ autocut_min_top: number;/*** v0.43 — relational recall arm. When on, a relational query ("who invested* in widget-co", "what connects fund-a and fund-b") resolves its seed@@ -309,6 +325,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =floor_ratio: undefined,// T2 — title-phrase boost ON by default (correctness fix, cheap + gated).title_boost: 1.25,+ evidence_cosine_floor: 0.8,// v0.36 cross-modal defaults (same across all modes — opt-in)cross_modal_both_text_weight: 0.6,cross_modal_both_image_weight: 0.4,@@ -332,6 +349,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =relationalRetrieval: false,relational_retrieval_depth: 2,autocut_jump: 0.2,+ autocut_min_top: 0.35,}),balanced: Object.freeze({cache_enabled: true,@@ -363,6 +381,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =floor_ratio: undefined,// T2 — title-phrase boost ON by default (correctness fix, cheap + gated).title_boost: 1.25,+ evidence_cosine_floor: 0.8,// v0.36 cross-modal defaults (same across all modes — opt-in)cross_modal_both_text_weight: 0.6,cross_modal_both_image_weight: 0.4,@@ -390,6 +409,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =relationalRetrieval: true,relational_retrieval_depth: 2,autocut_jump: 0.2,+ autocut_min_top: 0.35,}),tokenmax: Object.freeze({cache_enabled: true,@@ -418,6 +438,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =floor_ratio: undefined,// T2 — title-phrase boost ON by default (correctness fix, cheap + gated).title_boost: 1.25,+ evidence_cosine_floor: 0.8,// v0.36 cross-modal defaults (same across all modes — opt-in)cross_modal_both_text_weight: 0.6,cross_modal_both_image_weight: 0.4,@@ -441,6 +462,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =relationalRetrieval: true,relational_retrieval_depth: 2,autocut_jump: 0.2,+ autocut_min_top: 0.35,}),});@@ -476,6 +498,8 @@ export interface SearchKeyOverrides {floor_ratio?: number;// T2 — title-phrase boost override.title_boost?: number;+ // v0.46.15 — evidence cosine-floor override (label-only; not in knobsHash).+ evidence_cosine_floor?: number;// v0.36 cross-modal overridescross_modal_both_text_weight?: number;cross_modal_both_image_weight?: number;@@ -495,6 +519,7 @@ export interface SearchKeyOverrides {relationalRetrieval?: boolean;relational_retrieval_depth?: number;autocut_jump?: number;+ autocut_min_top?: number;}/**@@ -522,6 +547,8 @@ export interface SearchPerCallOpts {floor_ratio?: number;// T2 — title-phrase boost per-call override.title_boost?: number;+ // v0.46.15 — evidence cosine-floor per-call override.+ evidence_cosine_floor?: number;// v0.36 cross-modal per-call overridescross_modal_both_text_weight?: number;cross_modal_both_image_weight?: number;@@ -541,6 +568,7 @@ export interface SearchPerCallOpts {// numeric per-call knob threaded through the bundle.autocut?: boolean;autocut_jump?: number;+ autocut_min_top?: number;// v0.43 — relational recall per-call overrides.relationalRetrieval?: boolean;relational_retrieval_depth?: number;@@ -620,6 +648,7 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearch// v0.35.6.0 — floor-ratio resolved via the same pick chain.floor_ratio: pick('floor_ratio'),title_boost: pick('title_boost'),+ evidence_cosine_floor: pick('evidence_cosine_floor'),// v0.36 cross-modal knobscross_modal_both_text_weight: pick('cross_modal_both_text_weight'),cross_modal_both_image_weight: pick('cross_modal_both_image_weight'),@@ -636,6 +665,7 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearch// v0.42.3.0 — autocut resolved via the same pick chain.autocut: pick('autocut'),autocut_jump: pick('autocut_jump'),+ autocut_min_top: pick('autocut_min_top'),// v0.43 — relational recall resolved via the same pick chain.relationalRetrieval: pick('relationalRetrieval'),relational_retrieval_depth: pick('relational_retrieval_depth'),@@ -805,7 +835,7 @@ export function attributeKnob<K extends keyof ModeBundle>(// degraded:[{stage:'cache_prestamp'}] at hit time (belt-and-braces).// (Merge note: both this wave and master's #3515 wave claimed v=16 in// flight; the merge sequences them as 16 then 17.)-export const KNOBS_HASH_VERSION = 17;+export const KNOBS_HASH_VERSION = 18;/*** v0.36 (D8 / CDX-2) — second-arg context for the cache key. The@@ -934,6 +964,10 @@ export function knobsHash(// etc.) so a partial-knobs caller (tests passing a minimal literal) can't// crash the hash. Typed callers always carry the field.`acj=${(knobs.autocut_jump ?? 0.2).toFixed(2)}`,+ // v=18 addition (v0.46.15 #1863, append-only): weak-top floor. A floored+ // write (full cluster kept on a weak top) must not be served to an+ // unfloored lookup and vice versa — the kept set differs.+ `acm=${(knobs.autocut_min_top ?? 0.35).toFixed(2)}`,// v=10 additions (v0.43, append-only): relational recall arm. A// relational-on write (edge-seeded result set) must NOT be served to a// relational-off lookup — same contamination class as graph_signals. The@@ -1068,6 +1102,14 @@ export function loadOverridesFromConfig(if (Number.isFinite(n) && n >= 1.0 && n <= 5.0) out.title_boost = n;}+ // v0.46.15 — evidence cosine floor (label-only knob; deliberately not in+ // knobsHash). [0, 1] sanity-bounded.+ const ecf = get('search.evidence_cosine_floor');+ if (ecf !== undefined) {+ const n = parseFloat(ecf);+ if (Number.isFinite(n) && n >= 0 && n <= 1) out.evidence_cosine_floor = n;+ }+// v0.36 cross-modal overrides (D3 registry)const cmbt = get('search.cross_modal.both_mode_text_weight');if (cmbt !== undefined) {@@ -1129,6 +1171,12 @@ export function loadOverridesFromConfig(const n = parseFloat(acj);if (Number.isFinite(n) && n > 0 && n <= 1) out.autocut_jump = n;}+ // v0.46.15 (#1863) — weak-top floor. [0, 1]; 0 disables the floor.+ const acm = get('search.autocut_min_top');+ if (acm !== undefined) {+ const n = parseFloat(acm);+ if (Number.isFinite(n) && n >= 0 && n <= 1) out.autocut_min_top = n;+ }// v0.43 — relational recall arm.const rel = get('search.relational_retrieval');@@ -1162,6 +1210,7 @@ export const SEARCH_MODE_CONFIG_KEYS: ReadonlyArray<string> = Object.freeze([// v0.35.6.0 — floor-ratio gate'search.floor_ratio','search.title_boost',+ 'search.evidence_cosine_floor',// v0.36 cross-modal keys (D3)'search.cross_modal.both_mode_text_weight','search.cross_modal.both_mode_image_weight',@@ -1183,6 +1232,7 @@ export const SEARCH_MODE_CONFIG_KEYS: ReadonlyArray<string> = Object.freeze(['search.relational_retrieval','search.relational_retrieval_depth','search.autocut_jump',+ 'search.autocut_min_top',]);/**diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex dce47e9bf9..3f3403b4cf 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -31,6 +31,9 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {reranker_timeout_ms: 'HTTP timeout for the reranker call',floor_ratio: 'Floor-ratio gate for metadata boosts (0..1, undefined = off)',title_boost: 'Title-phrase boost multiplier (query is a title token-run; 1.0 = off)',+ // v0.46.15 retrieval wave knobs+ evidence_cosine_floor: 'Cosine floor for evidence high_vector_match (label-only; 0..1)',+ autocut_min_top: 'Weak-top floor — autocut no-ops when the top score is below this (0 disables)',// v0.36 cross-modal knobs (D3 registry)cross_modal_both_text_weight: "D6 'both'-mode RRF weight for text branch (0.6 default)",cross_modal_both_image_weight: "D6 'both'-mode RRF weight for image branch (0.4 default)",@@ -80,6 +83,10 @@ export async function buildModesReport(engine: BrainEngine): Promise<SearchModes// so config drift is legible. Default undefined renders as 'undefined'// in the bundle column, 'mode' source when unset by config/per-call.'floor_ratio',+ // v0.46.15 retrieval wave — evidence floor (label-only) + autocut weak-top+ // floor surfaced so config drift on the new knobs is legible.+ 'evidence_cosine_floor',+ 'autocut_min_top',];const attributions = {} as SearchModesReport['resolved'];diff --git a/src/core/search/query-intent.ts b/src/core/search/query-intent.tsindex 09831def16..028b6f7b38 100644--- a/src/core/search/query-intent.ts+++ b/src/core/search/query-intent.ts@@ -24,7 +24,7 @@* Pure module. No DB, no LLM, no async. Tested in test/query-intent.test.ts.*/-export type QueryIntent = 'entity' | 'temporal' | 'event' | 'general';+export type QueryIntent = 'entity' | 'temporal' | 'event' | 'concept' | 'general';export type SalienceMode = 'off' | 'on' | 'strong';export type RecencyMode = 'off' | 'on' | 'strong';@@ -322,6 +322,12 @@ export function classifyQueryIntent(query: string): QueryIntent {if (matches(FULL_CONTEXT_PATTERNS, query)) return 'temporal';if (matches(TEMPORAL_PATTERNS, query)) return 'temporal';if (matches(EVENT_PATTERNS, query)) return 'event';+ // v0.46.15 (Cat 13): concept BEFORE entity — definitional paraphrases+ // ("What is the ownership economy?") previously classified entity and got+ // the keyword tilt, making hybrid LOSE to its own vector arm on+ // paraphrase queries. Full-context/temporal/event keep their queries;+ // only entity/general-bound queries can re-route here.+ if (isConceptShapedQuery(query)) return 'concept';if (matches(ENTITY_PATTERNS, query)) return 'entity';return 'general';}@@ -332,6 +338,9 @@ export function intentToDetail(intent: QueryIntent): 'low' | 'medium' | 'high' |case 'entity': return 'low';case 'temporal': return 'high';case 'event': return 'high';+ // v0.46.15: concept queries keep the default detail — the vector-lean+ // weights (intent-weights.ts) are the mechanism, not source filtering.+ case 'concept': return undefined;case 'general': return undefined;}}@@ -354,7 +363,12 @@ export function autoDetectDetail(query: string): 'low' | 'medium' | 'high' | und// `query` on these would fight their descriptions):// - "who are the …" → find_experts// - bare "anything …" → get_recent_salience / find_anomalies-const CONCEPT_CUE_PATTERNS: RegExp[] = [+// v0.46.15 (Cat 13): the ONE shared concept cue bank — consumed by BOTH the+// intent classifier (ranking weights) and the CLI nudge below. Two drifting+// concept definitions was the DRY failure the outside voice flagged (R2-11).+//+// Landscape/quantifier cues: the query asks for a SET defined by meaning.+export const CONCEPT_CUE_PATTERNS: RegExp[] = [/\b(all|every)\b.+\b(that|who|which|doing|with|about|related to)\b/i,/\b(find|list|show)\s+(all|every|everything)\b/i,/\beverything\s+(about|on|matching|related)\b/i,@@ -363,6 +377,36 @@ const CONCEPT_CUE_PATTERNS: RegExp[] = [/\bwhich\s+\w+[\w\s]*\b(do|does|are|have|use|work)\b/i,];+// Definitional-paraphrase cues (v0.46.15): the query asks what an IDEA means+// — exactly where the vector arm wins and the keyword tilt hurt (Cat 13:+// hybrid 47.0 nDCG@5 vs bare vector 49.1 on paraphrase probes).+// DELIBERATELY DISJOINT from FULL_CONTEXT_PATTERNS ("everything about X",+// "all about X" stay full-context → temporal ordering unchanged).+export const CONCEPT_DEFINITIONAL_PATTERNS: RegExp[] = [+ // Lowercase MULTI-WORD subject required (adversarial ship-review F5): the+ // identity wave's own premise is that users type NAMES lowercase — "what+ // is saoirse working on" / "what do i know about galewright" must keep the+ // entity keyword tilt. Concepts in definitional paraphrases are noun+ // PHRASES ("ownership economy", "founder liquidity"); a single lowercase+ // subject word is undecidable without the alias table, so it conservatively+ // stays entity (pre-wave behavior).+ /\b[Ww]hat\s+(is|are)\s+(the\s+)?[a-z][\w'’-]*\s+[a-z]/, // "What is the ownership economy"+ /\b[Ww]hat\s+do\s+(i|you|we)\s+know\s+about\s+[a-z][\w'’-]*\s+[a-z]/, // multi-word lowercase subject+ /\b(notes|ideas|thinking|thoughts|writing)\s+(on|about)\b/i,+ /\bways\s+to\b/i,+ /\bhow\s+to\s+think\s+about\b/i,+ /\bconcept\s+of\b/i,+];++/**+ * Status-verb anti-signal for the DEFINITIONAL route only (adversarial F5):+ * "what is <name> working on / up to" asks what an entity is DOING, not what+ * a concept IS — the definitional cue is a false match there. Applies only+ * in isConceptShapedQuery (the ranking route); the CLI nudge's vocabulary is+ * deliberately untouched.+ */+const CONCEPT_STATUS_ANTI_RE = /\b(working on|up to|doing|saying|talking about|focused on|meeting with)\b/i;+// Exact-identifier anti-signals: the query names a specific thing, so the// cheap `search` op is the right tool and a nudge would be noise.const CONCEPT_ANTI_PATTERNS: RegExp[] = [@@ -371,11 +415,54 @@ const CONCEPT_ANTI_PATTERNS: RegExp[] = [];/**- * True when a query is concept-shaped: it carries a fuzzy-quantifier or- * landscape cue AND no exact-identifier anti-signal. Tuned to favor- * false-negatives (silence) over false-positives (noise): short queries,- * quoted phrases, slugs, and entity lookups (per classifyQueryIntent)- * never trigger. Pure function; no LLM, no DB.+ * v1-conservative proper-noun anti-signal (v0.46.15): any capitalized token+ * that is NOT sentence-initial is treated as evidence the query names a+ * specific entity — the entity keyword tilt is correct there, not the+ * concept vector lean. Sentence-initial capitalization alone never blocks.+ */+function hasMidSentenceCapital(q: string): boolean {+ const re = /\s(\p{Lu})/gu;+ for (const m of q.matchAll(re)) {+ const idx = m.index ?? 0;+ // Walk back past the whitespace to the previous non-space char.+ let i = idx;+ while (i >= 0 && /\s/.test(q[i])) i--;+ if (i < 0) continue; // start of string → sentence-initial+ if (!/[.!?:;\n\r•\-(["“]/.test(q[i])) return true;+ }+ return false;+}++/**+ * v0.46.15 — concept-shape detection for the INTENT classifier. A query is+ * concept-shaped when it carries a landscape/quantifier OR definitional-+ * paraphrase cue, and NO exact-identifier or proper-noun anti-signal.+ * Precision-biased: quoted phrases, slugs, mid-sentence capitalized tokens,+ * and sub-3-word queries never trigger.+ */+export function isConceptShapedQuery(query: string): boolean {+ const q = query.trim();+ if (q.split(/\s+/).length < 3) return false; // bare token / proper-noun lookup+ const definitional = matches(CONCEPT_DEFINITIONAL_PATTERNS, q);+ if (!matches(CONCEPT_CUE_PATTERNS, q) && !definitional) return false;+ if (matches(CONCEPT_ANTI_PATTERNS, q)) return false;+ if (hasMidSentenceCapital(q)) return false;+ // Definitional-route only (F5): a status verb means the subject is an+ // entity being asked about, not a concept being defined.+ if (definitional && !matches(CONCEPT_CUE_PATTERNS, q) && CONCEPT_STATUS_ANTI_RE.test(q)) return false;+ return true;+}++/**+ * True when a query is concept-shaped for the CLI NUDGE (#2416). Consumes+ * the SAME shared cue/anti banks as the intent detector above (single+ * concept vocabulary — R2-11), composed differently for a different+ * decision: the nudge steers `search` → `query` (breadth/expansion), so it+ * keeps the landscape-cue subset, skips the proper-noun anti-signal (a+ * landscape query about a capitalized techonym still wants expansion), and+ * only backs off when the classifier is confident the query names an+ * ENTITY. The ranking detector is stricter because a wrong vector-lean+ * costs precision; a wrong nudge costs one stderr line.*/export function looksConceptShaped(query: string): boolean {const q = query.trim();diff --git a/src/core/types.ts b/src/core/types.tsindex bb8f2e639b..5f825b7a49 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -823,6 +823,15 @@ export interface SearchResult {*//** RRF + cosine score BEFORE any boost stage mutated it. */base_score?: number;+ /**+ * v0.46.15 — RAW query↔chunk cosine similarity from cosineReScore's+ * hydration (the active embedding column's space). Absent on keyword-only+ * / no-embedding paths. This is the ONLY calibrated semantic signal on the+ * result — evidence's `high_vector_match` keys off it, never off the+ * blended/boosted score (the #3963 class: a keyword+boost pile-up reading+ * as a vector match).+ */+ cosine?: number;/** Multiplier applied by applyBacklinkBoost (1.0 = unchanged). */backlink_boost?: number;/** Multiplier applied by applySalienceBoost. */@@ -959,6 +968,16 @@ export interface ResolvedColumn {export interface SearchOpts {limit?: number;offset?: number;+ /**+ * v0.46.15 — out-channel for searchVector's bounded pagination escalation+ * (retrieval-cathedral P1: one dense page could consume the whole inner+ * candidate pool before the per-page DISTINCT collapse, underfilling the+ * result). Engines have no telemetry sink; the HYBRID layer passes a+ * collector here and owns the emit. Called at most once per searchVector+ * call, only when the escalation loop ended with the page set still+ * underfilled at the HNSW substrate cap (ef_search hard ceiling).+ */+ onVectorPoolMeta?: (m: { underfilled: boolean; escalations: number; innerLimit: number }) => void;/*** v0.42 — intent-aware adaptive return-sizing. `true` enables with config/* default caps; an object overrides caps per-call; omitted/`false` = off@@ -1742,12 +1761,19 @@ export interface HybridSearchMeta {* command can show "intent: temporal" alongside results to make the* weighting decision auditable.*/- intent?: 'entity' | 'temporal' | 'event' | 'general';+ intent?: 'entity' | 'temporal' | 'event' | 'concept' | 'general';/*** v0.42 — adaptive return-sizing decision (intent, cap, kept, total).* Omitted when the gate is off. Surfaced for `gbrain search --explain`.*/adaptive_return?: import('./search/return-policy.ts').AdaptiveReturnDecision;+ /**+ * v0.46.15 — searchVector's bounded pagination escalation ended at the HNSW+ * substrate cap with the page set still underfilled (dense-corpus signal:+ * the caller asked for more distinct pages than the candidate pool could+ * yield). Omitted on clean runs. Exhaustion is VISIBLE, not silent.+ */+ vector_pool_underfilled?: { escalations: number; innerLimit: number };/*** v0.42.3.0 — autocut decision (signal, cut point, kept/total, gapRatio).* Omitted when autocut didn't run (no reranker). Surfaced fordiff --git a/src/eval/brainbench/adapters/claude-code.ts b/src/eval/brainbench/adapters/claude-code.tsindex fa02f190e9..11801b6f07 100644--- a/src/eval/brainbench/adapters/claude-code.ts+++ b/src/eval/brainbench/adapters/claude-code.ts@@ -1,42 +1,69 @@/**- * BrainBench Claude Code adapter — seam: 'contract'.+ * BrainBench Claude Code adapter — seam: 'production' (v0.46.15, TODOS:556 P1).*- * Defines the UserPromptSubmit hook contract a future integration PR- * implements, and grades gbrain's memory primitives through it. The exported- * wire types are THE contract: the real hook script will read- * `UserPromptSubmitHookInput` JSON on stdin and write- * `UserPromptSubmitHookOutput` JSON on stdout, so the bench is test-first for- * the integration — when the real hook lands, this adapter swaps its in-process- * transport for an exec of the hook script and flips seam to 'production' with- * continuous bench numbers.+ * Drives the REAL shipped integration end-to-end: the fixture turn becomes+ * `UserPromptSubmit` hook stdin JSON, `runHook(['user-prompt'], io)` executes+ * the production hook (stdin parse → transcript-window parse → IPC+ * turn_context → additionalContext), and a run-scoped resolve-IPC server —+ * the SAME `startResolveIpcServer` + `assembleTurnContext` pair `gbrain+ * serve` registers — answers over a real unix socket with the real shared+ * secret. What used to be an in-process contract simulation is now the+ * shipped wire, transcript window, cross-turn dedupe, and IPC auth path.*- * Contract deltas vs the openclaw seam (the deltas ARE what the row measures):- * - NO conversation memory: a hook sees only the current prompt, so- * prior-context suppression is off → expect a higher re-injection rate.- * - Smaller injection budget (2 pointers): hooks compete with everything- * else feeding additionalContext.- *- * Every turn round-trips through JSON.stringify/parse of the wire shapes so a- * contract-breaking change fails loudly here, not in a future integration.+ * Production-fidelity notes:+ * - The transcript for each turn is synthesized in the Claude Code JSONL+ * shape (prior turns + our OWN previously-injected blocks as+ * `hook_additional_context` attachments), so the hook's 4-turn window+ * and cross-turn dedupe are exercised for real — the old contract row's+ * `suppression: 'none'` re-injection cost is replaced by the shipped+ * dedupe behavior.+ * - `HookIo.configOverride` + `disablePushBanner` are documented TEST+ * SEAMS: they point the hook at the bench brain without mutating+ * process-global GBRAIN_HOME (parallel-test safe) and keep the+ * operator's push-status files out of the measurement.+ * - `userPromptDeadlineMs` is pinned generous (10s): the production 800ms+ * deadline on a loaded CI runner would read as intermittent know-to-ask+ * misses (flake, not signal). Deadline behavior itself is hook-suite+ * territory (test/hook-user-prompt.test.ts).+ * - injectedSlugs = the `→ \`slug\`` references in the rendered block+ * (reflex pointers + volunteered pages — both are per-turn injection+ * decisions). Hot-fact entity refs (`[slug]`) are deliberately NOT+ * counted: hot memory fires on every turn regardless of the prompt, so+ * counting it would saturate false_fire with a signal the know-to-ask+ * metric doesn't own.*/+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { Server } from 'node:net';import type { PGLiteEngine } from '../../../core/pglite-engine.ts';+import type { GBrainConfig } from '../../../core/config.ts';+import { runHook } from '../../../commands/hook.ts';+import {+ ensureIpcSecret,+ resolveSocketPath,+ startResolveIpcServer,+} from '../../../core/context/resolve-ipc.ts';+import { assembleTurnContext } from '../../../core/context/turn-context.ts';+import { resolveEntitiesToPointers } from '../../../core/context/retrieval-reflex.ts';import type {AdapterFixtureView,HarnessAdapter,HarnessTurnResult,PublicTurn,} from '../types.ts';-import { runReflexPipeline, toTurnResult } from './shared.ts';+import { estimateTokens } from './shared.ts';-/** stdin JSON the real UserPromptSubmit hook will receive. */+/** stdin JSON the real UserPromptSubmit hook receives. */export interface UserPromptSubmitHookInput {prompt: string;session_id: string;cwd: string;+ transcript_path?: string;}-/** stdout JSON the real UserPromptSubmit hook will emit. */+/** stdout JSON the real UserPromptSubmit hook emits. */export interface UserPromptSubmitHookOutput {hookSpecificOutput: {hookEventName: 'UserPromptSubmit';@@ -44,57 +71,204 @@ export interface UserPromptSubmitHookOutput {};}+/**+ * Kept for scoreboard continuity: the production hook path has no per-seam+ * pointer budget knob (the server's DEFAULT_MAX_POINTERS governs); this+ * constant now only documents the historical contract-row budget.+ */export const CLAUDE_CODE_MAX_POINTERS = 2;+/** Generous bench deadline — see the header's flake-class note. */+export const BENCH_USER_PROMPT_DEADLINE_MS = 10_000;++/** `→ \`slug\`` references in a rendered block (pointers + volunteered). */+const INJECTED_SLUG_RE = /→ `([^`\n]+)`/g;+export class ClaudeCodeAdapter implements HarnessAdapter {readonly name = 'claude-code' as const;- readonly seam = 'contract' as const;+ readonly seam = 'production' as const;private engine: PGLiteEngine | null = null;private sourceId = 'default';private sessionId = '';+ private fixtureSeq = 0;++ // ── run-scoped state (setupRun/teardownRun own the server + temp home) ──+ private tmpHome: string | null = null;+ private transcriptRoot: string | null = null;+ private server: Server | null = null;+ private dbPath = '';+ private secret = '';++ // ── per-conversation state ──+ private turns: PublicTurn[] = [];+ private injectionByTurnId = new Map<number, string>();++ async setupRun(): Promise<void> {+ this.tmpHome = mkdtempSync(join(tmpdir(), 'brainbench-cc-'));+ this.transcriptRoot = join(this.tmpHome, 'projects');+ mkdirSync(this.transcriptRoot, { recursive: true });+ // database_path is the IPC data dir: socket + secret live beside it,+ // exactly where the hook's resolveSocketPath/readIpcSecret look.+ this.dbPath = join(this.tmpHome, 'brain.pglite');+ mkdirSync(this.dbPath, { recursive: true });+ this.secret = ensureIpcSecret(this.dbPath);+ this.server = await startResolveIpcServer(+ resolveSocketPath(this.dbPath),+ {+ // The resolve kind mirrors the serve wiring; the hook lane uses+ // turn_context, but a v1 client probing the socket must not crash it.+ // Null-engine guards (adversarial F13b): endConversation nulls the+ // engine while the socket server stays up for the next fixture — a+ // deadline-abandoned in-flight request must degrade to empty, not+ // crash the server on `this.engine!`.+ resolve: (req) =>+ this.engine+ ? resolveEntitiesToPointers(this.engine, this.sourceId, req.candidates ?? [], {+ priorContextText: req.priorContextText,+ maxPointers: req.maxPointers,+ suppression: req.suppression,+ lexicalArms: req.lexicalArms,+ })+ : Promise.resolve(null),+ // The SAME handler shape gbrain serve registers (mcp/server.ts):+ // always assembles against the adapter's active source.+ turn_context: (req) =>+ this.engine+ ? assembleTurnContext(this.engine, {+ sourceId: this.sourceId,+ window: req.window ?? [],+ priorContextText: req.priorContextText,+ sessionId: req.sessionId,+ maxBytes: req.maxBytes,+ })+ : Promise.resolve(null),+ },+ { secret: this.secret },+ );+ if (!this.server) {+ throw new Error('claude-code adapter: could not start the resolve IPC server');+ }+ }++ async teardownRun(): Promise<void> {+ if (this.server) {+ await new Promise<void>((res) => this.server!.close(() => res()));+ this.server = null;+ }+ if (this.tmpHome) {+ rmSync(this.tmpHome, { recursive: true, force: true });+ this.tmpHome = null;+ }+ }async beginConversation(engine: PGLiteEngine, fixture: AdapterFixtureView): Promise<void> {+ if (!this.server) {+ // Legacy single-fixture construction (tests) — own the run lifecycle.+ await this.setupRun();+ }this.engine = engine;this.sourceId = fixture.active_source;- this.sessionId = `brainbench-${fixture.fixture_id}`;+ this.fixtureSeq += 1;+ this.sessionId = `brainbench-${fixture.fixture_id}-${this.fixtureSeq}`;+ this.turns = fixture.turns;+ this.injectionByTurnId = new Map();+ }++ /**+ * Synthesize the session transcript in the Claude Code JSONL shape: every+ * fixture turn BEFORE the one being replayed (user AND assistant — the+ * harness only replays user turns, but the shipped 4-turn window sees+ * both), with our own prior injections recorded as+ * hook_additional_context attachments right after their user turn.+ */+ private writeTranscript(beforeTurnId: number): string {+ const path = join(this.transcriptRoot!, `${this.sessionId}.jsonl`);+ let body = '';+ for (const t of this.turns) {+ if (t.turn_id >= beforeTurnId) break;+ body += JSON.stringify({ type: t.role, message: { role: t.role, content: t.text } }) + '\n';+ const injected = this.injectionByTurnId.get(t.turn_id);+ if (injected) {+ body += JSON.stringify({+ type: 'attachment',+ attachment: { type: 'hook_additional_context', content: [injected] },+ }) + '\n';+ }+ }+ writeFileSync(path, body);+ return path;}async replayTurn(turn: PublicTurn, _priorContextText: string): Promise<HarnessTurnResult> {- if (!this.engine) throw new Error('claude-code adapter: beginConversation not called');+ if (!this.engine || !this.tmpHome) {+ throw new Error('claude-code adapter: beginConversation not called');+ }const started = performance.now();- // Serialize to the hook's stdin wire shape, then parse back — the- // contract boundary is exercised on every turn.+ const transcriptPath = this.writeTranscript(turn.turn_id);const wireIn: UserPromptSubmitHookInput = {- prompt: turn.text,+ prompt: turn.role === 'user' ? turn.text : '',session_id: this.sessionId,- cwd: '/',+ cwd: this.tmpHome,+ transcript_path: transcriptPath,};- const parsedIn = JSON.parse(JSON.stringify(wireIn)) as UserPromptSubmitHookInput;-- const block = await runReflexPipeline(- this.engine,- this.sourceId,- { ...turn, text: parsedIn.prompt },- '', // a hook has no prior-turn memory — deliberate contract delta- { maxPointers: CLAUDE_CODE_MAX_POINTERS, suppression: 'none' },- );- const wireOut: UserPromptSubmitHookOutput = {- hookSpecificOutput: {- hookEventName: 'UserPromptSubmit',- additionalContext: block?.text ?? '',+ let stdout = '';+ const cfg = { engine: 'pglite', database_path: this.dbPath } as GBrainConfig;+ const exit = await runHook(['user-prompt'], {+ stdin: JSON.stringify(wireIn),+ write: (s) => {+ stdout += s;},- };- const parsedOut = JSON.parse(JSON.stringify(wireOut)) as UserPromptSubmitHookOutput;- const injected = parsedOut.hookSpecificOutput.additionalContext || null;+ cwd: this.tmpHome,+ transcriptRoot: this.transcriptRoot!,+ userPromptDeadlineMs: BENCH_USER_PROMPT_DEADLINE_MS,+ configOverride: cfg,+ disablePushBanner: true,+ // Telemetry paths resolve from GBRAIN_HOME/homedir, not configOverride+ // — without this, every fixture turn appends to the OPERATOR's real+ // hook heartbeat history (codex ship-review).+ disableTelemetry: true,+ });+ if (exit !== 0) {+ // The hook is fail-open by design (exit 0 on degraded paths); a nonzero+ // exit is a harness bug — fail loud, not as a silent know-to-ask miss.+ throw new Error(`claude-code adapter: hook exit ${exit}`);+ }++ let injected: string | null = null;+ if (stdout.trim()) {+ const parsed = JSON.parse(stdout) as UserPromptSubmitHookOutput;+ injected = parsed.hookSpecificOutput?.additionalContext || null;+ }++ const injectedSlugs: string[] = [];+ if (injected) {+ for (const m of injected.matchAll(INJECTED_SLUG_RE)) {+ if (!injectedSlugs.includes(m[1])) injectedSlugs.push(m[1]);+ }+ }const latencyMs = performance.now() - started;- return toTurnResult(block, injected, latencyMs);+ // Feed the shipped cross-turn dedupe: what we injected THIS turn appears+ // in later turns' transcripts as a hook_additional_context attachment.+ if (injected) this.injectionByTurnId.set(turn.turn_id, injected);++ return {+ injectedText: injected,+ injectedSlugs,+ // The production wire carries rendered text, not pointer objects —+ // metrics score injectedSlugs; receipts show the wire text.+ pointers: [],+ injectedTokens: estimateTokens(injected),+ latencyMs,+ };}async endConversation(): Promise<void> {this.engine = null;+ this.turns = [];+ this.injectionByTurnId = new Map();}}diff --git a/src/eval/brainbench/adapters/codex.ts b/src/eval/brainbench/adapters/codex.tsindex b112df2ef1..da807cd74b 100644--- a/src/eval/brainbench/adapters/codex.ts+++ b/src/eval/brainbench/adapters/codex.ts@@ -13,7 +13,11 @@* diagnostics (decision 18) see its cost.*/+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import type { PGLiteEngine } from '../../../core/pglite-engine.ts';+import { codexAdapter as codexTranscriptAdapter } from '../../../core/transcripts/codex.ts';import type {AdapterFixtureView,HarnessAdapter,@@ -34,12 +38,78 @@ export class CodexAdapter implements HarnessAdapter {private sourceId = 'default';private preamble = '';private firstTurn = true;+ private tmpDir: string | null = null;+ private fixtureSeq = 0;+ /** Turn texts the REAL rollout parser selected as user turns. */+ // Multiset keyed on trimmed text (adversarial F14): a Set could not see a+ // parser that DROPS one of two duplicate turns, and exact-equality keying+ // read cosmetic whitespace normalization as total turn loss.+ private parserSelected = new Map<string, number>();++ async setupRun(): Promise<void> {+ this.tmpDir = mkdtempSync(join(tmpdir(), 'brainbench-codex-'));+ }++ async teardownRun(): Promise<void> {+ if (this.tmpDir) {+ rmSync(this.tmpDir, { recursive: true, force: true });+ this.tmpDir = null;+ }+ }async beginConversation(engine: PGLiteEngine, fixture: AdapterFixtureView): Promise<void> {+ if (!this.tmpDir) await this.setupRun();this.engine = engine;this.sourceId = fixture.active_source;this.firstTurn = true;this.preamble = await this.buildPreamble();+ // v0.46.15 (F5, parser integration): the fixture conversation round-trips+ // through the REAL codex rollout format + the REAL shipped parser+ // (src/core/transcripts/codex.ts) for structural TURN SELECTION — a+ // parser drift that loses user turns now tanks the row visibly. The+ // fragment DELIVERY below remains a harness-shaped contract (disclosed+ // in docs/eval/BRAINBENCH.md); the full production flip is a filed TODO.+ this.parserSelected = await this.parseRollout(fixture);+ }++ /** Synthesize the rollout JSONL and run the shipped parser over it. */+ private async parseRollout(fixture: AdapterFixtureView): Promise<Map<string, number>> {+ this.fixtureSeq += 1;+ const path = join(this.tmpDir!, `rollout-${this.fixtureSeq}.jsonl`);+ const ts = '2026-01-01T00:00:00.000Z';+ const lines: string[] = [+ JSON.stringify({+ timestamp: ts,+ type: 'session_meta',+ payload: { session_id: `brainbench-${fixture.fixture_id}`, cwd: '/', timestamp: ts, cli_version: 'bench' },+ }),+ ];+ for (const t of fixture.turns) {+ if (t.role === 'user') {+ lines.push(+ JSON.stringify({ timestamp: ts, type: 'event_msg', payload: { type: 'user_message', message: t.text } }),+ );+ } else {+ lines.push(+ JSON.stringify({+ timestamp: ts,+ type: 'response_item',+ payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: t.text }] },+ }),+ );+ }+ }+ writeFileSync(path, lines.join('\n') + '\n');+ const selected = new Map<string, number>();+ const gen = codexTranscriptAdapter.parse(path);+ for await (const session of gen) {+ for (const m of session.messages) {+ if (m.role !== 'user') continue;+ const key = m.text.trim();+ selected.set(key, (selected.get(key) ?? 0) + 1);+ }+ }+ return selected;}/** Static entity index: titles + slugs in the active source, alphabetical. */@@ -66,6 +136,15 @@ export class CodexAdapter implements HarnessAdapter {async replayTurn(turn: PublicTurn, priorContextText: string): Promise<HarnessTurnResult> {if (!this.engine) throw new Error('codex adapter: beginConversation not called');const started = performance.now();+ // Parser-selected turns only (F5): a user turn the shipped rollout+ // parser failed to surface never reaches the fragment pipeline — parser+ // drift shows up as missed retrievals, not as a silently-passing bench.+ const selKey = turn.text.trim();+ const remaining = this.parserSelected.get(selKey) ?? 0;+ if (remaining <= 0) {+ return toTurnResult(null, null, performance.now() - started);+ }+ this.parserSelected.set(selKey, remaining - 1);const block = await runReflexPipeline(this.engine, this.sourceId, turn, priorContextText, {maxPointers: CODEX_MAX_FRAGMENTS,suppression: 'prior-context',diff --git a/src/eval/brainbench/harness.ts b/src/eval/brainbench/harness.tsindex 2a145d7776..7842802a5e 100644--- a/src/eval/brainbench/harness.ts+++ b/src/eval/brainbench/harness.ts@@ -78,10 +78,19 @@ function makeAdapter(name: HarnessName): HarnessAdapter {const SEAM: Record<HarnessName, 'production' | 'contract'> = {openclaw: 'production',- 'claude-code': 'contract',+ // v0.46.15 (TODOS:556 P1): the claude-code row now drives the REAL+ // UserPromptSubmit hook over the real IPC socket — see the adapter header.+ 'claude-code': 'production',codex: 'contract',};+/** The SEAM map and the adapters' own seam fields must agree — pinned by+ * test/brainbench-adapters.test.ts (outside-voice F4: the scoreboard reads+ * THIS map, so a flipped adapter field alone changes nothing). */+export function seamFor(name: HarnessName): 'production' | 'contract' {+ return SEAM[name];+}+function adapterView(lf: LoadedFixture): AdapterFixtureView {return {fixture_id: lf.fixture.fixture_id,@@ -175,6 +184,28 @@ export async function runBrainBench(const turnRows: TurnRow[] = [];const seedFailures: Array<{ fixture_id: string; error: string }> = [];+ // v0.46.15 (F4/R2-5): ONE adapter per harness per RUN, torn down in the+ // finally — a production seam owns long-lived infrastructure (the+ // claude-code IPC server) across fixtures instead of paying per-fixture+ // setup (the ~15s gate stays fast). setupRun is LAZY on first replay+ // (codex ship-review): a `--suite write-back` run replays nothing, so it+ // must not require the IPC substrate; and a setup that only happens inside+ // the try below can never leak a live socket server past the finally.+ // Input dedupe: a duplicated harness name would construct two instances+ // and orphan the first (Map overwrite).+ const harnessList = [...new Set(opts.harnesses)];+ const adapters = new Map<HarnessName, HarnessAdapter>();+ for (const h of harnessList) adapters.set(h, makeAdapter(h));+ const setUp = new Set<HarnessName>();+ const adapterFor = async (h: HarnessName): Promise<HarnessAdapter> => {+ const a = adapters.get(h)!;+ if (!setUp.has(h)) {+ setUp.add(h); // before the await — teardown must cover a FAILED setup too+ await a.setupRun?.();+ }+ return a;+ };+const wantedSuites = new Set(opts.suites);const eligible = corpus.fixtures.filter((lf) => {if (lf.fixture.holdout && !opts.includeHoldout) return false;@@ -236,8 +267,8 @@ export async function runBrainBench((s): s is BrainBenchSuite => (s === 'know-to-ask' || s === 'push') && wantedSuites.has(s),);if (retrievalSuites.length > 0) {- for (const harness of opts.harnesses) {- const adapter = makeAdapter(harness);+ for (const harness of harnessList) {+ const adapter = await adapterFor(harness);const rows = await replayFixture(engine, adapter, lf, seed, retrievalSuites);turnRows.push(...rows);}@@ -315,8 +346,8 @@ export async function runBrainBench(}// Every requested harness reads the SAME persisted state (read-only).- for (const readerHarness of opts.harnesses) {- const readerAdapter = makeAdapter(readerHarness);+ for (const readerHarness of harnessList) {+ const readerAdapter = await adapterFor(readerHarness);const readerRows = await replayFixture(engine, readerAdapter, reader, mergedSeed, ['continuity']);turnRows.push(...readerRows);@@ -334,12 +365,19 @@ export async function runBrainBench(}}} finally {+ for (const a of adapters.values()) {+ try {+ await a.teardownRun?.();+ } catch {+ /* teardown is best-effort — a leaked temp dir must not fail the run */+ }+ }await engine.disconnect();}// ---- assemble cells ----const cells: SuiteMetrics[] = [];- for (const harness of opts.harnesses) {+ for (const harness of harnessList) {for (const suite of opts.suites) {const cell = assembleCell(harness, suite, turnRows, writeBackAgg, continuityByReader, opts.llm);if (cell) cells.push(cell);diff --git a/src/eval/brainbench/types.ts b/src/eval/brainbench/types.tsindex 0ad3a4ada3..53521d5598 100644--- a/src/eval/brainbench/types.ts+++ b/src/eval/brainbench/types.ts@@ -204,6 +204,15 @@ export interface HarnessTurnResult {export interface HarnessAdapter {readonly name: HarnessName;readonly seam: SeamKind;+ /**+ * v0.46.15 — optional RUN-scoped lifecycle (outside-voice F4/R2-5). The+ * harness constructs ONE adapter per harness per run and calls setupRun+ * before the first fixture / teardownRun after the last, so a production+ * seam can own long-lived infrastructure (the claude-code adapter's+ * resolve-IPC server + temp home) instead of paying setup per fixture.+ */+ setupRun?(): Promise<void>;+ teardownRun?(): Promise<void>;/** Called once per (fixture, adapter) before any turn. */beginConversation(engine: PGLiteEngine, fixture: AdapterFixtureView): Promise<void>;/**diff --git a/src/eval/retrieval-quality/harness.ts b/src/eval/retrieval-quality/harness.tsindex 780bfb1f8b..f02ba1be8c 100644--- a/src/eval/retrieval-quality/harness.ts+++ b/src/eval/retrieval-quality/harness.ts@@ -23,6 +23,7 @@ export type Family =| 'multi-chunk-dilution'| 'short-vs-rich'| 'graph-relationship'+ | 'concept-paraphrase'| 'hard-negative';export interface NamedThingQuestion {@@ -160,7 +161,7 @@ export const DEFAULT_GATE: GateOpts = {'multi-chunk-dilution': { hit_at_3: floorEnv('GBRAIN_NTB_DILUTION_HIT3', 1.0) },'alias-synonym': { hit_at_1: floorEnv('GBRAIN_NTB_ALIAS_HIT1', 0.98) },},- softFamilies: ['generic-to-named', 'short-vs-rich', 'graph-relationship', 'hard-negative'],+ softFamilies: ['generic-to-named', 'short-vs-rich', 'graph-relationship', 'concept-paraphrase', 'hard-negative'],};function floorEnv(name: string, dflt: number): number {diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex d8aab22ae5..1b7eff3fe8 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -19,6 +19,7 @@ import {ensureIpcSecret,} from '../core/context/resolve-ipc.ts';import { resolveEntitiesToPointers, logDeliveredReflexPointers } from '../core/context/retrieval-reflex.ts';+import { lexicalArmsEnabled } from '../core/context/reflex.ts';import { assembleTurnContext } from '../core/context/turn-context.ts';import { gcSessionContextState } from '../core/context/session-state.ts';import { makeContextPackIpcHandler } from './context-pack-handler.ts';@@ -212,6 +213,15 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSpriorContextText: req.priorContextText,maxPointers: req.maxPointers,suppression: req.suppression,+ // v0.46.15 kill switch: either side may disable — a client+ // `false` wins, else the server's own file-config gate.+ // Config is re-read PER REQUEST (adversarial F3): `gbrain+ // serve` is long-running, and the switch's whole value is+ // reverting a false-fire regression on the NEXT TURN with a+ // config edit — a startup snapshot would freeze it until a+ // serve restart. loadConfig is a file read (~1ms) inside the+ // 400ms IPC budget.+ lexicalArms: req.lexicalArms === false ? false : lexicalArmsEnabled(loadConfig()),},),// IPC v2 [ENG-3]: per-turn context assembly for the hook command.@@ -225,6 +235,9 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSpriorContextText: req.priorContextText,sessionId: req.sessionId,maxBytes: req.maxBytes,+ // Per-request config read — same next-turn-revert rationale as+ // the resolve handler above (adversarial F3).+ lexicalArms: lexicalArmsEnabled(loadConfig()),}),// v0.45.7 ambient recall: boundary context pack. Extracted to// context-pack-handler.ts (directly testable against a real engine);diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex bb1575f12b..8e18bf3792 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.46.14.0 -->+<!-- gbrain-template-stamp: 0.46.15.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/brainbench-adapters.test.ts b/test/brainbench-adapters.test.tsindex 45ad07ad71..121993dd2d 100644--- a/test/brainbench-adapters.test.ts+++ b/test/brainbench-adapters.test.ts@@ -112,30 +112,70 @@ describe('OpenClawAdapter (production seam)', () => {}, 30_000);});-describe('ClaudeCodeAdapter (contract seam: hook wire shape, no conversation memory)', () => {- test('round-trips the UserPromptSubmit JSON contract and ignores prior context', async () => {+describe('ClaudeCodeAdapter (PRODUCTION seam: real hook + real IPC — v0.46.15 flip)', () => {+ test('drives the shipped UserPromptSubmit hook end-to-end over the IPC socket', async () => {const a = new ClaudeCodeAdapter();- await a.beginConversation(engine, VIEW);- const prior = 'we already injected people/alice-example earlier';- const r = await a.replayTurn(turn('Status on Alice Example?'), prior);- // No memory: prior context does NOT suppress (the measured contract delta).+ await a.beginConversation(engine, {+ ...VIEW,+ turns: [{ turn_id: 1, role: 'user', text: 'Status on Alice Example?' }],+ });+ const r = await a.replayTurn(turn('Status on Alice Example?'), '');expect(r.injectedSlugs).toContain('people/alice-example');+ // The wire artifact is the hook's rendered additionalContext.+ expect(r.injectedText).toContain('people/alice-example');await a.endConversation();+ await a.teardownRun?.();}, 30_000);- test('respects the 2-pointer hook budget', async () => {+ test('RE-PINNED (v0.46.15): the shipped budget governs, not the old 2-pointer contract cap', async () => {+ // Was: <= 2 (the contract row's budget). The production row runs the+ // shipped hook -> turn_context path: DEFAULT_MAX_POINTERS (3) reflex+ // pointers + the volunteer layer's own cap. Bounded, but by production+ // knobs — that delta IS what the seam flip measures.const a = new ClaudeCodeAdapter();- await a.beginConversation(engine, VIEW);- const r = await a.replayTurn(turn('Memo: Alice Example, Charlie Example, and Widget Co all in one.'), '');- expect(r.injectedSlugs.length).toBeLessThanOrEqual(2);+ const text = 'Memo: Alice Example, Charlie Example, and Widget Co all in one.';+ await a.beginConversation(engine, { ...VIEW, turns: [{ turn_id: 1, role: 'user', text }] });+ const r = await a.replayTurn(turn(text), '');+ expect(r.injectedSlugs.length).toBeGreaterThanOrEqual(1);+ expect(r.injectedSlugs.length).toBeLessThanOrEqual(6); // 3 pointers + <=3 volunteered+ await a.endConversation();+ await a.teardownRun?.();+ }, 30_000);++ test('cross-turn dedupe is REAL now: our own prior injection suppresses re-injection', async () => {+ const a = new ClaudeCodeAdapter();+ const t1 = 'Status on Alice Example?';+ const t2 = 'Anything else on Alice Example?';+ await a.beginConversation(engine, {+ ...VIEW,+ turns: [+ { turn_id: 1, role: 'user', text: t1 },+ { turn_id: 2, role: 'user', text: t2 },+ ],+ });+ const r1 = await a.replayTurn({ turn_id: 1, role: 'user', text: t1 }, '');+ expect(r1.injectedSlugs).toContain('people/alice-example');+ const r2 = await a.replayTurn({ turn_id: 2, role: 'user', text: t2 }, '');+ // The shipped transcript-window dedupe (hook_additional_context+ // attachment round-trip) suppresses the page volunteered one turn ago.+ expect(r2.injectedSlugs).not.toContain('people/alice-example');await a.endConversation();+ await a.teardownRun?.();}, 30_000);});-describe('CodexAdapter (contract seam: static preamble + ≤1 fragment)', () => {+describe('CodexAdapter (contract seam: static preamble + ≤1 fragment + REAL rollout parser turn selection)', () => {test('one fragment max; preamble slugs do NOT count as injections; preamble tokens land once', async () => {const a = new CodexAdapter();- await a.beginConversation(engine, VIEW);+ // v0.46.15 (F5): the adapter round-trips the fixture through the shipped+ // rollout parser for turn selection — turns must exist in the view.+ await a.beginConversation(engine, {+ ...VIEW,+ turns: [+ { turn_id: 1, role: 'user', text: 'Brief me on Alice Example and Charlie Example.' },+ { turn_id: 2, role: 'user', text: 'And Widget Co?' },+ ],+ });const r1 = await a.replayTurn(turn('Brief me on Alice Example and Charlie Example.'), '');expect(r1.injectedSlugs.length).toBeLessThanOrEqual(1);// The preamble indexes every page, but only the fragment is scored.@@ -166,3 +206,12 @@ describe('sentinel isolation (the engine-sharing guarantee, eng-review D9)', ()await seedBrain(engine, FIXTURE);}, 30_000);});++describe('SEAM map ↔ adapter.seam agreement (outside-voice F4)', () => {+ test('the scoreboard map and every adapter field agree', async () => {+ const { seamFor } = await import('../src/eval/brainbench/harness.ts');+ expect(seamFor('openclaw')).toBe(new OpenClawAdapter().seam);+ expect(seamFor('claude-code')).toBe(new ClaudeCodeAdapter().seam);+ expect(seamFor('codex')).toBe(new CodexAdapter().seam);+ });+});diff --git a/test/brainbench-floors.test.ts b/test/brainbench-floors.test.tsnew file mode 100644index 0000000000..40f9ee4187--- /dev/null+++ b/test/brainbench-floors.test.ts@@ -0,0 +1,64 @@+/**+ * v0.46.15 — EXECUTABLE pre-registered floors (outside-voice R2-14).+ *+ * The BrainBench CI gate is baseline-RELATIVE (HEAD run vs origin/master's+ * committed baseline) and a justified `--update-baseline` can bank any+ * movement — so the wave's pre-registered absolute floors were prose until+ * this test. It asserts them against the COMMITTED baseline: a future+ * justified bank that regresses below a floor now fails the unit suite,+ * not just a human reviewer's judgment.+ *+ * Floors are the v0.46.15 identity-wave pre-registrations (MINIMUMS — the+ * banked numbers exceed several of them; do not ratchet the floors to the+ * observed values without a new pre-registration):+ * know_to_ask_failure_rate ≤ 0.05 false_fire_rate ≤ 0.03+ * push_precision ≥ 0.95 source_isolation_violations = 0+ * push_recall ≥ 0.88 / 0.72 / 0.52 (openclaw / claude-code / codex)+ */++import { describe, test, expect } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++type CellMetrics = Record<string, number>;++const baseline = JSON.parse(+ readFileSync(join(import.meta.dir, '..', 'evals', 'brainbench', 'baselines', 'main.json'), 'utf8'),+) as { cells: Record<string, CellMetrics> };++function cell(harness: string, suite: string): CellMetrics {+ const c = baseline.cells[`${harness}/${suite}`];+ if (!c) throw new Error(`baseline cell missing: ${harness}/${suite}`);+ return c;+}++const HARNESSES = ['openclaw', 'claude-code', 'codex'] as const;+const PUSH_RECALL_FLOORS: Record<(typeof HARNESSES)[number], number> = {+ openclaw: 0.88,+ 'claude-code': 0.72,+ codex: 0.52,+};++describe('pre-registered absolute floors (v0.46.15) hold in the committed baseline', () => {+ for (const h of HARNESSES) {+ test(`${h}: know_to_ask_failure_rate ≤ 0.05 and false_fire_rate ≤ 0.03`, () => {+ const m = cell(h, 'know-to-ask');+ expect(m.know_to_ask_failure_rate).toBeLessThanOrEqual(0.05);+ expect(m.false_fire_rate).toBeLessThanOrEqual(0.03);+ });++ test(`${h}: push_precision ≥ 0.95 and push_recall ≥ ${PUSH_RECALL_FLOORS[h]}`, () => {+ const m = cell(h, 'push');+ expect(m.push_precision).toBeGreaterThanOrEqual(0.95);+ expect(m.push_recall).toBeGreaterThanOrEqual(PUSH_RECALL_FLOORS[h]);+ });+ }++ test('source_isolation_violations = 0 in EVERY cell (hard floor)', () => {+ const keys = Object.keys(baseline.cells);+ expect(keys.length).toBeGreaterThan(0);+ for (const k of keys) {+ expect(baseline.cells[k].source_isolation_violations ?? 0).toBe(0);+ }+ });+});diff --git a/test/by-mention.test.ts b/test/by-mention.test.tsindex b9111b0c6e..80f96b2f3b 100644--- a/test/by-mention.test.ts+++ b/test/by-mention.test.ts@@ -648,6 +648,75 @@ describe('buildGazetteer — engine integration', () => {expect(g.get('apple')![0]!.slug).toBe('companies/apple');});+ test('alias entries (v0.46.15, #3801): page_aliases become gazetteer entries', async () => {+ await engine.putPage('people/saoirse-x', {+ type: 'person', title: 'Saoirse Example', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ await engine.setPageAliases('people/saoirse-x', 'default', ['saoirse']);+ const g = await buildGazetteer(engine);+ const bucket = g.get('saoirse');+ expect(bucket).toBeDefined();+ expect(bucket!.some((e) => e.slug === 'people/saoirse-x')).toBe(true);+ });++ test('REGRESSION (v0.46.15): ignore-list rejects ALIAS entries case-insensitively; CK12 title behavior unchanged', async () => {+ // Title side (unchanged CK12 policy): a real page titled "Apple" stays.+ await engine.putPage('companies/apple', {+ type: 'company', title: 'Apple', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ // Alias side (new teeth): an alias "apple" on an unrelated page is+ // suppressed — aliases are not user-created pages; the cased ignore list+ // must match the normalized-lowercase alias store.+ await engine.putPage('people/annie-p', {+ type: 'person', title: 'Annie P Example', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ await engine.setPageAliases('people/annie-p', 'default', ['apple']);+ const g = await buildGazetteer(engine);+ const bucket = g.get('apple') ?? [];+ expect(bucket.some((e) => e.slug === 'companies/apple')).toBe(true); // title entry survives+ expect(bucket.some((e) => e.slug === 'people/annie-p')).toBe(false); // alias entry rejected+ });++ test('alias entries: ambiguous alias (two slugs, same source) is skipped', async () => {+ await engine.putPage('people/sable-one', {+ type: 'person', title: 'Sable One Example', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ await engine.putPage('people/sable-two', {+ type: 'person', title: 'Sable Two Example', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ await engine.setPageAliases('people/sable-one', 'default', ['sable']);+ await engine.setPageAliases('people/sable-two', 'default', ['sable']);+ const g = await buildGazetteer(engine);+ // Title entries ("Sable One Example" etc.) legitimately share the key —+ // the ALIAS-shaped entries (single-token) must be absent.+ expect((g.get('sable') ?? []).filter((e) => e.tokens.length === 1)).toHaveLength(0);+ });++ test('alias entries: alias colliding with an existing page TITLE in the same source is skipped', async () => {+ await engine.putPage('companies/acme-corp', {+ type: 'company', title: 'Acme', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ await engine.putPage('people/andy-c', {+ type: 'person', title: 'Andy C Example', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ await engine.setPageAliases('people/andy-c', 'default', ['acme']);+ const g = await buildGazetteer(engine);+ const bucket = g.get('acme') ?? [];+ expect(bucket.some((e) => e.slug === 'companies/acme-corp')).toBe(true);+ expect(bucket.some((e) => e.slug === 'people/andy-c')).toBe(false);+ });++ test('alias entries: sub-MIN_NAME_LENGTH aliases are skipped', async () => {+ await engine.putPage('people/jt-example', {+ type: 'person', title: 'JT Example Person', compiled_truth: 'b', timeline: '', frontmatter: {},+ });+ await engine.setPageAliases('people/jt-example', 'default', ['jt']);+ const g = await buildGazetteer(engine);+ // The multi-token TITLE entry may share the key; the single-token alias+ // entry ('jt' < MIN_NAME_LENGTH) must be absent.+ expect((g.get('jt') ?? []).filter((e) => e.tokens.length === 1)).toHaveLength(0);+ });+test('13. all entity pages soft-deleted → empty gazetteer', async () => {await engine.putPage('people/alice', {type: 'person', title: 'Alice Example', compiled_truth: 'b', timeline: '', frontmatter: {},diff --git a/test/context/entity-salience.test.ts b/test/context/entity-salience.test.tsindex c7846219a9..895eb896ac 100644--- a/test/context/entity-salience.test.ts+++ b/test/context/entity-salience.test.ts@@ -3,10 +3,24 @@* No DB, no SDK — just the deterministic candidate extraction + precision filters.*/import { describe, test, expect } from 'bun:test';-import { extractCandidates, MAX_CANDIDATES } from '../../src/core/context/entity-salience.ts';+import {+ extractCandidates,+ extractCandidatesFromWindow,+ MAX_CANDIDATES,+ MAX_WEAK_CANDIDATES,+} from '../../src/core/context/entity-salience.ts';+/** STRONG candidate queries only (the v1 contract most tests pin). */function queries(text: string): string[] {- return extractCandidates(text).map((c) => c.query);+ return extractCandidates(text)+ .filter((c) => !c.weak)+ .map((c) => c.query);+}++function weakQueries(text: string): string[] {+ return extractCandidates(text)+ .filter((c) => c.weak)+ .map((c) => c.query);}describe('extractCandidates', () => {@@ -29,6 +43,9 @@ describe('extractCandidates', () => {});test('drops weekday/common words seen only at sentence start', () => {+ // Re-pinned for the v0.46.15 identity wave: STRONG extraction still drops+ // these; the lowercase pass may emit weak candidates ("ship", "busy"),+ // which are alias-arm-restricted and cannot fabricate pointers.expect(queries('Monday we ship. Today is busy.')).toEqual([]);});@@ -67,7 +84,98 @@ describe('extractCandidates', () => {expect(extractCandidates(null)).toEqual([]);});- test('documented v1 limit: lowercase names are NOT detected', () => {+ test('lowercase names are now detected as WEAK candidates (v1 limit lifted at extraction)', () => {+ // Re-pinned for the v0.46.15 identity wave (was: "lowercase names are NOT+ // detected"). The lowercase pass emits weak, alias-arm-restricted+ // candidates; strong extraction stays capitalization-biased.expect(queries('what about garry tan')).toEqual([]);+ const weak = weakQueries('what about garry tan');+ expect(weak).toContain('garry');+ expect(weak).toContain('tan');+ });++ test('leading-stopword trim: surname escapes a glued auxiliary', () => {+ // "Did Galewright" is the raw run; the trimmed remainder must ALSO be a+ // strong candidate (kta-pos variant 4, the documented surname-only limit).+ const q = queries('Did Galewright ever follow up on that intro?');+ expect(q).toContain('Galewright');+ expect(q).toContain('Did Galewright'); // original run preserved+ });++ test('trim keeps multi-token remainders whole', () => {+ expect(queries('Did Garry Tan reply?')).toContain('Garry Tan');+ });++ test('weak candidates: possessives stripped, stopwords/common excluded, deduped vs strong', () => {+ const weak = weakQueries("remind me what saoirse's take on the round was");+ expect(weak).toContain('saoirse');+ expect(weak).not.toContain('the'); // stopword+ expect(weak).not.toContain('me'); // stopword (and <3 chars)+ const both = extractCandidates('Apple and apple again');+ // lowercase "apple" is covered by the strong "Apple" candidate — no weak dup+ expect(both.filter((c) => c.weak).map((c) => c.query)).not.toContain('apple');+ });++ test('weak candidates ride a separate budget and never evict strong ones', () => {+ const strongPart = Array.from({ length: 20 }, (_, i) => `Personx${i}q`).join('. ');+ const weakPart = Array.from({ length: 50 }, (_, i) => `wkword${i}xy`).join(' ');+ const out = extractCandidates(`${strongPart}. ${weakPart}`);+ const strong = out.filter((c) => !c.weak);+ const weak = out.filter((c) => c.weak);+ expect(strong.length).toBeLessThanOrEqual(MAX_CANDIDATES);+ expect(strong.length).toBe(MAX_CANDIDATES); // weak never displaces strong+ expect(weak.length).toBeLessThanOrEqual(MAX_WEAK_CANDIDATES);+ // strong candidates come first in the output+ expect(out.findIndex((c) => c.weak)).toBeGreaterThanOrEqual(strong.length);+ });+});++describe('extractCandidatesFromWindow — weak threading (v0.46.15)', () => {+ test('weak flag survives the window merge', () => {+ const out = extractCandidatesFromWindow([+ { role: 'user', text: 'remind me what saoirse said' },+ ]);+ const saoirse = out.find((c) => c.query === 'saoirse');+ expect(saoirse).toBeDefined();+ expect(saoirse!.weak).toBe(true);+ });++ test('a strong sighting upgrades a weak-born candidate and takes its surface', () => {+ const out = extractCandidatesFromWindow([+ { role: 'user', text: 'remind me what saoirse said' },+ { role: 'user', text: 'I met Saoirse yesterday' },+ ]);+ const c = out.find((x) => x.query.toLowerCase() === 'saoirse');+ expect(c).toBeDefined();+ expect(c!.weak).toBeUndefined();+ expect(c!.display).toBe('Saoirse');+ });++ test('strong candidates rank strictly above weak, with separate budgets', () => {+ const weakTurn = Array.from({ length: 40 }, (_, i) => `wkword${i}xy`).join(' ');+ const out = extractCandidatesFromWindow([+ { role: 'assistant', text: 'Galewright shipped the memo' }, // old strong+ { role: 'user', text: weakTurn }, // fresh weak noise+ ]);+ const strongIdx = out.findIndex((c) => c.query === 'Galewright');+ expect(strongIdx).toBe(0); // recent weak noise never outranks an older strong candidate+ expect(out.filter((c) => !c.weak).length).toBeLessThanOrEqual(MAX_CANDIDATES);+ expect(out.filter((c) => c.weak).length).toBeLessThanOrEqual(MAX_WEAK_CANDIDATES);+ });+});++describe('v0.46.15 ship-review F10 — rejected strong candidates do not shadow weak probes', () => {+ test('a name pushed past MAX_CANDIDATES still gets its lowercase weak probe', () => {+ // 12 strong names consume the strong cap; the 13th name appears ONLY+ // beyond the cap plus once lowercase. strongNorms built from the raw+ // accumulator would suppress the weak probe for a name that was never+ // actually emitted as strong.+ const names = Array.from({ length: 13 }, (_, i) => `Zed Persona${i}`);+ const text = names.map((n) => `${n} joined.`).join(' ') + ' later persona12 pinged me again';+ const out = extractCandidates(text);+ const strong = out.filter((c) => !c.weak);+ expect(strong.length).toBeLessThanOrEqual(MAX_CANDIDATES);+ const weak = out.filter((c) => c.weak);+ expect(weak.some((c) => c.query === 'persona12')).toBe(true);});});diff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.tsindex 68745455d6..452704f5cc 100644--- a/test/cross-modal-phase1.test.ts+++ b/test/cross-modal-phase1.test.ts@@ -136,7 +136,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {return resolveSearchMode({ mode: 'balanced' });}- test('KNOBS_HASH_VERSION is 17 (cross-modal still appended; 15→16 detail fold #3515; 16→17 degradation-stamp epoch)', () => {+ test('KNOBS_HASH_VERSION is 18 (cross-modal still appended; 16→17 degradation-stamp epoch; 17→18 autocut weak-top floor #1863)', () => {// v0.35 ladder: 1→2 reranker, 2→3 floor_ratio. v0.36 piggybacks on v=3// with 7 cross-modal knobs + column/provider context. v0.40.4 (salem) +// v0.39 T21 (master) bump to v=4 for graph_signals + schema-pack fields.@@ -152,7 +152,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {// #3515: 15→16 detail fold (det=).// WP2/T3: 16→17 degradation-stamp epoch — pre-stamp cache rows must not// claim a clean (undegraded) run they can't prove.- expect(KNOBS_HASH_VERSION).toBe(17);+ expect(KNOBS_HASH_VERSION).toBe(18);});test('flipping unified_multimodal changes the hash', () => {diff --git a/test/dedup.test.ts b/test/dedup.test.tsindex b714973653..cb94f5ba2c 100644--- a/test/dedup.test.ts+++ b/test/dedup.test.ts@@ -36,14 +36,29 @@ describe('dedupResults', () => {expect(aChunks.length).toBeLessThanOrEqual(2);});- test('removes text-similar chunks', () => {+ test('removes text-similar chunks WITHIN a page (v0.46.15 #3983 scope)', () => {+ const base = 'the quick brown fox jumps over the lazy dog while seventeen other animals watch from a nearby grassy hill in silence';const results = [- makeResult({ slug: 'a', score: 0.9, chunk_text: 'the quick brown fox jumps over the lazy dog' }),- makeResult({ slug: 'b', score: 0.8, chunk_text: 'the quick brown fox jumps over the lazy cat' }),+ makeResult({ slug: 'a', chunk_id: 1, score: 0.9, chunk_text: `${base} today` }),+ makeResult({ slug: 'a', chunk_id: 2, score: 0.8, chunk_text: `${base} now` }),];const deduped = dedupResults(results);- // These share high Jaccard similarity, one should be removed- expect(deduped.length).toBeLessThanOrEqual(2);+ // Same page, near-identical text → intra-page collapse still fires.+ expect(deduped.filter(r => r.slug === 'a').length).toBe(1);+ });++ test('REGRESSION (#3983): near-duplicate text on DIFFERENT pages never deletes a page', () => {+ // Near-duplicate-record corpus: two deal memos sharing boilerplate.+ // The unscoped Jaccard drop silently deleted the second PAGE from the+ // result set — distinct pages are distinct answers.+ const results = [+ makeResult({ slug: 'deals/acme-seed', page_id: 1, score: 0.9, chunk_text: 'standard deal memo boilerplate terms valuation notes intro' }),+ makeResult({ slug: 'deals/widget-series-a', page_id: 2, score: 0.85, chunk_text: 'standard deal memo boilerplate terms valuation notes summary' }),+ ];+ const deduped = dedupResults(results);+ const pages = new Set(deduped.map(r => r.slug));+ expect(pages.has('deals/acme-seed')).toBe(true);+ expect(pages.has('deals/widget-series-a')).toBe(true);});test('enforces type diversity when mixed types present', () => {diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.tsindex 5df1518aaa..757b5dd56e 100644--- a/test/e2e/engine-parity.test.ts+++ b/test/e2e/engine-parity.test.ts@@ -150,6 +150,48 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {expect(pgResults[0]?.slug).toBe(pgliteResults[0]?.slug);});+ test('v0.46.15 searchVector escalation parity: a dense page cannot starve the page result on either engine', async () => {+ // One page with 120 chunks nearest the query + 8 sparse pages behind it.+ // Pre-fix, the 100-chunk inner pool was consumed entirely by the dense+ // page → 1 result page. The bounded escalation loop (identical in both+ // engines) must recover >= limit distinct pages with identical top-5.+ const denseDim = 900;+ const mk = (cos: number, other: number): Float32Array => {+ const e = new Float32Array(1536);+ e[denseDim] = cos;+ e[other % 1536] = Math.sqrt(Math.max(0, 1 - cos * cos));+ return e;+ };+ for (const eng of [pgEngine, pgliteEngine]) {+ await eng.putPage('notes/parity-dense', { type: 'note', title: 'Parity Dense', compiled_truth: 'd.' });+ await eng.upsertChunks(+ 'notes/parity-dense',+ Array.from({ length: 120 }, (_, i) => ({+ chunk_index: i,+ chunk_text: `pd ${i}`,+ chunk_source: 'compiled_truth' as const,+ embedding: mk(0.99 - i * 0.0005, 1000 + i),+ token_count: 2,+ })),+ );+ for (let p = 0; p < 8; p++) {+ const slug = `notes/parity-sparse-${p}`;+ await eng.putPage(slug, { type: 'note', title: `Parity Sparse ${p}`, compiled_truth: 's.' });+ await eng.upsertChunks(slug, [+ { chunk_index: 0, chunk_text: `ps ${p}`, chunk_source: 'compiled_truth', embedding: mk(0.6 - p * 0.001, 1200 + p), token_count: 2 },+ ]);+ }+ }+ const q = new Float32Array(1536);+ q[denseDim] = 1.0;+ const pg = await pgEngine.searchVector(q, { limit: 6, detail: 'high' });+ const pl = await pgliteEngine.searchVector(q, { limit: 6, detail: 'high' });+ expect(pg.length).toBe(6); // pre-fix: 1+ expect(pl.length).toBe(6);+ expect(pg.slice(0, 5).map((r) => r.slug)).toEqual(pl.slice(0, 5).map((r) => r.slug));+ expect(new Set(pg.map((r) => r.slug)).size).toBe(6);+ });+test('#4152 dream verdict triage-v1 round-trip: identical shape on both engines (jsonb path)', async () => {// The postgres path binds segments/entities via sql.json(); PGLite via// $N::jsonb + JSON.stringify. A double-encode regression on the postgresdiff --git a/test/entity-resolve.test.ts b/test/entity-resolve.test.tsindex 2b67fde09f..a311588ecc 100644--- a/test/entity-resolve.test.ts+++ b/test/entity-resolve.test.ts@@ -324,3 +324,66 @@ describe('resolveEntitySlugWithSource — back-compat with resolveEntitySlug', (expect(b!.source).toBe<ResolutionSource>('fallback_slugify');});});++describe('alias_exact branch (v0.46.15 identity wave, #3730)', () => {+ it('an unambiguous registered alias resolves before prefix expansion / fuzzy', async () => {+ await engine.setPageAliases('people/bob-rosenstein', 'default', ['rosey']);+ const a = await resolveEntitySlug(engine as unknown as BrainEngine, 'default', 'rosey');+ expect(a).toBe('people/bob-rosenstein');+ const b = await resolveEntitySlugWithSource(engine as unknown as BrainEngine, 'default', 'rosey');+ expect(b!.slug).toBe('people/bob-rosenstein');+ expect(b!.source).toBe<ResolutionSource>('alias_exact');+ });++ it('alias beats the ambiguous bare-name collision that prefix expansion refuses', async () => {+ // "bob" prefix-expands ambiguously (bob-example vs bob-rosenstein) and+ // previously fell to fallback_slugify('bob'). A registered alias resolves it.+ await engine.setPageAliases('people/bob-example', 'default', ['bob']);+ const r = await resolveEntitySlugWithSource(engine as unknown as BrainEngine, 'default', 'bob');+ expect(r!.slug).toBe('people/bob-example');+ expect(r!.source).toBe<ResolutionSource>('alias_exact');+ });++ it('a phantom alias (deleted page) is ignored — falls through to the old chain', async () => {+ await engine.putPage('people/ghost-example', {+ type: 'person', title: 'Ghost Example', compiled_truth: 'b', timeline: '', frontmatter: {},+ } as never);+ await engine.setPageAliases('people/ghost-example', 'default', ['spectre']);+ await engine.softDeletePage('people/ghost-example');+ const r = await resolveEntitySlugWithSource(engine as unknown as BrainEngine, 'default', 'spectre');+ expect(r!.source).toBe<ResolutionSource>('fallback_slugify');+ expect(r!.slug).toBe('spectre');+ });+});++describe('alias_exact — liveness before uniqueness (v0.46.15 codex ship-review)', () => {+ it('a stale sibling alias row (deleted page) cannot veto the sole live target', async () => {+ await engine.putPage('people/nickname-live', {+ type: 'person', title: 'Nickname Live', compiled_truth: 'b', timeline: '', frontmatter: {},+ } as never);+ await engine.putPage('people/nickname-old', {+ type: 'person', title: 'Nickname Old', compiled_truth: 'b', timeline: '', frontmatter: {},+ } as never);+ await engine.setPageAliases('people/nickname-live', 'default', ['nicky']);+ await engine.setPageAliases('people/nickname-old', 'default', ['nicky']);+ await engine.softDeletePage('people/nickname-old');+ // Raw-hit uniqueness would see 2 rows, reject, and fall through to+ // fallback_slugify('nicky') — recreating a phantom slug on a WRITE path.+ const r = await resolveEntitySlugWithSource(engine as unknown as BrainEngine, 'default', 'nicky');+ expect(r!.slug).toBe('people/nickname-live');+ expect(r!.source).toBe<ResolutionSource>('alias_exact');+ });++ it('two LIVE holders of the same alias stay ambiguous (no pointer)', async () => {+ await engine.putPage('people/twin-a', {+ type: 'person', title: 'Twin A', compiled_truth: 'b', timeline: '', frontmatter: {},+ } as never);+ await engine.putPage('people/twin-b', {+ type: 'person', title: 'Twin B', compiled_truth: 'b', timeline: '', frontmatter: {},+ } as never);+ await engine.setPageAliases('people/twin-a', 'default', ['twinsy']);+ await engine.setPageAliases('people/twin-b', 'default', ['twinsy']);+ const r = await resolveEntitySlugWithSource(engine as unknown as BrainEngine, 'default', 'twinsy');+ expect(r!.source).not.toBe<ResolutionSource>('alias_exact');+ });+});diff --git a/test/fixtures/eval-baselines/qrels-search.json b/test/fixtures/eval-baselines/qrels-search.jsonindex 8fc3f85134..018642e388 100644--- a/test/fixtures/eval-baselines/qrels-search.json+++ b/test/fixtures/eval-baselines/qrels-search.json@@ -85,6 +85,20 @@"embedding_dim": 11,"relevant_slugs": ["originals/founder-mode-example", "concepts/founder-mode-example"],"first_relevant_slug": "originals/founder-mode-example"+ },+ {+ "query_id": "q13-concept-paraphrase",+ "query": "what is the compounding advantage idea",+ "embedding_dim": 12,+ "relevant_slugs": ["concepts/compounding-advantage-example", "notes/compounding-mentions-example"],+ "first_relevant_slug": "concepts/compounding-advantage-example"+ },+ {+ "query_id": "q14-concept-knowabout",+ "query": "what do i know about founder liquidity",+ "embedding_dim": 13,+ "relevant_slugs": ["concepts/founder-liquidity-example", "notes/liquidity-mentions-example"],+ "first_relevant_slug": "concepts/founder-liquidity-example"}]}diff --git a/test/fixtures/retrieval-quality/namedthing.jsonl b/test/fixtures/retrieval-quality/namedthing.jsonlindex bb5cffc8ab..7871fe47b3 100644--- a/test/fixtures/retrieval-quality/namedthing.jsonl+++ b/test/fixtures/retrieval-quality/namedthing.jsonl@@ -8,3 +8,5 @@{"family":"short-vs-rich","query":"indoor greek amphitheater for adversarial debate in the city","relevant":["projects/example-amphitheater"]}{"family":"graph-relationship","query":"who works on the civic platform","relevant":["people/alice-example"]}{"family":"hard-negative","query":"quarterly tax filing checklist","forbidden":["projects/example-amphitheater","projects/example-civic-platform"],"notes":"must NOT return the named projects"}+{"family":"concept-paraphrase","query":"what is the idea of debating in public forums","relevant":["projects/example-amphitheater"],"notes":"v0.46.8 Cat 13: definitional paraphrase, no title tokens — the vector-lean concept intent should recover it"}+{"family":"concept-paraphrase","query":"what do i know about civic engagement tooling","relevant":["projects/example-civic-platform"],"notes":"v0.46.8 Cat 13: know-about paraphrase, lowercase subject"}diff --git a/test/query-intent-concept.test.ts b/test/query-intent-concept.test.tsindex 5822996c24..d218dde5c2 100644--- a/test/query-intent-concept.test.ts+++ b/test/query-intent-concept.test.ts@@ -9,7 +9,7 @@*/import { describe, test, expect } from 'bun:test';-import { looksConceptShaped, conceptNudge } from '../src/core/search/query-intent.ts';+import { looksConceptShaped, conceptNudge, classifyQueryIntent, intentToDetail } from '../src/core/search/query-intent.ts';describe('#2416 — looksConceptShaped: concept/landscape queries → true', () => {const CONCEPT_SHAPED = [@@ -86,3 +86,43 @@ describe('#2416 — conceptNudge message', () => {expect(msg.length).toBeLessThan(320);});});++describe('v0.46.15 — classifyQueryIntent concept-guard branches (Cat 13)', () => {+ test('mid-sentence capital blocks concept: "What is Stripe Atlas?" → entity', () => {+ // Sentence-initial capitalization alone does not block; a proper noun+ // AFTER the first token is v1-conservative evidence of an entity lookup.+ expect(classifyQueryIntent('What is Stripe Atlas?')).toBe('entity');+ });++ test('definitional paraphrase without proper nouns → concept', () => {+ expect(classifyQueryIntent('What is the ownership economy?')).toBe('concept');+ expect(classifyQueryIntent('What are embeddings used for in retrieval?')).toBe('concept');+ });++ test('<3-word guard: bare two-word phrase never classifies concept', () => {+ expect(classifyQueryIntent('ownership economy')).toBe('general');+ });++ test("intentToDetail('concept') → undefined (concept never narrows detail)", () => {+ expect(intentToDetail('concept')).toBeUndefined();+ });+});++describe('v0.46.15 ship-review F5 — lowercase NAMES keep the entity tilt', () => {+ // The identity wave's own premise is that users type names lowercase; the+ // definitional concept cue must not cannibalize those lookups.+ test('status-verb queries about an entity are NOT concept', () => {+ expect(classifyQueryIntent('what is saoirse working on')).toBe('entity');+ expect(classifyQueryIntent('what is alice up to these days')).toBe('entity');+ });++ test('single-word lowercase subject is NOT concept (undecidable → entity)', () => {+ expect(classifyQueryIntent('what do i know about galewright')).toBe('entity');+ expect(classifyQueryIntent('what is kubernetes')).not.toBe('concept');+ });++ test('multi-word lowercase noun-phrase subjects stay concept', () => {+ expect(classifyQueryIntent('what do i know about founder liquidity')).toBe('concept');+ expect(classifyQueryIntent('what is the compounding advantage idea')).toBe('concept');+ });+});diff --git a/test/query-intent-legacy.test.ts b/test/query-intent-legacy.test.tsindex 971f311f66..82e886d2dc 100644--- a/test/query-intent-legacy.test.ts+++ b/test/query-intent-legacy.test.ts@@ -19,8 +19,13 @@ describe('classifyQueryIntent', () => {expect(classifyQueryIntent('Tell me about Brex')).toBe('entity');});- test('"What is the ownership economy?" → entity', () => {- expect(classifyQueryIntent('What is the ownership economy?')).toBe('entity');+ test('"What is the ownership economy?" → concept (RE-PINNED v0.46.15, Cat 13)', () => {+ // Was: → entity. That keyword tilt (kw×1.15 + exactMatch 1.25) on+ // definitional PARAPHRASES made hybrid lose to its own vector arm+ // (Cat 13: 47.0 vs 49.1 nDCG@5 on 500 paraphrase probes). Lowercase+ // subject + no proper noun = concept; "What is Stripe Atlas?" (mid-+ // sentence capital) stays entity.+ expect(classifyQueryIntent('What is the ownership economy?')).toBe('concept');});test('"Summarize Pedro" → entity', () => {diff --git a/test/retrieval-reflex-pre-v110.test.ts b/test/retrieval-reflex-pre-v110.test.tsnew file mode 100644index 0000000000..6f9507a18a--- /dev/null+++ b/test/retrieval-reflex-pre-v110.test.ts@@ -0,0 +1,40 @@+/**+ * Pre-v110 brains: page_aliases does not exist — the reflex resolver's other+ * arms must keep working (the alias probes swallow undefined-table).+ *+ * Own FILE, not a test inside retrieval-reflex.test.ts: this test DROPS+ * page_aliases, and "restoring" it via initSchema() is a trap under+ * GBRAIN_PGLITE_SNAPSHOT — the snapshot fast-path short-circuits initSchema,+ * the table never comes back, and every later alias test sharing the engine+ * fails with 42P01. A dedicated file's engine dies with the file.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resolveEntitiesToPointers } from '../src/core/context/retrieval-reflex.ts';+import { extractCandidates } from '../src/core/context/entity-salience.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++describe('pre-v110 brains (no page_aliases table)', () => {+ test('alias-table absence does not break the slug arm', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)+ VALUES ('people/alice-example', 'default', 'person', 'Alice Example', 'A founder.', '')`,+ [],+ );+ await engine.executeRaw('DROP TABLE IF EXISTS page_aliases');+ const block = await resolveEntitiesToPointers(engine, 'default', extractCandidates('about Alice Example'), {});+ expect(block).not.toBeNull();+ expect(block!.pointers[0].slug).toBe('people/alice-example');+ });+});diff --git a/test/retrieval-reflex.test.ts b/test/retrieval-reflex.test.tsindex f79e0c04c5..688758ef0f 100644--- a/test/retrieval-reflex.test.ts+++ b/test/retrieval-reflex.test.ts@@ -14,7 +14,7 @@ import { normalizeAlias } from '../src/core/search/alias-normalize.ts';import { resolveEntitiesToPointers } from '../src/core/context/retrieval-reflex.ts';import { extractCandidates } from '../src/core/context/entity-salience.ts';import { createGBrainContextEngine } from '../src/core/context-engine.ts';-import { disposeReflex } from '../src/core/context/reflex.ts';+import { disposeReflex, lexicalArmsEnabled } from '../src/core/context/reflex.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';let engine: PGLiteEngine;@@ -54,6 +54,109 @@ describe('resolveEntitiesToPointers', () => {expect(block!.text).toContain('use get_page');});+ test('weak-alias arm: a lowercase mention resolves via an exact unique alias (kta-pos variant 3)', async () => {+ await seed('people/saoirse-x', 'Saoirse X', 'A founder.');+ await engine.setPageAliases('people/saoirse-x', 'default', [normalizeAlias('saoirse')]);+ const candidates = extractCandidates('remind me what saoirse said about the round');+ expect(candidates.some((c) => c.weak)).toBe(true);+ const block = await resolveEntitiesToPointers(engine, 'default', candidates, {});+ expect(block).not.toBeNull();+ expect(block!.pointers).toHaveLength(1); // other lowercase words resolve nothing+ expect(block!.pointers[0].slug).toBe('people/saoirse-x');+ expect(block!.pointers[0].arm).toBe('alias');+ });++ test('kill switch: lexicalArms=false reproduces pre-wave resolution exactly', async () => {+ await seed('people/saoirse-x', 'Saoirse X', 'A founder.');+ await seed('people/ronan-galewright', 'Ronan Galewright', 'An investor.');+ await engine.setPageAliases('people/saoirse-x', 'default', [normalizeAlias('saoirse')]);+ const weakTurn = extractCandidates('remind me what saoirse said about the round');+ const surnameTurn = extractCandidates('Did Galewright ever follow up on that intro?');+ expect(await resolveEntitiesToPointers(engine, 'default', weakTurn, { lexicalArms: false })).toBeNull();+ expect(await resolveEntitiesToPointers(engine, 'default', surnameTurn, { lexicalArms: false })).toBeNull();+ });++ test('surname arm: unique person page resolves from a surname-only reference (kta-pos variant 4)', async () => {+ await seed('people/ronan-galewright', 'Ronan Galewright', 'An investor.');+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('Did Galewright ever follow up on that intro?'),+ {},+ );+ expect(block).not.toBeNull();+ expect(block!.pointers[0].slug).toBe('people/ronan-galewright');+ expect(block!.pointers[0].arm).toBe('title-surname');+ expect(block!.pointers[0].confidence).toBeGreaterThanOrEqual(0.7); // survives the volunteer gate+ expect(block!.pointers[0].matchedNorm).toBe(normalizeAlias('Galewright'));+ });++ test('surname arm: ambiguous surname (two people) injects nothing', async () => {+ await seed('people/ronan-galewright', 'Ronan Galewright', 'An investor.');+ await seed('people/mira-galewright', 'Mira Galewright', 'A founder.');+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('Did Galewright ever follow up?'),+ {},+ );+ expect(block).toBeNull();+ });++ test('surname arm: company tails are excluded by the person-type guard', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)+ VALUES ('companies/acme-labs', 'default', 'company', 'Acme Labs', 'A company.', '')`,+ [],+ );+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('Did Labs ever ship it?'),+ {},+ );+ expect(block).toBeNull();+ });++ test('surname arm: adversarial near-miss stays silent', async () => {+ await seed('people/elias-marrowfield', 'Elias Marrowfield', 'A founder.');+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('Did Marrowfielder ever reply?'),+ {},+ );+ expect(block).toBeNull();+ });++ test('weak-alias arm: cross-source ambiguity injects nothing (global uniqueness)', async () => {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'Other') ON CONFLICT DO NOTHING`, []).catch(() => {});+ await seed('people/saoirse-x', 'Saoirse X', 'A founder.');+ await seed('people/saoirse-y', 'Saoirse Y', 'Another person.', 'other');+ await engine.setPageAliases('people/saoirse-x', 'default', [normalizeAlias('saoirse')]);+ await engine.setPageAliases('people/saoirse-y', 'other', [normalizeAlias('saoirse')]);+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('remind me what saoirse said'),+ { sourceIds: ['default', 'other'] },+ );+ expect(block).toBeNull();+ });++ test('weak-alias arm: a phantom alias (deleted page) resolves nothing', async () => {+ await seed('people/ghost-page', 'Ghost Page', 'Gone.');+ await engine.setPageAliases('people/ghost-page', 'default', [normalizeAlias('ghostly')]);+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'people/ghost-page'`, []);+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('any update from ghostly today?'),+ {},+ );+ expect(block).toBeNull();+ });+test('alias arm resolves an unambiguous single-slug hit', async () => {await seed('people/swami-x', 'Swami X', 'A close friend.');await engine.setPageAliases('people/swami-x', 'default', [normalizeAlias('Swami')]);@@ -96,16 +199,11 @@ describe('resolveEntitiesToPointers', () => {expect(block!.pointers.length).toBe(2);});- test('pre-v110 brains: alias-table absence does not break the slug arm', async () => {- await seed('people/alice-example', 'Alice Example', 'A founder.');- // Simulate no page_aliases table.- await engine.executeRaw('DROP TABLE IF EXISTS page_aliases');- const block = await resolveEntitiesToPointers(engine, 'default', extractCandidates('about Alice Example'), {});- expect(block).not.toBeNull();- expect(block!.pointers[0].slug).toBe('people/alice-example');- // restore for other tests- await engine.initSchema();- });+ // The pre-v110 alias-table-absence case lives in its own file+ // (test/retrieval-reflex-pre-v110.test.ts): it DROPS page_aliases, and+ // "restoring" via initSchema() is a trap under GBRAIN_PGLITE_SNAPSHOT —+ // the snapshot fast-path short-circuits initSchema, the table never comes+ // back, and every later alias test in the sharing file fails with 42P01.});describe('context-engine assemble() — Retrieval Reflex integration', () => {@@ -152,15 +250,38 @@ describe('context-engine assemble() — Retrieval Reflex integration', () => {workspaceDir: '/tmp/rr-test-ws-3',resolveEntities: async () => { called = true; return null; },});+ // Re-pinned for the v0.46.15 identity wave: the turn must be GENUINELY+ // candidate-free (stopwords / sub-3-char tokens only) — lowercase words+ // like "help" are now WEAK candidates and legitimately reach the+ // resolver's alias arm.const res = await ce.assemble({sessionId: 's3',- messages: [{ role: 'user', content: 'can you help me with this?' }],+ messages: [{ role: 'user', content: 'can you do it?' }],});expect(called).toBe(false);expect(res.systemPromptAddition).not.toContain('Brain pages mentioned this turn');});});+ test('weak-only smalltalk reaches the resolver but yields no pointer block', async () => {+ await withEnv(REFLEX_ON, async () => {+ let called = false;+ const ce = createGBrainContextEngine({+ workspaceDir: '/tmp/rr-test-ws-3b',+ resolveEntities: async (candidates) => {+ called = true;+ return resolveEntitiesToPointers(engine, 'default', candidates, {});+ },+ });+ const res = await ce.assemble({+ sessionId: 's3b',+ messages: [{ role: 'user', content: 'can you help me with this?' }],+ });+ expect(called).toBe(true); // "help" is a weak candidate — alias-arm-restricted+ expect(res.systemPromptAddition).not.toContain('Brain pages mentioned this turn');+ });+ });+test('suppression uses PRIOR turns only, not the current message', async () => {await withEnv(REFLEX_ON, async () => {await seed('people/alice-example', 'Alice Example', 'A founder.');@@ -437,3 +558,116 @@ describe('windowTurnCount — knob edge semantics', () => {});});});++describe('lexicalArmsEnabled — kill-switch resolution (env > config > default-ON)', () => {+ const cfg = (o: object) => o as import('../src/core/config.ts').GBrainConfig;++ test('defaults ON with no env and no config', async () => {+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: undefined }, async () => {+ expect(lexicalArmsEnabled(null)).toBe(true);+ expect(lexicalArmsEnabled(cfg({}))).toBe(true);+ });+ });++ test('config file-plane key disables and re-enables', async () => {+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: undefined }, async () => {+ expect(lexicalArmsEnabled(cfg({ retrieval_reflex_lexical_arms: false }))).toBe(false);+ expect(lexicalArmsEnabled(cfg({ retrieval_reflex_lexical_arms: true }))).toBe(true);+ });+ });++ test('env beats config in BOTH directions (incident escape hatch)', async () => {+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: 'false' }, async () => {+ expect(lexicalArmsEnabled(cfg({ retrieval_reflex_lexical_arms: true }))).toBe(false);+ });+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: '0' }, async () => {+ expect(lexicalArmsEnabled(null)).toBe(false);+ });+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: 'true' }, async () => {+ expect(lexicalArmsEnabled(cfg({ retrieval_reflex_lexical_arms: false }))).toBe(true);+ });+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: '1' }, async () => {+ expect(lexicalArmsEnabled(cfg({ retrieval_reflex_lexical_arms: false }))).toBe(true);+ });+ });++ test('empty-string env falls through to config (not treated as set)', async () => {+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: '' }, async () => {+ expect(lexicalArmsEnabled(cfg({ retrieval_reflex_lexical_arms: false }))).toBe(false);+ expect(lexicalArmsEnabled(null)).toBe(true);+ });+ });++ test('incident-hatch parse is case-insensitive with common negatives (F11)', async () => {+ for (const v of ['FALSE', 'False', 'OFF', 'off', 'No', ' 0 ']) {+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: v }, async () => {+ expect(lexicalArmsEnabled(null)).toBe(false);+ });+ }+ await withEnv({ GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS: 'TRUE' }, async () => {+ expect(lexicalArmsEnabled(cfg({ retrieval_reflex_lexical_arms: false }))).toBe(true);+ });+ });+});++describe('v0.46.15 ship-review hardening (adversarial F1/F2 + stale-alias veto)', () => {+ test('F1: a title-claimed namesake still makes the bare surname AMBIGUOUS', async () => {+ // Jane resolves via title; the bare "Galewright" must count BOTH holders+ // and stay silent — classification precedence must not hand John the+ // "unique" surname slot (wrong-person injection at above-gate confidence).+ await seed('people/jane-galewright', 'Jane Galewright', 'A founder.');+ await seed('people/john-galewright', 'John Galewright', 'Her brother.');+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('Jane Galewright mentioned it. Did Galewright follow up?'),+ {},+ );+ expect(block).not.toBeNull();+ const slugs = block!.pointers.map((p) => p.slug);+ expect(slugs).toContain('people/jane-galewright'); // title arm+ expect(slugs).not.toContain('people/john-galewright'); // surname stays ambiguous+ expect(block!.pointers.every((p) => p.arm !== 'title-surname')).toBe(true);+ });++ test('stale-alias veto: a deleted page\'s leftover alias row cannot veto the sole live target', async () => {+ await seed('people/saoirse-x', 'Saoirse X', 'A founder.');+ await seed('people/saoirse-old', 'Saoirse Old', 'Renamed away.');+ await engine.setPageAliases('people/saoirse-x', 'default', [normalizeAlias('saoirse')]);+ await engine.setPageAliases('people/saoirse-old', 'default', [normalizeAlias('saoirse')]);+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'people/saoirse-old'`, []);+ const block = await resolveEntitiesToPointers(+ engine,+ 'default',+ extractCandidates('remind me what saoirse said about the round'),+ {},+ );+ expect(block).not.toBeNull();+ expect(block!.pointers).toHaveLength(1);+ expect(block!.pointers[0].slug).toBe('people/saoirse-x');+ });++ test('F2: weak fold goes FAIL-CLOSED when any source\'s alias lookup fails', async () => {+ // Alias registered in two sources = ambiguous = must inject nothing.+ // If one source's lookup transiently fails, the survivor must NOT look+ // unique — partial visibility cannot manufacture uniqueness.+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path) VALUES ('other', 'Other', '/tmp/other') ON CONFLICT (id) DO NOTHING`, []).catch(() => {});+ await seed('people/saoirse-x', 'Saoirse X', 'A founder.');+ await engine.setPageAliases('people/saoirse-x', 'default', [normalizeAlias('saoirse')]);+ // (In reality 'other' also has the alias, but its lookup fails.)+ const shim = {+ resolveAliases: (norms: string[], opts?: { sourceId?: string }) =>+ opts?.sourceId === 'other'+ ? Promise.reject(new Error('transient blip'))+ : engine.resolveAliases(norms, opts),+ executeRaw: (sql: string, params: unknown[]) => engine.executeRaw(sql, params),+ } as unknown as typeof engine;+ const block = await resolveEntitiesToPointers(+ shim,+ 'default',+ extractCandidates('remind me what saoirse said'),+ { sourceIds: ['default', 'other'] },+ );+ expect(block).toBeNull();+ });+});diff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.tsindex 3d72a9696a..d4cf79dc84 100644--- a/test/search-alias-resolved-boost.test.ts+++ b/test/search-alias-resolved-boost.test.ts@@ -89,7 +89,7 @@ describe('alias_resolved boost stage', () => {});describe('KNOBS_HASH_VERSION', () => {- it('is 17 (15→16 detail fold #3515; 16→17 degradation-stamp epoch: pre-stamp cache rows become unreachable)', () => {- expect(KNOBS_HASH_VERSION).toBe(17);+ it('is 18 (16→17 degradation-stamp epoch; 17→18 autocut weak-top floor #1863)', () => {+ expect(KNOBS_HASH_VERSION).toBe(18);});});diff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex 5058970a16..6516294c7f 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -70,6 +70,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {reranker_timeout_ms: 5000,floor_ratio: undefined,title_boost: 1.25,+ evidence_cosine_floor: 0.8,...CROSS_MODAL_DEFAULTS,graph_signals: false,...CR_DISABLED_DEFAULT,@@ -77,6 +78,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {// v0.42.3.0 — autocut OFF for conservative (no reranker).autocut: false,autocut_jump: 0.2,+ autocut_min_top: 0.35,// v0.43 — relational recall OFF for conservative.relationalRetrieval: false,relational_retrieval_depth: 2,@@ -102,6 +104,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {reranker_timeout_ms: 5000,floor_ratio: undefined,title_boost: 1.25,+ evidence_cosine_floor: 0.8,...CROSS_MODAL_DEFAULTS,graph_signals: true,...CR_DISABLED_DEFAULT,@@ -109,6 +112,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {// v0.42.3.0 — autocut ON.autocut: true,autocut_jump: 0.2,+ autocut_min_top: 0.35,// v0.43 — relational recall ON for balanced.relationalRetrieval: true,relational_retrieval_depth: 2,@@ -132,6 +136,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {reranker_timeout_ms: 5000,floor_ratio: undefined,title_boost: 1.25,+ evidence_cosine_floor: 0.8,...CROSS_MODAL_DEFAULTS,graph_signals: true,...CR_DISABLED_DEFAULT,@@ -139,6 +144,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {// v0.42.3.0 — autocut ON.autocut: true,autocut_jump: 0.2,+ autocut_min_top: 0.35,// v0.43 — relational recall ON for tokenmax.relationalRetrieval: true,relational_retrieval_depth: 2,@@ -422,7 +428,8 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// not survive a `reindex-search-vector` switch.// #3515: bumped 15→16 to fold the effective detail level (det=) — a// detail=low write must not be served to a detail=medium lookup.- expect(KNOBS_HASH_VERSION).toBe(17);+ // v0.46.15 (#1863): bumped 17→18 to fold the autocut weak-top floor (acm=).+ expect(KNOBS_HASH_VERSION).toBe(18);});test('#3515: detail set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -439,7 +446,8 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {expect(unset).toBe(medium);// WP2/T3: bumped 16→17 for the degradation-stamp epoch — cache rows now// carry degraded[]/retrieved_count; pre-stamp rows must not claim clean.- expect(KNOBS_HASH_VERSION).toBe(17);+ // v0.46.15 (#1863): 17→18 — autocut weak-top floor folds in (acm=).+ expect(KNOBS_HASH_VERSION).toBe(18);});test('T1 (codex): floor_ratio set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -604,8 +612,8 @@ describe('v0.40.4 — graph_signals knob', () => {});describe('v0.42.3.0 — autocut knobs', () => {- test('KNOBS_HASH_VERSION is 17 (15→16 detail fold #3515; 16→17 degradation-stamp epoch)', () => {- expect(KNOBS_HASH_VERSION).toBe(17);+ test('KNOBS_HASH_VERSION is 18 (16→17 degradation-stamp epoch; 17→18 autocut weak-top floor #1863)', () => {+ expect(KNOBS_HASH_VERSION).toBe(18);});test('bundle defaults: conservative off, balanced/tokenmax on @0.20', () => {@@ -709,3 +717,36 @@ describe('v0.43 — relational recall knobs', () => {expect(on).not.toBe(off);});});++describe('v0.46.15 — retrieval-wave knobs (evidence_cosine_floor + autocut_min_top)', () => {+ test('loadOverridesFromConfig parses both new keys with [0,1] range guards', () => {+ expect(loadOverridesFromConfig({ 'search.evidence_cosine_floor': '0.75' }).evidence_cosine_floor).toBe(0.75);+ expect(loadOverridesFromConfig({ 'search.evidence_cosine_floor': '1.5' }).evidence_cosine_floor).toBeUndefined();+ expect(loadOverridesFromConfig({ 'search.evidence_cosine_floor': '-0.1' }).evidence_cosine_floor).toBeUndefined();+ expect(loadOverridesFromConfig({ 'search.evidence_cosine_floor': 'cheese' }).evidence_cosine_floor).toBeUndefined();+ expect(loadOverridesFromConfig({ 'search.autocut_min_top': '0.5' }).autocut_min_top).toBe(0.5);+ expect(loadOverridesFromConfig({ 'search.autocut_min_top': '0' }).autocut_min_top).toBe(0);+ expect(loadOverridesFromConfig({ 'search.autocut_min_top': '2' }).autocut_min_top).toBeUndefined();+ expect(loadOverridesFromConfig({ 'search.autocut_min_top': '-1' }).autocut_min_top).toBeUndefined();+ });++ test('SEARCH_MODE_CONFIG_KEYS includes both new keys', () => {+ expect(SEARCH_MODE_CONFIG_KEYS).toContain('search.evidence_cosine_floor');+ expect(SEARCH_MODE_CONFIG_KEYS).toContain('search.autocut_min_top');+ });++ test('autocut_min_top participates in knobsHash (acm=) — cache key bifurcates', () => {+ const base = knobsHash(resolveSearchMode({ mode: 'balanced' }));+ const tuned = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { autocut_min_top: 0.5 } }));+ expect(base).not.toBe(tuned);+ });++ test('evidence_cosine_floor is label-only — deliberately NOT in knobsHash', () => {+ // The floor relabels evidence strings on already-fetched results; it never+ // changes WHICH rows come back, so folding it into the cache key would+ // fragment the cache for zero isolation benefit.+ const base = knobsHash(resolveSearchMode({ mode: 'balanced' }));+ const relabeled = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { evidence_cosine_floor: 0.5 } }));+ expect(relabeled).toBe(base);+ });+});diff --git a/test/search/autocut-eval.test.ts b/test/search/autocut-eval.test.tsindex d32970d6bd..726ea3cf77 100644--- a/test/search/autocut-eval.test.ts+++ b/test/search/autocut-eval.test.ts@@ -195,3 +195,32 @@ describe('autocut eval gate (D2 — precision lift without recall regression)',}});});++describe('v0.46.15 (#1863) — weak-top floor', () => {+ const scoreOfR = (r: { rerank_score?: number }) => r.rerank_score;+ const mkScores = (scores: number[]) => scores.map((s, i) => ({ id: i, rerank_score: s }));++ test('the #1863 collapse case: weak top (0.317) no longer manufactures a confident cliff', () => {+ // Rare cross-source query: every score is low; the old normalization by+ // the weak top made ordinary decay look like a >=20% cliff and collapsed+ // the list to 1. The floor keeps the full cluster.+ const weak = mkScores([0.317, 0.21, 0.19, 0.18, 0.15]);+ const r = applyAutocut(weak, scoreOfR, { ...DEFAULT_AUTOCUT });+ expect(r.decision.applied).toBe(false);+ expect(r.kept.length).toBe(5);+ });++ test('strong-top cliffs still cut exactly as before', () => {+ const strong = mkScores([0.95, 0.92, 0.31, 0.12]);+ const r = applyAutocut(strong, scoreOfR, { ...DEFAULT_AUTOCUT });+ expect(r.decision.applied).toBe(true);+ expect(r.kept.length).toBe(2);+ });++ test('floor is tunable: 0 disables it (pre-wave behavior)', () => {+ const weak = mkScores([0.317, 0.05]);+ const r = applyAutocut(weak, scoreOfR, { ...DEFAULT_AUTOCUT, minTopScore: 0 });+ expect(r.decision.applied).toBe(true);+ expect(r.kept.length).toBe(1);+ });+});diff --git a/test/search/autocut.test.ts b/test/search/autocut.test.tsindex 2b1cd22724..0867518505 100644--- a/test/search/autocut.test.ts+++ b/test/search/autocut.test.ts@@ -18,7 +18,7 @@ import {// items survived the cut.type R = { id: string; rs?: number };const scoreOf = (r: R) => r.rs;-const ON: AutocutConfig = { enabled: true, jumpRatio: 0.2, minKeep: 1 };+const ON: AutocutConfig = { enabled: true, jumpRatio: 0.2, minKeep: 1, minTopScore: 0.35 };function mk(scores: Array<number | undefined>): R[] {return scores.map((rs, i) => ({ id: `r${i}`, rs }));@@ -29,6 +29,7 @@ describe('DEFAULT_AUTOCUT', () => {expect(DEFAULT_AUTOCUT.enabled).toBe(true);expect(DEFAULT_AUTOCUT.jumpRatio).toBe(0.2);expect(DEFAULT_AUTOCUT.minKeep).toBe(1);+ expect(DEFAULT_AUTOCUT.minTopScore).toBe(0.35);});test('is frozen', () => {expect(Object.isFrozen(DEFAULT_AUTOCUT)).toBe(true);@@ -230,3 +231,17 @@ describe('resolveAutocut — precedence ladder', () => {expect(cfg.enabled).toBe(false); // inherited from config (partial didn't set it)});});++describe('autocutFromConfig — search.autocut_min_top (v0.46.15)', () => {+ test('parses valid [0,1] values (0 disables the weak-top floor)', () => {+ expect(autocutFromConfig({ search: { autocut_min_top: 0.5 } }).minTopScore).toBe(0.5);+ expect(autocutFromConfig({ search: { autocut_min_top: 0 } }).minTopScore).toBe(0);+ expect(autocutFromConfig({ search: { autocut_min_top: 1 } }).minTopScore).toBe(1);+ });++ test('out-of-range / non-numeric values fall through to the default', () => {+ expect(autocutFromConfig({ search: { autocut_min_top: 1.5 } }).minTopScore).toBeUndefined();+ expect(autocutFromConfig({ search: { autocut_min_top: -0.1 } }).minTopScore).toBeUndefined();+ expect(autocutFromConfig({ search: { autocut_min_top: 'cheese' } }).minTopScore).toBeUndefined();+ });+});diff --git a/test/search/concept-weights.test.ts b/test/search/concept-weights.test.tsnew file mode 100644index 0000000000..fc24e0e49d--- /dev/null+++ b/test/search/concept-weights.test.ts@@ -0,0 +1,133 @@+/**+ * v0.46.15 (Cat 13) — concept-intent vector-lean weights, DELTA-asserted.+ *+ * The measured defect: definitional paraphrases classified `entity` and got+ * the keyword tilt, making hybrid LOSE to its own vector arm (47.0 vs 49.1+ * nDCG@5 on 500 paraphrase probes). This test builds the minimal+ * discriminating corpus:+ *+ * - concept page: semantic match ONLY (paraphrase body, no query tokens;+ * chunk embedded at the query's basis dim → vector arm votes it)+ * - decoy page: lexical match ONLY (query tokens in title-grain FTS ++ * chunk text; chunk embedded at a far dim → keyword/title arms vote it)+ *+ * and asserts the DIRECTION FLIPS with the concept weights:+ * intentWeighting off (general weights) → the decoy wins top-1+ * intentWeighting on (concept weights) → the concept page wins top-1+ *+ * Hermetic: in-memory PGLite + the deterministic queryEmbedFn seam (the+ * v0.46.5.0 canary hook). No keys, no network.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway } from '../../src/core/ai/gateway.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import { classifyQueryIntent } from '../../src/core/search/query-intent.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';++const DIM = 1536;+const QUERY = 'what is the compounding advantage idea';+const QUERY_DIM = 12;++let engine: PGLiteEngine;++beforeAll(async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: DIM,+ env: {},+ });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ // Concept page: pure-paraphrase body (ZERO query-token overlap), embedded+ // at the query's dim. Title tokens deliberately disjoint from the query.+ await engine.putPage('concepts/durable-moat-example', {+ type: 'concept',+ title: 'Durable Moat Example',+ compiled_truth: 'a moat that grows stronger the longer it persists, snowballing returns from early wins',+ timeline: 'a moat that grows stronger the longer it persists, snowballing returns from early wins',+ });+ await engine.upsertChunks('concepts/durable-moat-example', [+ {+ chunk_index: 0,+ chunk_text: 'a moat that grows stronger the longer it persists, snowballing returns from early wins',+ chunk_source: 'compiled_truth',+ embedding: basisEmbedding(QUERY_DIM, DIM),+ token_count: 16,+ },+ ]);++ // Decoy page: query tokens everywhere lexical (title + timeline + chunk),+ // embedded at a FAR dim (vector arm never votes it).+ await engine.putPage('notes/compounding-advantage-idea-notes', {+ type: 'note',+ title: 'compounding advantage idea',+ compiled_truth: 'the compounding advantage idea came up in notes',+ timeline: 'the compounding advantage idea came up: compounding advantage idea',+ });+ await engine.upsertChunks('notes/compounding-advantage-idea-notes', [+ {+ chunk_index: 0,+ chunk_text: 'the compounding advantage idea came up: compounding advantage idea',+ chunk_source: 'compiled_truth',+ embedding: basisEmbedding(512, DIM),+ token_count: 12,+ },+ ]);+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++describe('concept-intent weights (Cat 13)', () => {+ test('the query classifies as concept', () => {+ expect(classifyQueryIntent(QUERY)).toBe('concept');+ });++ test('DIRECTIONAL DELTA: concept weights measurably close the gap to the lexical decoy', async () => {+ // The tilt is deliberately subtle (±10-20% on RRF k), so a top-1 flip+ // fixture would be knife-edge and flaky by construction. What the k math+ // GUARANTEES is direction: with concept weights (vec k 60→50, kw k+ // 60→66.7) the semantic page's score RATIO vs the lexical decoy strictly+ // improves. The authoritative top-1 lift claim is Cat 13's pre-merge+ // keyed validation (500 paraphrase probes), not this fixture.+ const run = (intentWeighting: boolean) =>+ hybridSearch(engine, QUERY, {+ limit: 5,+ intentWeighting,+ queryEmbedFn: () => basisEmbedding(QUERY_DIM, DIM),+ });++ const off = await run(false);+ const on = await run(true);++ const ratio = (rs: Awaited<ReturnType<typeof run>>) => {+ const concept = rs.find((r) => r.slug === 'concepts/durable-moat-example');+ const decoy = rs.find((r) => r.slug === 'notes/compounding-advantage-idea-notes');+ expect(concept).toBeDefined();+ expect(decoy).toBeDefined();+ return concept!.score / decoy!.score;+ };++ const offRatio = ratio(off);+ const onRatio = ratio(on);+ // Concept weights close the gap by a real margin (~20% in the k math);+ // assert >8% so boost-stage noise can't flake it while a weight+ // regression (concept tilt lost/reversed) still fails hard.+ expect(onRatio).toBeGreaterThan(offRatio * 1.08);+ });++ test('the raw cosine survives to the result (evidence contract feed)', async () => {+ const on = await hybridSearch(engine, QUERY, {+ limit: 5,+ intentWeighting: true,+ queryEmbedFn: () => basisEmbedding(QUERY_DIM, DIM),+ });+ const concept = on.find((r) => r.slug === 'concepts/durable-moat-example');+ expect(concept?.cosine).toBeCloseTo(1.0, 5);+ });+});diff --git a/test/search/evidence.test.ts b/test/search/evidence.test.tsindex 49c53f832b..56a55aebc4 100644--- a/test/search/evidence.test.ts+++ b/test/search/evidence.test.ts@@ -19,9 +19,22 @@ describe('classifyEvidence precedence', () => {test('exact_title_match when title boost fired', () => {expect(classifyEvidence(r({ title_match_boost: 1.25, base_score: 0.2 }))).toBe('exact_title_match');});- test('high_vector_match at/above HIGH_MATCH_FLOOR', () => {- expect(classifyEvidence(r({ base_score: HIGH_MATCH_FLOOR }))).toBe('high_vector_match');- expect(classifyEvidence(r({ base_score: 0.90 }))).toBe('high_vector_match');+ test('RE-PINNED (v0.46.15, #3963): a high BLENDED score without a real cosine is NOT a vector match', () => {+ // Was: base_score >= HIGH_MATCH_FLOOR → high_vector_match. That let a+ // keyword+boost pile-up read as confident semantic evidence (the exact+ // bug class this wave fixes). Without a cosine, the ceiling is+ // keyword_exact / create_safety 'probable' — the safe direction.+ expect(classifyEvidence(r({ base_score: HIGH_MATCH_FLOOR }))).toBe('keyword_exact');+ expect(classifyEvidence(r({ base_score: 0.90 }))).toBe('keyword_exact');+ });+ test('high_vector_match fires ONLY on a real cosine at/above the floor', () => {+ expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.85 }))).toBe('high_vector_match');+ expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.8 }))).toBe('high_vector_match');+ expect(classifyEvidence(r({ base_score: 0.95, cosine: 0.5 }))).toBe('keyword_exact');+ });+ test('cosine floor is overridable (per-model calibration knob)', () => {+ expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.7 }), { cosineFloor: 0.65 })).toBe('high_vector_match');+ expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.7 }), { cosineFloor: 0.9 })).toBe('weak_semantic');});test('keyword_exact in the solid band', () => {expect(classifyEvidence(r({ base_score: SOLID_MATCH_FLOOR }))).toBe('keyword_exact');@@ -30,8 +43,15 @@ describe('classifyEvidence precedence', () => {test('weak_semantic below the solid floor (the incident: 0.64 body chunk... 0.5 here)', () => {expect(classifyEvidence(r({ base_score: 0.4 }))).toBe('weak_semantic');});- test('falls back to score when base_score absent', () => {- expect(classifyEvidence(r({ score: 0.95, base_score: undefined }))).toBe('high_vector_match');+ test('RE-PINNED (v0.46.15): score fallback without cosine caps at keyword_exact', () => {+ expect(classifyEvidence(r({ score: 0.95, base_score: undefined }))).toBe('keyword_exact');+ });+ test('keyless fall-through: no cosine anywhere → create_safety never claims exists via vector', () => {+ const rs = [r({ base_score: 0.99 }), r({ base_score: 0.7 })];+ stampEvidence(rs);+ expect(rs[0].evidence).toBe('keyword_exact');+ expect(rs[0].create_safety).toBe('probable'); // degraded from 'exists' — safe direction+ expect(rs[1].create_safety).toBe('probable');});});diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.tsindex b32956c75c..707f02b6ce 100644--- a/test/search/knobs-hash-reranker.test.ts+++ b/test/search/knobs-hash-reranker.test.ts@@ -44,7 +44,7 @@ function baseKnobs(): ResolvedSearchKnobs {}describe('KNOBS_HASH_VERSION + version invariants', () => {- test('version is 17 (…; 12→13 embedding-provider migration #3390; 14→15 FTS language; 15→16 detail fold #3515; 16→17 degradation stamp)', () => {+ test('version is 18 (…; 15→16 detail fold #3515; 16→17 degradation stamp; 17→18 autocut weak-top floor #1863)', () => {// v0.35.0.0: 1→2 to fold reranker fields. v0.35.6.0: 2→3 to fold// floor_ratio. v0.36 wave: piggybacks on v=3 with 7 cross-modal knobs// (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).@@ -75,7 +75,7 @@ describe('KNOBS_HASH_VERSION + version invariants', () => {// write must not be served to a detail=medium lookup.// WP2/T3: 16→17 degradation-stamp epoch — cache rows now carry// degraded[]/retrieved_count; pre-stamp rows must not claim clean.- expect(KNOBS_HASH_VERSION).toBe(17);+ expect(KNOBS_HASH_VERSION).toBe(18);});test('hash is 16 hex chars regardless of reranker config', () => {diff --git a/test/search/searchvector-escalation.test.ts b/test/search/searchvector-escalation.test.tsnew file mode 100644index 0000000000..7ee285ccde--- /dev/null+++ b/test/search/searchvector-escalation.test.ts@@ -0,0 +1,124 @@+/**+ * v0.46.15 — searchVector bounded pagination escalation (retrieval-cathedral+ * P1, outside-voice R2-10).+ *+ * The bug: innerLimit counted CHUNKS before the best-per-page DISTINCT+ * collapse. One dense page with 100+ strong chunks consumed the entire+ * candidate pool, so the PAGE result came back underfilled — sparse pages+ * behind the dense one were unreachable at any limit.+ *+ * The fix: escalate innerLimit ×4 (≤3 times, hard-capped at the HNSW+ * ef_search substrate ceiling of 1000) while the page set is short but the+ * pre-collapse candidate pool was FULL. A short page with a non-full pool is+ * a genuine final page — no retry. Exhaustion at the cap emits+ * onVectorPoolMeta (visible, not silent).+ *+ * PGLite side of the engine-parity pair; the postgres side is pinned by+ * test/e2e/engine-parity.test.ts.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway } from '../../src/core/ai/gateway.ts';+import type { ChunkInput } from '../../src/core/types.ts';++let engine: PGLiteEngine;++const DIM = 1536;++/** Unit vector with cosine-similarity `cos` against basis direction 0. */+function gradedEmb(cos: number, otherDim: number): Float32Array {+ const e = new Float32Array(DIM);+ e[0] = cos;+ e[otherDim % DIM] = Math.sqrt(Math.max(0, 1 - cos * cos));+ return e;+}++function basisEmbedding(idx: number): Float32Array {+ const e = new Float32Array(DIM);+ e[idx % DIM] = 1.0;+ return e;+}++beforeAll(async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: DIM,+ env: { ...process.env },+ });+ engine = new PGLiteEngine();+ await engine.connect({}); // in-memory+ await engine.initSchema();++ // Dense page: 120 chunks, all closer to the query than any sparse page.+ // Pre-fix, these 120 fill the 100-chunk inner pool alone → 1 result page.+ await engine.putPage('notes/dense', {+ type: 'note',+ title: 'Dense Page',+ compiled_truth: 'dense.',+ });+ const denseChunks: ChunkInput[] = Array.from({ length: 120 }, (_, i) => ({+ chunk_index: i,+ chunk_text: `dense chunk ${i}`,+ chunk_source: 'compiled_truth' as const,+ embedding: gradedEmb(0.99 - i * 0.0005, 10 + i),+ token_count: 3,+ }));+ await engine.upsertChunks('notes/dense', denseChunks);++ // 15 sparse pages, one weaker chunk each — reachable only past the dense wall.+ for (let p = 0; p < 15; p++) {+ const slug = `notes/sparse-${String(p).padStart(2, '0')}`;+ await engine.putPage(slug, { type: 'note', title: `Sparse ${p}`, compiled_truth: 'sparse.' });+ await engine.upsertChunks(slug, [+ {+ chunk_index: 0,+ chunk_text: `sparse ${p}`,+ chunk_source: 'compiled_truth',+ embedding: gradedEmb(0.6 - p * 0.001, 400 + p),+ token_count: 2,+ },+ ]);+ }+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++describe('searchVector bounded escalation', () => {+ test('a dense page can no longer starve the page result (escalates past the chunk wall)', async () => {+ const results = await engine.searchVector(basisEmbedding(0), { limit: 10, detail: 'high' });+ const slugs = results.map((r) => r.slug);+ expect(new Set(slugs).size).toBe(slugs.length); // per-page pooled — no dup pages+ expect(results.length).toBe(10); // pre-fix: 1 (the dense page only)+ expect(slugs[0]).toBe('notes/dense'); // strongest page still first+ expect(slugs.filter((s) => s.startsWith('notes/sparse-')).length).toBe(9);+ });++ test('a genuine short corpus does NOT escalate forever and emits nothing', async () => {+ const events: unknown[] = [];+ // limit far above what the corpus can yield (16 pages total): the pool+ // goes non-full at the first escalation that swallows the whole corpus,+ // and the loop stops WITHOUT an exhaustion event.+ const results = await engine.searchVector(basisEmbedding(0), {+ limit: 50,+ detail: 'high',+ onVectorPoolMeta: (m) => events.push(m),+ });+ expect(results.length).toBe(16); // every page, once+ expect(events).toHaveLength(0);+ });++ test('offset paging past the end returns empty without an exhaustion event', async () => {+ const events: unknown[] = [];+ const results = await engine.searchVector(basisEmbedding(0), {+ limit: 10,+ offset: 500,+ detail: 'high',+ onVectorPoolMeta: (m) => events.push(m),+ });+ expect(results.length).toBe(0);+ expect(events).toHaveLength(0);+ });+});diff --git a/test/volunteer-context.test.ts b/test/volunteer-context.test.tsindex 97c6f7262d..353d209a4f 100644--- a/test/volunteer-context.test.ts+++ b/test/volunteer-context.test.ts@@ -277,6 +277,21 @@ describe('gateVolunteeredPointers — direct unit (the pure gate step)', () => {});expect(pages).toEqual([]);});++ test('title-surname arm clears the 0.70 gate unboosted and renders a surname rationale (R2-7)', () => {+ const block: PointerBlock = {+ pointers: [+ { display: 'Galewright', slug: 'people/ronan-galewright', source_id: 'default', synopsis: 'z', arm: 'title-surname', confidence: 0.72 },+ ],+ text: 'B',+ };+ // Empty candidate map: no salience boost — the arm's base 0.72 alone must+ // survive the 0.70 volunteer floor (the reason it isn't 0.65).+ const pages = gateVolunteeredPointers(block, new Map(), { windowSize: 1 });+ expect(pages).toHaveLength(1);+ expect(pages[0].confidence).toBeCloseTo(0.72);+ expect(pages[0].rationale).toContain('surname match "Galewright"');+ });});describe('volunteerUsageStats', () => {@@ -490,7 +505,10 @@ describe('window-cap ordering — the newest user mention survives the cap', (){ role: 'assistant', text: `consider ${stale}.` },{ role: 'user', text: 'actually ask Alice Example first' },]);- expect(cands.length).toBeLessThanOrEqual(CAP);+ // Re-pinned for the v0.46.15 identity wave: the STRONG cap is what this+ // test pins; lowercase weak candidates ("consider", "ask", …) ride a+ // separate alias-arm-restricted budget and never evict strong ones.+ expect(cands.filter((c) => !c.weak).length).toBeLessThanOrEqual(CAP);const alice = cands.find((c) => normalizeAlias(c.query) === normalizeAlias('Alice Example'));expect(alice).toBeDefined();// Recency + user-role weighting puts the newest user mention FIRST.