Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-218 A1: integrate identity and enforcement lanes; docs, BEHAVIOR_CHANGES rows, CHANGELOG [Unreleased], key files, config key registration
garrytand40d77363433
diff --git a/AGENTS.md b/AGENTS.mdindex 2ba1f7b089..d6fe7cb511 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -174,6 +174,11 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contwrapper). Wrapper and rules:[cron-schedule.md](docs/guides/cron-schedule.md#calling-gbrain-unattended),[scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout).+- **Keep a page to some members of a shared source:** put `readable_by: [alice-example, group:team-a]` in its+ frontmatter and bind each member's credential (`gbrain access member add`, `gbrain auth rescope --token <name>+ --member <id>`); `gbrain access check --token <name>` and `--as <member>` preview what a member reads. A remote+ `not_found` may be a restricted page: check `whoami` before telling the user there are no notes+ ([Model C](docs/tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).- **Delete or purge pages:** `gbrain delete --purge` skips the 72-hour softdelete, cascades to chunks, versions, links and facts, and `gbrain restore`cannot undo it. Purge only on the user's explicit go for that purge ("scrubdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex fd10aab7d2..ea15b1acac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,28 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**A shared brain can now keep a page to the members it names, inside one source. Put `readable_by: [alice-example, group:team-a]` in a page's frontmatter, bind each member's token, OAuth client or stdio server to a member, and remote reads of that page answer only for them. Nothing changes until a page names readers or a member is created.**++### What changed++| Situation | Before | Now |+|---|---|---|+| A page names `readable_by` | ignored: every remote caller granted the source read it | read remotely only by a credential bound to a listed member (directly or through a group); everyone else gets the canonical `not_found` on every read path, and a remote write to it answers `page_not_found` |+| Escape hatches and `--private-pages granted-sources` | relaxed `visibility: private` | still relax only `visibility: private`; they never open a page to an unlisted member |+| A `visibility: private` page that also names readers | hidden remotely | still hidden from a listed member unless that member's credential also has `--private-pages granted-sources` |+| Atoms, concepts and chronicle events derived from a restricted page | followed the origin's visibility | readable by no remote caller |+| Members and groups | | `gbrain access member add\|disable\|enable\|rm\|list`, `gbrain access group add\|rm\|list`, `gbrain access who-can-read <slug>`, `gbrain access check --token\|--client <name>`; `--member` and `--may-act-for` on `auth create`, `auth rescope` and `auth register-client`; config `mcp.stdio_member` for a stdio server; `--as <member>` previews one member's view from the local CLI; `whoami` and `grant_diagnosis` show member and groups |+| Doctor | | `access_readers_malformed`, `access_unknown_readers`, `access_recent_narrowings`, `access_page_readers_backfill` |++### What to watch for after you upgrade++- A page that already carried `readable_by` before this release reads as nobody remotely until you run `gbrain repair access` (preview) and then `gbrain repair access --apply`. Doctor's `access_page_readers_backfill` lists them.+- On a brain with any restriction, the escape hatches no longer turn the remote read filter off, and secondary surfaces (proactive brief, retrieval reflex, entity resolution, known-as-of) hide restricted pages from every remote caller, listed members included.+- A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).+- Works the same on a repo-less brain: members, groups and bindings live in the database.+## [0.60.453.0] - 2026-10-25**A shared brain can now let each member's agent read that member's own private pages, and nobody else's. Access tokens and OAuth clients have a new private-pages grant: `none` for every token and client, existing or new, so remote reads keep hiding `visibility: private` pages exactly as before until the brain host opts a connection in with `gbrain auth rescope --token <name> --private-pages granted-sources` (or `--client <client_id>`). An opted-in connection then reads private pages only in the sources its grant names.**diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex a7c8384cf3..792fded123 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/arm-confidence.ts` — arm-confidence-weighted fusion for the keyword arm (`search.keyword_arm_confidence_floor`; `null` = off in every bundle — the pre-registered Cat 13 E2 mechanism FAILED its held-out rule at the calibrated floor 0.6121 (53.0 → 53.0), so the knob ships default off for operators and the receipt is published). `keywordArmConfidence(rows)` reads the strict keyword arm's raw `score` column into a scale-free statistic (`top`, `second`, `margin_ratio`; TypeScript-side — engines still return raw `ts_rank × sourceFactor`, no SQL change); `decideKeywordArmWeight({keywordList, floor, vectorArmVoted, relationalQuery})` down-weights the keyword AND title fusion entries to `KEYWORD_ARM_WEAK_WEIGHT` (0.5) only when the floor is set, the keyword list is non-empty, a text vector arm voted, the query is not relational, and `margin_ratio < floor`; otherwise it emits no weight (byte-identical fusion). It is called from `composeFusionLists` (`fusion-lists.ts`) so the weight lands through the same per-list `weight` primitive as the expansion budget, never a k change. `normalizeKeywordArmConfidenceFloor` is the ONE range contract (number in `(0, 1]` or a string parsing to one; `null`/`false`/`off` → `null`; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`. The decision (`{top, second, margin_ratio, downweighted}`) is surfaced as `HybridSearchMeta.keyword_arm_confidence` even with the floor off, so a calibration run can pick a floor from per-probe receipts; knobs-hash part `kacf=`. Pinned by `test/search/arm-confidence.test.ts` (pure contract) and `test/search/arm-confidence-hybrid.test.ts` (hermetic PGLite: a weak keyword arm is down-weighted only with the floor set; off is byte-identical).-- `src/core/search/autocut.ts` (OFF in every bundle since rule R2; `search.autocut true` re-enables it where the reranker runs) — 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, when enabled, runs ONLY where the reranker ran (`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 default reranker; a default-reranker change 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`/`autocut_min_keep` (`autocut` false in every bundle since rule R2 — the LongMemEval replay from the captured post-rerank pool found no floor that beat autocut off; jump 0.20 stays the sensitivity when re-enabled; floor 1 in every mode — `search.autocut_min_keep` sets the minimum result count a cut may leave, resolved through the same bundle → config → per-call chain) 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). 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 || r.exact_lookup !== undefined || r.relational_pinned === true` so a canonical page injected by `applyAliasHop` after reranking (no `rerank_score`), an exact-lookup tier hit, or a relational row re-pinned by `pinRelationalRows` (low cross-encoder score by construction; ALSO excluded from the cliff computation through `scoreOf`, so text-row autocut is unchanged by the pin) 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`, `search.autocut_min_keep`. The `DEFAULT_AUTOCUT` module constant is unchanged (`enabled=true`) for operators who re-enable it; the cliff logic is 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 loss 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/autocut.ts` (OFF in every bundle since rule R2; `search.autocut true` re-enables it where the reranker runs) — 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, when enabled, runs ONLY where the reranker ran (`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 default reranker; a default-reranker change 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`/`autocut_min_keep` (`autocut` false in every bundle since rule R2 — the LongMemEval replay from the captured post-rerank pool found no floor that beat autocut off; jump 0.20 stays the sensitivity when re-enabled; fl... (line truncated to 2000 chars)- `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).@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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 both survive), (3) no page type exceeds 60% of results — only when the candidates span several page types; a homogeneous set passes unchanged, since dropping one of three distinct LongMemEval `note` sessions only loses multi-session recall (pinned in `test/dedup.test.ts`), (4) max 2 chunks per page (default; `hybrid.ts`'s two-pass structural expansion widens it; with `regions` (`segmentRegions`: one query, only when a page has over 2 results; passed by `hybrid.ts` and both keyword-only paths) a segmented page applies (1) and (4) per occurrence cluster (gaps over 1 MiB split) and keeps at most `MAX_PER_SEGMENTED_PAGE` 6), (5) at least 1 compiled_truth chunk per page — the best one is APPENDED (never swapped over a kept chunk, so matching evidence survives) and the output re-sorted by score, which slice / token budget / evidence consumers assume. Every layer keys pages by `pageKey()` (source_id, slug), so slug collisions across sources can't collapse recall.- `src/core/search/diverse-pool.ts` — the session-diverse candidate pool before the reranker, `search.diverse_pool_depth` (integer 0..100, `off` = 0; 0 in every bundle, so off by default). With N > 0: every retrieval arm fetches at least N candidates (`hybrid/request.ts` passes `max(PRE_FUSION_POOL_FLOOR, N)` as the `perArmPoolLimit` floor; still capped at `MAX_SEARCH_LIMIT` unless an eval pool depth is set), `capPerSession` keeps the first row of each session in the deduped pool (`hybrid/rank.ts` `capSessionPool`, called on `dedupResults`' output; a session is `sessionPrefix(slug)` from `graph-signals.ts`, else the page, keyed with the source id) and `rerankAndPin` raises the reranker's `topNIn` to at least N. The keyword-only paths have no reranker and are unchanged. `normalizeDiversePoolDepth` is the one range contract (mode.ts config parse and the `gbrain config set` refusal through `search/config-values.ts`); the mode field folds into `knobsHash` as an append-only `dpd=` part only when on. Motivation and measurement: BEAM-1M S1 in gbrain-evals (`docs/benchmarks/2026-10-12-beam-1m-s1-fixes.md`): at depth 100 on BEAM-1M dev (voyage-4, balanced reranker) strict recall at 10 rose 76 → 83 of 198 (+3.5 points, 95% interval [0, +6.6]) and at 5 was flat (55 → 56), with search p50 latency 340 → 455 ms and about 4x the rerank tokens per query; the preregistered flip rule needed an interval above zero, so every bundle keeps 0. Tests: `test/search/diverse-pool.test.ts`, `test/search/diverse-pool-hybrid.serial.test.ts`.-- `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). Engine column routing is covered by `test/e2e/embedding-column-pglite.test.ts`, `test/e2e/embedding-column-postgres.test.ts` and `test/cosine-rescore-column.test.ts`. Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image vectors travel in their own INSERT column; malformed registry JSON is forgiven like loadConfigWithEngine; unregistered names throw the paste-ready error), and `vectorCastSuffix(resolved)` is the placeholder-free `'::vector' | '::halfvec(N)'` cast shared by the read fragment builder and the write path so the two casts can't drift. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts`.+- `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). Engine column routing is covered by `test/e2e/embedding-column-pglite.test.ts`, `test/e2e/embedding-column-postgres.test.ts` and `test/cosine-rescore-column.test.ts`. Write side: `resolveWriteColumnFromConfigRows({searchEmbeddingColumn, embeddingColumnsJson})` resolves upsertChunks's active write target from the raw DB-plane config rows through the same registry/validation chain (legacy `embedding` descriptor when neither row routes elsewhere; `embedding_image` falls back to the legacy text column since image v... (line truncated to 2000 chars)- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator. The `vector` strategy runs the production query path: `embedQuery` (query-side `input_type` on asymmetric providers) in the resolved embedding column's model, searched on that column — `embed()` is the document side and would handicap the vector baseline.@@ -31,11 +31,11 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field; also prints the raw query↔chunk cosine (`SearchResult.cosine`, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. `formatResultsExplain(results, meta?)` prepends header lines from the captured retrieval meta when present — `formatAutocutSummary` (the autocut decision) and `formatDegradedSummary(meta.degraded)`, which renders the closed `degraded[]` vocabulary as `degraded: reranker_skipped (no_key)` (null when the run was clean); `cli.ts:formatResult` threads `lastRetrievalMeta` into it, so a silently skipped reranker is visible from the CLI. Pinned by `test/search/explain-formatter.test.ts` + `test/cli-explain-degraded-render.test.ts`. `formatDecideSummary` prints one `decide <slot>:` line per slot that ran (all-off: none), including the slot's answer summary (S2 label, S4 probability and verdict). `formatTimingsSummary` (stage-timings.ts) adds the `timings:` line.-- `src/core/search/fusion-lists.ts` — the ONE composition point for `hybridSearch`'s RRF inputs. Every vector recall list is a ROLE-tagged arm (`VectorArm {list, role: 'original'|'variant'|'clause'|'image'}`, appended only via `pushVectorList`) — never a parallel index-aligned array, since the `allSettled` salvage path drops failed arms and the both-mode image branch fails open, so positional rules mis-tag lists. `composeFusionLists({arms, keywordFusionList, titleFusionList, relationalList, includeRelational, ks, knobs})` returns the complete weighted list set (`FusionListEntry {list, k, weight?}`) in the fixed order vector arms → keyword (`keywordK`) → title (`keywordK`, only if non-empty) → relational (`baseRrfK`, only if non-empty and not image modality): text arms fuse at `textRrfK` and the image arm at `imageRrfK` only when BOTH kinds are present, otherwise every arm at `vectorK` (text, image-only, unified, and a both-mode whose image branch fell open). `variant`/`clause` arms share `expansionVariantBudget` as total RRF weight — `weight_i = b / n_voting_arms` over the NON-EMPTY expansion arms (an empty list casts no vote), the `original` arm always weight 1; a `null` budget emits no `weight` key, byte-identical to unweighted fusion; when the original is missing every surviving text arm is a `variant` sharing the budget. `rrfFusionWeighted` (hybrid.ts) scores `weight / (k + rank)` (weighted RRF: a list-level multiplier at every rank). `textArmsNonEmpty` is the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count). `normalizeExpansionVariantBudget` is the single range contract for the knob: finite `(0, 4]` (or a string parsing to one) → number, `null`/`legacy`/`null`-literal → null, anything else → `undefined` (fall through to config → bundle); shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`, so an invalid per-call value never reaches fusion or the cache key. `interleaveFusion(arms, key, limit)`: score-free round-robin (each arm's #1, then #2, deduped by key, cut at `limit`) for fact supersession candidates (`facts.candidate_fusion`); hybrid search stays on RRF (`test/search/interleave-fusion.test.ts`). Pure, no engine/IO. Pinned by `test/search/fusion-lists.test.ts` (knife-edge arithmetic at budget 1.0, legacy deep-equals the pre-role text mapping, role alignment under rejected arms), `test/search/expansion-variant-budget.test.ts` (hermetic directional PGLite test), and the both-mode demotion-gate regression in `test/keyword-relaxed-fusion.serial.test.ts`.+- `src/core/search/fusion-lists.ts` — the ONE composition point for `hybridSearch`'s RRF inputs. Every vector recall list is a ROLE-tagged arm (`VectorArm {list, role: 'original'|'variant'|'clause'|'image'}`, appended only via `pushVectorList`) — never a parallel index-aligned array, since the `allSettled` salvage path drops failed arms and the both-mode image branch fails open, so positional rules mis-tag lists. `composeFusionLists({arms, keywordFusionList, titleFusionList, relationalList, includeRelational, ks, knobs})` returns the complete weighted list set (`FusionListEntry {list, k, weight?}`) in the fixed order vector arms → keyword (`keywordK`) → title (`keywordK`, only if non-empty) → relational (`baseRrfK`, only if non-empty and not image modality): text arms fuse at `textRrfK` and the image arm at `imageRrfK` only when BOTH kinds are present, otherwise every arm at `vectorK` (text, image-only, unified, and a both-mode whose image branch fell open). `variant`/`clause` arms share `expansionVariantBudget` as total RRF weight — `weight_i = b / n_voting_arms` over the NON-EMPTY expansion arms (an empty list casts no vote), the `original` arm always weight 1; a `null` budget emits no `weight` key, byte-identical to unweighted fusion; when the original is missing every surviving text arm is a `variant` sharing the budget. `rrfFusionWeighted` (hybrid.ts) scores `weight / (k + rank)` (weighted RRF: a list-level multiplier at every rank). `textArmsNonEmpty` is the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count). `normalizeExpansionVariantBudget` is the single range contract for the knob: finite `(0, 4]` (or a string parsing to one) → number, `null`/`legacy`/`null`-literal → null, anything else → `undefined` (fall through to config → bundle); shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`, so an invalid per-call value never reaches fusion or the cache key. `interleaveFusion(arms, key,... (line truncated to 2000 chars)- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.-- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` (`search/cosine-rescore.ts`) scores the active column in SQL with the JS rules (a failure falls back to JS and sets `cosine_rescore`), and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).+- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` (`search/cosine-rescore.ts`) scores the active column in SQL with the JS rules (a failure falls back to JS and sets `cosine_rescore`), and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_sea... (line truncated to 2000 chars)Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). `hybridSearch` and `hybridSearchCached` are short orchestrators over the named stages in `src/core/search/hybrid/` (next entry); the file keeps the post-fusion boosts, RRF, cosine rescore, the cache-write drainer and the public helpers.- `src/core/search/hybrid/` — hybridSearch pipeline stages. `startVectorSide` runs modality, expansion and the vector arms alongside the lexical and relational arms (`runLexicalAndRelational`) on its own timer branch, `degraded` list and `vectorPoolMetaSink`; `joinVectorSide` merges its stamps and `expansionApplied` after the lexical ones, so `degraded[]` keeps the sequential order. Every other stage runs in a fixed order: `request.ts` (`resolveHybridRequest` builds a `HybridRequest` once: mode, embedding column, limits (per-arm pool from `perArmPoolLimit` in `src/core/search/eval-pool-depth.ts`: today's max(2·limit, floor, offset+limit) capped at 100 unless an eval sets `--eval-pool-depth`), intent, `searchOpts`, identity-tier opts, and the accumulators `vectorPoolUnderfill` / `expansionApplied` / `lastResultsCount` / `lastRank1Score` that stages write only as `req.<field>`; `emitHybridMeta`, `applyIdentityBoosts`), `arms.ts` (lexical, relational, modality + expansion, vector arms), `keyword-only.ts` (the no-provider and all-vector-arms-empty return paths; `opts.decide.keywordOnly`, the System One S6 fire retrieval, takes the no-provider path on purpose without the vector-unavailable degraded marker or warning), `rank.ts` (fusion + post-fusion boosts, A2 expansion, rerank + relational pin, identity tiers + adaptive return + autocut + relational slot, main return), `cache-stages.ts` (hybridSearchCached mode resolution, semantic-cache handle, skip gate, hit path; the result cache stays hard-disabled), `degraded.ts`, `effective-modes.ts`, `rerank-gate.ts` (the W3 pre-rerank grade; see the `crag.ts` entry in Core Search 2/2). The orchestrators wrap each stage in `req.timer` / `opts._timings` (stage-timings.ts). Stages import public helpers back from `hybrid.ts` at call time only (the `exact-lookup.ts` pattern); `hybrid.ts` exports nothing new. Pinned by `test/hybrid-golden.test.ts` (exact `(id, score)`, cold and warm).@@ -58,23 +58,18 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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/metadata-boost-gate.ts` — the ONE parse + decision contract for `search.metadata_boost_gate` (`always` | `lexical`; every bundle is `lexical`, `DEFAULT_METADATA_BOOST_GATE` stays `always` so a knobs literal without the field keeps its pre-wave hash identity). `lexicalArmsVoted` answers "did a strict keyword, title-phrase or relational row fuse?" from the composed fusion lists (relaxed OR-fallback rows do not count — they are already demoted); `decideMetadataBoosts({gate, lexicalVoted})` returns `{gate, lexical_voted, boosts_applied, reason: 'gate_always'|'lexical_voted'|'vector_only_voter'|'image_modality'}`. Image-modality queries are exempt from the gate: `hybridSearch` never runs the keyword / title arms for an image query and excludes the relational arm, so their lexical arms never vote by construction and `lexical` would silently disable the boosts for the whole modality — the caller passes `modality` (from `effectiveModality`) and an image decision applies the boosts as before (reason `image_modality`). Under `lexical`, `hybridSearch` passes `skipMetadataBoosts` into `runPostFusionStages` so the backlink, salience, recency (+chronicle), graph-signal and alias-resolved boosts are skipped when the vector arm was the only voter; supersede downrank, exact-match boost, title-phrase boost, compiled-truth boost, cosine re-score, dedup, reranker and autocut are untouched either way. Receipt (Cat 13 conceptual recall, sibling repo): the E1 localization showed hub pages carrying 1.03–1.12x backlink / graph-adjacency / recency boosts over gold concept pages that carried none whenever both lexical arms were empty; the pre-registered E3 held-out arm moved gbrain from 53.0 to 57.8 nDCG@5 (rule ≥ 57.0) with NamedThingBench, BrainBench, the retrieval canary and the LongMemEval dev slice byte-identical, so the gate flipped to `lexical` in all three bundles. The decision is surfaced as `HybridSearchMeta.metadata_boost_gate` (`--explain`); knobs-hash part `mbg=`; override chain per-call `metadataBoostGate` → config → bundle (`normalizeMetadataBoostGate` is the shared parser, garbage falls through). Pinned by `test/search/metadata-boost-gate.test.ts` (pure contract, hash participation, resolution chain) and `test/search/metadata-boost-gate-hybrid.test.ts` (hermetic PGLite hub-vs-gold corpus: `always` reproduces the hub-first regression, the default yields gold-first, config and per-call planes, unparseable falls through).+- `src/core/search/metadata-boost-gate.ts` — the ONE parse + decision contract for `search.metadata_boost_gate` (`always` | `lexical`; every bundle is `lexical`, `DEFAULT_METADATA_BOOST_GATE` stays `always` so a knobs literal without the field keeps its pre-wave hash identity). `lexicalArmsVoted` answers "did a strict keyword, title-phrase or relational row fuse?" from the composed fusion lists (relaxed OR-fallback rows do not count — they are already demoted); `decideMetadataBoosts({gate, lexicalVoted})` returns `{gate, lexical_voted, boosts_applied, reason: 'gate_always'|'lexical_voted'|'vector_only_voter'|'image_modality'}`. Image-modality queries are exempt from the gate: `hybridSearch` never runs the keyword / title arms for an image query and excludes the relational arm, so their lexical arms never vote by construction and `lexical` would silently disable the boosts for the whole modality — the caller passes `modality` (from `effectiveModality`) and an image decision applies the boosts as before (reason `image_modality`). Under `lexical`, `hybridSearch` passes `skipMetadataBoosts` into `runPostFusionStages` so the backlink, salience, recency (+chronicle), graph-signal and alias-resolved boosts are skipped when the vector arm was the only voter; supersede downrank, exact-match boost, title-phrase boost, compiled-truth boost, cosine re-score, dedup, reranker and autocut are untouched either way. Receipt (Cat 13 conceptual recall, sibling repo): the E1 localization showed hub pages carrying 1.03–1.12x backlink / graph-adjacency / recency boosts over gold concept pages that carried none whenever both lexical arms were empty; the pre-registered E3 held-out arm moved gbrain from 53.0 to 57.8 nDCG@5 (rule ≥ 57.0) with NamedThingBench, BrainBench, the retrieval canary and the LongMemEval dev slice byte-identical, so the gate flipped to `lexical` in all three bundles. The decision is surfaced as `HybridSearchMeta.metadata_boost_gate` (`--explain`); knobs-hash part `mbg... (line truncated to 2000 chars)-- `src/core/search/mode.ts` — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. `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 registered search knobs 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`. `query_cache` rows written under an older hash version hash differently — natural row segregation, cleared 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). `KNOB_CONFIG_KEY` (a `Record<keyof ModeBundle, string>`, so every knob names the `search.*` key `loadOverridesFromConfig` reads it from) is the single knob→key map: `SEARCH_MODE_CONFIG_KEYS` derives from it, `attributeKnob` prints it as the override `source_detail`, and `KNOWN_CONFIG_KEYS` in `config.ts` hand-mirrors it (config.ts stays import-light; `test/config-search-registry.test.ts` pins the two equal), 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. `keywordOrFallback: boolean` knob in `ModeBundle` (default true in all three bundles; config `search.keywordOrFallback`): the keyword arm's AND→OR zero-recall retry — corpora the FTS config can't stem (CJK/agglutinative text under `'english'`) can turn it off because the OR retry has no IDF demotion and its common-token hits read as noise in the RRF blend; folds into `knobsHash` as a `kof=` part. `KnobsHashContext` additionally carries the EFFECTIVE per-call salience/recency boost modes (`sal=`/`rec=` — explicit `SearchOpts` ?? the classifier's auto-suggestion, resolved by the same chain bare `hybridSearch` uses) and the per-engine `search.intent_patterns` config fingerprint (`ipat=`, from `query-intent.ts`'s `intentPatternFingerprint`; threaded through ctx, never read process-globally, so a multi-engine process can't key one brain's rows under another brain's patterns) — a reordered or reclassified write can never serve a differently-configured lookup. Cache HITS slice the stored page to the same resolved result count as misses (per-call `limit` → the mode's `searchLimit`) in `hybridSearchCached`, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely. `expansion_variant_budget: number | null` knob in `ModeBundle` (`null` in all three bundles; config `search.expansion_variant_budget` accepts `legacy`/`null` or a number in (0, 4] through the ONE range contract `normalizeExpansionVariantBudget` in `fusion-lists.ts` — out-of-range falls through to the bundle; per-call `HybridSearchOpts.expansionVariantBudget`, normalized by the same function in both the inner search and the cache resolver): the total RRF weight the NON-EMPTY expansion variant/clause lists share at fusion (`weight_i = b / n_voting_arms`; the original list always keeps weight 1), `null` = legacy weight 1 on every list (byte-identical fusion), a no-op when `expansion` is off. It folds into `knobsHash` as the last, append-only `evb=` part (`legacy` or the budget to 3 decimals) — `KNOBS_HASH_VERSION` is 29 with that part in — so a budget-weighted write can never serve a legacy lookup. `KNOB_NULL_LABELS` + `formatKnobValue` in `modes-report.ts` render its legitimate null as `legacy (null)` in `gbrain search modes` (plain `(undefined)` stays reserved for genuinely unset knobs). `relational_rerank_pin: number` knob in `ModeBundle` (3 in all three bundles — a no-op under `conservative`, which has no reranker; config `search.relational_rerank_pin` accepts `off`/`0` or an integer in [0, 10] through the ONE range contract `normalizeRelationalRerankPin` in `relational-rerank-pin.ts`, out-of-range falls through to the bundle; per-call `SearchOpts.relationalRerankPin`, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rows `pinRelationalRows` re-pins above the reranked text rows after `applyReranker`. It folds into `knobsHash` as the append-only `rrp=` part, riding `KNOBS_HASH_VERSION` 29 together with `evb=` (one bump per wave — both parts landed before v29 shipped; a partial-knobs literal without the field hashes as the bundle default), so a pin-3 write can never serve a pin-0 lookup. Pinned by `test/search-mode.test.ts` (bundle snapshots + hash pins), `test/search/knobs-hash-reranker.test.ts` (the version comment chain), `test/config-adaptive-return-keys.test.ts`, `test/search/modes-report-coverage.test.ts`.+- `src/core/search/mode.ts` — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. `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 registered search knobs 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`. `query_cache` rows written under an older hash version hash differently — natural row segregation, cleared 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_... (line truncated to 2000 chars)- `src/core/search/mode-advice.ts` — the one source of the search-mode recommendation (`RECOMMENDED_SEARCH_MODE`, `MODE_REASONS`) and the copy that states it: the downstream-input cost matrix priced from `model-pricing.ts` (`costMatrixLines`, `costMatrixSentence` for init's first-run decision), the picker's `[AGENT]` banner, the post-upgrade banner and `QUERY_EXPANSION_LINE`; `search.mode_source` (`auto` | `operator`). `INSTALL_FOR_AGENTS.md` Step 3.5 carries the matrix verbatim (pinned by `test/init-mode-picker.test.ts`).- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.-- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`source_markdown_slug`) is private; the fact-list reads in `engine-sql/facts.ts` (by entity, since, keyset, session, supersessions, trajectory) apply it behind `FactListOpts.excludePrivate` / `TrajectoryOpts.excludePrivate`, which every remote fact surface resolves with `resolveExcludePrivatePages` (`test/remote-fact-list-private-provenance.test.ts`, both engines). Remote fact writes apply the same predicate behind an `excludePrivate` option: `forget` (`guardRemoteForget`, the row lock in `persistence/memory-mutations.ts`, `recordFactWithdrawal`, `similarActiveAfterForget`) and `remember` (`decideSingleFact`'s exact and cosine arms, `decideReplacement`), so a fact remote reads hide is `not_found` to a remote write and never matched as its duplicate (`test/remote-fact-write-private-provenance.test.ts`, both engines). Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.+- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`s... (line truncated to 2000 chars)+- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originRestrictedSql`). Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`.- `src/core/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only) or unknown; LIMIT 1 arms walk the v161 pending index, not pages. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. A pass that changed fewer than 50 + 10% of the sampled pages leaves the statistics alone once they exist (the projection statistic and, on Postgres, every `SEARCH_STATISTICS_COLUMNS` column: `missingSearchStatistics`), and PGLite then analyzes only the hot tables its row deltas mark stale. On Postgres it also samples the page columns search filters read (`SEARCH_PAGE_STATISTICS_SQL`) and the chunk `SEARCH_STATISTICS_COLUMNS`; a vacuum holding a table defers it (analyze-lock.ts). `refreshChunkStatistics` runs the chunk step after a drain that changed 50 + 10% of chunks (any sans statistics): without them the vector candidate statement sorts every eligible chunk instead of walking the HNSW index (`test/e2e/vector-chunk-statistics-postgres.test.ts`). Absent search statistics (pg_upgrade, a deleted pg_statistic; 50-60 s searches at 5k pages) get `ensureSearchStatistics`: PostgresEngine runs it once per engine in the background on its first pool search (never awaited; disconnect waits), and doctor `planner_stats_stale` plus `repair planner-stats` report and apply the same refresh (`test/search-statistics-guard.test.ts`).- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`, and skips the key/config setup (merged config, cache config, intent-pattern state) so the wrapper adds no engine round-trips; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.--- `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 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/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults. Link reads skip non-ranking link types (`rankingLinkSql`). `readChainHop` (behind `BrainEngine.relationalChainHop`) is one oriented, authorized, bounded expansion step of a multi-hop chain: fenced LATERAL link scans and primary-key page lookups (a statistics-less planner otherwise joins pages on source_id quadratically), relationship page-type signatures (`stored` / `flipped` / `uncertain`; frontmatter, manual and attendance-section links keep stored direction), logical-edge collapse, `neighborCap` per frontier page, degree saturating at `CHAIN_DEGREE_SATURATION` (300) link rows, and edge context only from pages whose text the caller may read. Pinned by `test/relational-chain.test.ts`, `test/relational-chain-hub.slow.test.ts` and the engine-parity chain case.--- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex b09fefc7df..b35a1ce085 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -185,9 +185,12 @@ per-member tokens for that, and `source_ids` to narrow further.### Lay out sources by who may read them-gbrain enforces access per source, never per page. Two pages in one source are-readable by exactly the same tokens. So put content in sources by who may read-it, before any member's bot connects:+Source grants are the coarse boundary: without page readers, two pages in one+source are readable by exactly the same tokens. Inside one source, a page that+names readers in frontmatter `readable_by` is read only by credentials bound to+a listed member ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape));+it only narrows a grant, never widens it. Either way, put content in sources by+who may read it, before any member's bot connects:- **One source per channel, team or member.** Give a channel's pages a sourceof their own (`channel-a`), a team's documents theirs (`team-a`), and eachdiff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 667359feb0..350c01f6c7 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -233,8 +233,12 @@ For one bot acting for several members of a shared brain, give each member aseparate client or token restricted to that member's sources. The grant is thesecurity boundary; a request's `source_ids` can only narrow inside it. See[a bot acting for many members](../guides/multi-source-brains.md#a-bot-acting-for-many-members).-Access is per source, never per page, so lay sources out by who may read them+Grants are per source, so lay sources out by who may read them([guide](../guides/multi-source-brains.md#lay-out-sources-by-who-may-read-them)).+Inside one source, bind each member's credential with `gbrain auth rescope+--token <name> --member <id>` (or `--client`) and put `readable_by` on the pages+only some members may read; `gbrain access check --token <name>` shows the+result ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).New `memory-reader`, `memory-writer` and `coding-agent` grants are callable andlisted on the full surface; their operation snapshot is still the ceiling, so adiff --git a/llms-full.txt b/llms-full.txtindex 3d1563f19e..2f9ed195bb 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1933,6 +1933,11 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contwrapper). Wrapper and rules:[cron-schedule.md](docs/guides/cron-schedule.md#calling-gbrain-unattended),[scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout).+- **Keep a page to some members of a shared source:** put `readable_by: [alice-example, group:team-a]` in its+ frontmatter and bind each member's credential (`gbrain access member add`, `gbrain auth rescope --token <name>+ --member <id>`); `gbrain access check --token <name>` and `--as <member>` preview what a member reads. A remote+ `not_found` may be a restricted page: check `whoami` before telling the user there are no notes+ ([Model C](docs/tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).- **Delete or purge pages:** `gbrain delete --purge` skips the 72-hour softdelete, cascades to chunks, versions, links and facts, and `gbrain restore`cannot undo it. Purge only on the user's explicit go for that purge ("scrubdiff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.mdindex afcc57ddc8..d2cd67ebf2 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md@@ -26,6 +26,9 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.+A remote `not_found` or a short result may be a page whose `readable_by` excludes+this credential: check `whoami` (member, groups) before telling the user there are no notes.+## When to switch brainSwitch brain (`--brain <id>`) when:diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.mdindex afcc57ddc8..d2cd67ebf2 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md@@ -26,6 +26,9 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.+A remote `not_found` or a short result may be a page whose `readable_by` excludes+this credential: check `whoami` (member, groups) before telling the user there are no notes.+## When to switch brainSwitch brain (`--brain <id>`) when:diff --git a/plugin/skills/conventions/brain-routing.md b/plugin/skills/conventions/brain-routing.mdindex afcc57ddc8..d2cd67ebf2 100644--- a/plugin/skills/conventions/brain-routing.md+++ b/plugin/skills/conventions/brain-routing.md@@ -26,6 +26,9 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.+A remote `not_found` or a short result may be a page whose `readable_by` excludes+this credential: check `whoami` (member, groups) before telling the user there are no notes.+## When to switch brainSwitch brain (`--brain <id>`) when:diff --git a/skills/conventions/brain-routing.md b/skills/conventions/brain-routing.mdindex afcc57ddc8..d2cd67ebf2 100644--- a/skills/conventions/brain-routing.md+++ b/skills/conventions/brain-routing.md@@ -26,6 +26,9 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.+A remote `not_found` or a short result may be a page whose `readable_by` excludes+this credential: check `whoami` (member, groups) before telling the user there are no notes.+## When to switch brainSwitch brain (`--brain <id>`) when:diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex a5a22106e2..74e10b4942 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1269,6 +1269,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.452.0', id: 'sources_not_readable_gbra156', text: 'An unscoped `search`, `query`, `recall` or `list_pages` from a token or agent connection with no source grant that comes back empty, while every source it can read holds no page and other sources do, now carries a `sources_not_readable` notice (kind degraded). It says the empty result is not proof of absence, never names a hidden source, and its fix is `gbrain sources federate <source>` on the brain host, or a grant for the token. Granted tokens and OAuth clients never get it.' },{ since: '0.60.452.0', id: 'sources_add_federation_warning_gbra156', text: '`gbrain sources add` without `--federated` or `--no-federated` now warns on stderr that the new source is not federated, so a remote token or agent connection with no source grant cannot read its pages, and names `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`. The stored default is still non-federated.' },{ since: 'TBD', id: 'private_pages_granted_sources_gbra156', text: 'Access tokens and OAuth clients have a new private-pages grant, `none` for every existing and new token and client, so remote reads still hide `visibility: private` pages until the brain host opts a connection in: `gbrain auth rescope --token <name> --private-pages granted-sources` (or `--client <id>`) lets it read private pages in the sources its grant names, and only those. A token with no source grant, federated sources the grant does not name and a request\'s `source_ids` never add one; `context_pack`, `delta` and writes keep hiding private pages. `--private-pages none` turns it off on the next request.' },+ { since: 'TBD', id: 'member_read_access_gbra218', text: 'A page whose frontmatter names readers (`readable_by: [alice-example, group:team-a]`) is now read remotely only by a token, OAuth client or stdio server bound to a listed member (`gbrain access member add`, `gbrain auth rescope --token <name> --member <id>`, config `mcp.stdio_member`). Every other remote caller gets the same `not_found` as for a missing page, including unbound credentials, a `--private-pages granted-sources` bot and both escape hatches (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), which relax only `visibility: private`. A malformed `readable_by` reads as nobody, and a page derived from a restricted page reads as nobody remotely. Pages that already named `readable_by` before this upgrade read as nobody remotely until `gbrain repair access` (preview, then `--apply`). The local CLI is unchanged; `--as <member>` previews one member\'s view.' },+ { since: 'TBD', id: 'member_access_hatch_scope_gbra218', text: 'On a brain where any page names readers or any member exists, the escape hatches no longer turn the remote read filter off: remote reads still hide pages the caller\'s member is not listed on, and secondary surfaces that use the identity-free filter (proactive brief, retrieval reflex, entity resolution, known-as-of) hide every restricted page and keep hiding `visibility: private` pages under a hatch. A brain with no restriction keeps the old hatch behaviour exactly. A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex 0c53200966..c3d29c47ca 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -20,4 +20,5 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['serve.cli_socket', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve answers CLI reads over a private Unix socket, default off'serve.vector_prewarm', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve prewarms the HNSW indexes into shared_buffers at start when they fit, default off'mcp.stdio_member', // access/caller.ts (GBRA-218): binds a local stdio MCP server to one member; unbound, stdio reads no page that names readers+ 'access.restrictions_present', // search/private-visibility.ts (GBRA-218): '1' once a page names readers or a member exists (set by a migration trigger; sticky)];