Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-156 harness wave: vector scope parity tests, remote page cap, sources_not_readable refusal (WIP)

garrytanfa7232c6c7fa
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index d161240d0d..eb4b3e7758 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -23,7 +23,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook (document mode, exit 0; the event records `command`, `version`, `guard: 'document'` and `exit_code: 0`, never argv values; `outcome` keeps its value, #6629/D26). The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.
- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.
- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. With the call's `_meta.retrieval.coverage`, `degradedRecallNotice` leaves `projection_pending` out when no pending page could match the query, otherwise names the count in its why, and escalates when it is the only stage. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `privateFactNotice` (#6606: a local... (line truncated to 2000 chars)
-- `src/core/unreadable-sources-notice.ts` — `unreadableSourcesNotice`, dispatch's producer of the per-call `sources_not_readable` notice (kind degraded): an unscoped `search`/`query`/`recall`/`list_pages` from a connection with no source grant (no `allowedSources`, `hasSourceGrant` not true, no stdio binding; OAuth clients always carry a grant) that came back empty while its `federatedSearchScope` holds no live page and another live source does. The why says the result is not proof of absence and never names a hidden source; the fix is the host's `gbrain sources federate <source>` (input `source`), with the token grant named in the why. Never throws (`test/mcp-unreadable-sources-notice.test.ts`).
+- `src/core/sources-not-readable.ts` — `assertUnscopedReadReachesPages`, the `sources_not_readable` refusal (class host_only) dispatch runs before the handler: an unscoped `search`/`query`/`recall`/`list_pages` (no `source_id`, no non-empty `source_ids`) from a remote connection with no source grant (no `allowedSources`, `hasSourceGrant` not true, no stdio binding; OAuth clients always carry a grant) whose `federatedSearchScope` holds no live page while another live, unarchived source does. One `CASE WHEN EXISTS` read, fail-open on any error. The message and suggestion never name a hidden source; the fix is the host's `gbrain sources federate <source>` (`hostFix`, input `source`: ask the user), with the token rescope named in the suggestion. A scope holding pages that matched nothing and a brain with no pages read as before (`test/mcp-sources-not-readable.test.ts`).
- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}`... (line truncated to 2000 chars)
- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.
- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`. D2: `hiddenToolRoute(op, ToolConnection)` is the one decision for every transport (`callable` | `widen {surface}` | `host {read_only|surface|grant}`): a widen is offered only when the widened connection could call the tool (read-only access, `GBRAIN_MCP_FORCE_SURFACE`, the grant's snapshot/scopes and an operator pin all hold); dispatch builds the connection with `toolConnection(opts)`. `hiddenToolNext` turns a route into the D2 fix (the call itself; request_tools; on HTTP the D4 grant repair; on stdio the CLI equivalent with the call's arguments as flags).
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index eb6dfe99ae..4163e646f7 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -42,7 +42,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/sources-strategy.ts` — `gbrain sources set-strategy <id> <markdown|code|auto>` (#4899, PR #5955): writes `sources.config.strategy` through `updateSourceConfig` (single-key merge; every other config key survives), the value `sync --all`, autopilot, the dream cycle and the MCP `sync` op pass to the per-source sync when the caller names no `--strategy`; unset means `markdown`. The one writer of that key (no `sources add --strategy`, no op param). Connector kinds refuse it. [R26]: refuses with `sync_run_unfinished` (exit 1) while the source has an unfinished `managed-sync` cursor, naming the resume and the orphan repair, because the frozen manifest was classified under the old strategy; re-stating the current value is allowed. `sources list --json` and `listSources` report `strategy` (`null` when unset). Pinned by `test/sources-strategy.test.ts`.
-- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. `add` without `--federated` or `--no-federated` stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>` (`test/sources-add-federation-warning.test.ts`). Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
+- `src/commands/sources-add-next.ts` — GBRA-156: `noGrantFloorNext(engine, id)`, the federate step `sources add` prints when a new non-federated source leaves the no-grant floor (`localFederatedSourceIds(engine, 'default', 'seed_default')`, else `['default']`) holding no live page; returns `{ command, argv, why }` or null. One read, no write.
+- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar}`; `set-calendar` dispatches to `src/commands/sources-set-calendar.ts`, and `set-cr-mode` prints `contextualModeHint` after the write. `refresh` dispatches to `src/commands/sources-refresh.ts` (argument parsing, stdout text or `--json` result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in `src/core/persistence/worktree-refresh.ts`). `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. `add` without `--federated` or `--no-federated` stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`; when the no-grant floor (the default source plus federated sources) then holds no live page it also prints `next: gbrain sources federate <id>` on stdout (`noGrantFloorNext` in `sources-add-next.ts`). `add --json` prints one object (`id`, `name`, `local_path`, `remote_url`, `federated`, and `next` with `command`/`argv`/`why` when that step applies) and moves the human lines to stderr (`test/sources-add-federation-warning.test.ts`). Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
- `src/commands/status-funnel.ts` — `gbrain status --funnel [--json] [--enable | --delete]` (D8 adoption funnel): engine-free, dispatched from `src/cli/main.ts` before any connect so it works before `gbrain init` and on a thin client; reads and writes only the local record through `src/core/funnel.ts`. Guide: `docs/guides/adoption-funnel.md`. Tests: `test/funnel.test.ts`, `test/funnel-cli.test.ts`.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 4e74cd4de0..dbcb1394e7 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -27,6 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/output-redaction.ts` — copies retrieval results and metadata before output sanitation, sharing the canonical `secret-scan.ts` plan and echo dictionary. Keyword, hybrid, image, exact and CRAG paths sanitize after internal grading/capture and before snippet truncation; CLI search/query JSON, explain and human rendering repeat the defense-in-depth pass. Every field is planned with `highEntropy: true`, so `KEY=value` assignments redact alongside the named shapes. Identity fields (`id`, `slug`, `source_id`, `page_id`, `chunk_id`, `message_id`, `thread_id`, `graph_session_prefix`, relational seed/path, `superseded_by`, `fact_id`, `entity_slug`) remain byte-identical: never put secrets in IDs. By default each field is capped at 64 Ki UTF-16 characters, the response at 1 Mi characters/8192 text fields, and nesting at 24 levels; oversized/unscannable text becomes `<REDACTED:output_limit>`. `RetrievalRedactionOpts.uncapped` scans every field whole (no `output_limit` replacement; one echo dictionary, every field planned before any write; the depth cap stays) and `verbatim` copies the named keys of each top-level result unscanned. `withOutputRedaction(op)` is the registration-time wrapper behind `Operation.outputRedaction` (`src/core/ops/contract.ts`): `operations.ts` wraps every `'retrieval'` op's handler once, so the CLI, stdio and HTTP MCP, subagent tools and `gbrain call` all pass the whole response (early returns included) through the uncapped redactor, linear in output size; `{ retrieval: { localVerbatim } }` leaves the named keys raw only when `ctx.remote === false`. The memory verbs: `recall`, `context_pack` and `delta` redact their presentation sets with one echo dictionary before packing, so budgets, `budget_used` and the delta cursor follow the delivered text, and their rendered `text` is never replaced by `output_limit`; facts (`fact`, `context`, `source`) are `localVerbatim`, so a remembered credential is readable raw only by the trusted local CLI on the brain host (stdio MCP and thin clients are remote). Handlers that clip or summarize stored text (transcript summaries, entity-card and compiled-context excerpts) redact the whole field before clipping. THREAT MODEL: this defends against accidental exposure of stored credentials into agent context and transcripts through retrieval ops. It does not cover the raw-read exemptions (`get_page`, `fetch`, `get_chunks`, `get_raw_data`, `get_versions`, the skill catalog, admin job ops), stored content (unchanged), or configured providers (embeddings at ingest, the hosted reranker, synthesis/think generation still receive unredacted text, except private keys, which the credential-safe projection keeps out of chunks). Unknown formats and short fragments can escape detection. This is output hygiene, not authorization or provider/eval no-egress. Tests: `test/search/output-redaction.serial.test.ts`, `test/search/output-redaction.test.ts`, `test/retrieval-op-redaction.test.ts` (every `'retrieval'` and `'no_stored_text'` op run through MCP dispatch with `remote = true` against a planted secret, plus the registration wrapper), `test/transcripts-redaction.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/remote-page-cap.ts` — GBRA-156: the default distinct-page cap of a remote `search`/`query` that names no `limit` (and no `offset`). `remotePageCap(ctx, p)` reads `search.remote_page_cap` (default `DEFAULT_REMOTE_PAGE_CAP`, `0` = off; null for trusted local callers); `capVectorOnlyPages(rows, cap)` keeps every page with lexical evidence (`keyword_hit`, strict or relaxed, `alias_hit`, `exact_lookup`, `relational_pinned`) and admits vector-only pages, in rank order, only while the result holds fewer than `cap` distinct `(source_id, slug)` pages; it reports `{ cap, kept_pages, dropped_pages }` as `_meta.retrieval.page_cap` when it dropped any. `pageCapLine(retrieval)` renders that as the model-visible line dispatch's `retrievalNoticeBlocks` appends after the keyword count line (hosts that show only `content[]` never see `_meta`). Applied to the hybrid output before alias fan-out (search) and to the first pass and an adopted CRAG re-run (query); keyword-only paths carry no vector-only rows and the image branch is uncapped (`test/search-remote-page-cap.test.ts`).
- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain. `chunkWriteInvalidations(pageId, chunks)` yields one guarded `chunker_version = -1` invalidation per row batch of a chunk replacement (`batch-rows.ts` `jsonRowBatches`); the caller stops at the first that returns a row. Wave B: `chunkVisibleFilter(p, c)` (current projection plus a row at or below the page's body generation; sealed pages hold no retired rows, and no subplan keeps vector search on HNSW) is the search predicate; `chunkGenerationFilter(p, c)` serves generation readers (an inline row of a non-segmented page, or a row whose occurrence has a live manifest row, hiding rows a deferred retirement or demotion left; `p` needs `body_storage`), `chunkGenerationProbe(c)` the same without a joined page, and `chunkManifestJoin` / `chunkDocumentOrder` give segmented rows document order (manifest byte_start, local_ordinal); `scripts/check-chunk-visibility.ts` requires one of them or a reason on every `content_chunks` reader (rules in its header).
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 96d74abd8a..6151ea912d 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -50,7 +50,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.
-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). Both resolve their source scope through `ops/search-source-scope.ts` and return no rows when that scope is empty. `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate (projection_by_design when the only unsealed pages in scope are protected-OCR images, #6803). Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local; a lean row keeps `id` only when `ctx.isCallable('fetch')`, the MCP dispatch predicate `buildOperationContext` threads in, says the caller can call `fetch` (unset keeps it), and prints `score` at 4 significant digits) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). Each handler times its request (`SearchTimings`, search/stage-timings.ts) and `searchOutput` emits `retrieval.timings` last. The typed-search type check lives in `ops/search-type-filter.ts` (`reconcileTypeFilter`): one statement of per-type `EXISTS` probes over each type's schema-expanded set, with the `DISTINCT` type list for the `type_filter_notice` evaluated only when a probe misses, run `jitOff` and unprepared (a generic plan scans every page per missing type); pinned by `test/search-type-filter-reconcile.test.ts` and `test/e2e/typed-search-jit-postgres.test.ts`. `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`); `coverage` counts pending, held and embedding-held items with `could_affect` (`search/retrieval-coverage.ts`). Its safe-index probe, projection readiness, entity saved facts, saved-fact match and held-file coverage run concurrently, each with its own catch; the answer-feedback write runs after them (`test/search-response-meta-concurrency.test.ts`). The saved-fact match is one statement: an uncorrelated `EXISTS` probe (a one-time filter) skips its `LIKE ANY` scan when no fact qualifies. The handlers start the alias fan-out's `resolveQueryEntity` alongside the hybrid search, and `evidenceOutput` reads page trust (`loadPageTrust` over the rows every delivered row is copied from) alongside evidence delivery (`test/search-post-rerank-concurrency.test.ts`). The starter list leaves out (`fullSurfaceOnly`, still accepted) `mode`, `snippet_chars`, `return_window`, `token_budget`, `salience`, `recency`, `fields`, and on `query` `image`/`image_mime`/`embedding_column`, the code params, `detail`, `adaptive_return`, `autocut` and `relational`.
+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). Both resolve their source scope through `ops/search-source-scope.ts` and return no rows when that scope is empty. `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate (projection_by_design when the only unsealed pages in scope are protected-OCR images, #6803). Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. `searchOutput` then projects the returned rows to the caller's row shape (`src/core/search/lean-rows.ts`: lean for remote callers unless `fields: "full"`, the transport chose full rows, or the caller is trusted-local; a lean row keeps `id` only when `ctx.isCallable('fetch')`, the MCP dispatch predicate `buildOperationContext` threads in, says the caller can call `fetch` (unset keeps it), and prints `score` at 4 significant digits) and reports it as `retrieval.rows` for remote callers and whenever `fields` is passed. The CLI formatter repeats this on JSON, explain and human output. System One: the `query` op asks S4 answerability (`decide.answerability`, diagnostic only) and surfaces `meta.answerability`; the crag escalation re-run keeps S2-S5 off (`rerankOnly`). Each handler times its request (`SearchTimings`, search/stage-timings.ts) and `searchOutput` emits `retrieval.timings` last. The typed-search type check lives in `ops/search-type-filter.ts` (`reconcileTypeFilter`): one statement of per-type `EXISTS` probes over each type's schema-expanded set, with the `DISTINCT` type list for the `type_filter_notice` evaluated only when a probe misses, run `jitOff` and unprepared (a generic plan scans every page per missing type); pinned by `test/search-type-filter-reconcile.test.ts` and `test/e2e/typed-search-jit-postgres.test.ts`. `buildRetrievalResponseMeta` also stamps `stale` on hits whose page's newer file is held, adds `held_files` per source in scope and emits the `held_files` degraded notice (`persistence/held-reads.ts`; Test: `test/held-read-signals.test.ts`); `coverage` counts pending, held and embedding-held items with `could_affect` (`search/retrieval-coverage.ts`). Its safe-index probe, projection readiness, entity saved facts, saved-fact match and held-file coverage run concurrently, each with its own catch; the answer-feedback write runs after them (`test/search-response-meta-concurrency.test.ts`). The saved-fact match is one statement: an uncorrelated `EXISTS` probe (a one-time filter) skips its `LIKE ANY` scan when no fact qualifies. The handlers start the alias fan-out's `resolveQueryEntity` alongside the hybrid search, and `evidenceOutput` reads page trust (`loadPageTrust` over the rows every delivered row is copied from) alongside evidence delivery (`test/search-post-rerank-concurrency.test.ts`). The starter list leaves out (`fullSurfaceOnly`, still accepted) `mode`, `snippet_chars`, `return_window`, `token_budget`, `salience`, `recency`, `fields`, and on `query` `image`/`image_mime`/`embedding_column`, the code params, `detail`, `adaptive_return`, `autocut` and `relational`. A remote `search`/`query` without `limit` passes its hybrid rows through `capVectorOnlyPages` (`search/remote-page-cap.ts`); every vector path reads the keyword path's source scope (`test/search-vector-scope-parity.test.ts`).
- `src/core/ops/search-source-scope.ts` — per-request scope of `search`/`query`: `source_id` through `federatedSearchScope`, narrowed by `source_ids` (`parseSourceIdsParam`: trimmed, deduped, validated; `__all__` refused; `[]` or a blank string is absent, #5390). Each listed id is authorized like an explicit `source_id` (out-of-grant: permission_denied; non-live: unknown_source); with both params the scope is their intersection, and an empty one (`sourceIds: []`) emits `empty_retrieval` and nothing is searched. Tests: `test/search/search-source-ids.test.ts` (+ its `test/e2e/` Postgres twin), `test/e2e/serve-http-member-tokens.test.ts`.
- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index af64295cb7..72aa24cd98 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4021,6 +4021,16 @@ More: [docs/guides/write-refusals.md#slug_page_mismatch](../../docs/guides/write
|---|---|---|---|---|---|---|
| Canonical preparation requires a source-content correction; this profile never writes repository files. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+### sources_not_readable
+
+<a id="sources_not_readable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An unscoped search, query, recall or list_pages was refused before it ran: every source this connection can read (the default source and federated sources) holds no page, while other sources on the brain hold pages it cannot read (not federated, and no source grant). | Answering would return an empty result that reads like a clean miss. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages](../../docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages)
+
### split_bad_ratio
<a id="split_bad_ratio"></a>
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 65dbd90349..e3cc4a5557 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -115,6 +115,34 @@ behave as you'd expect — every page appears in search.
Flip later with `gbrain sources federate <id>` / `unfederate <id>`.
+### An unscoped connection whose sources hold no pages
+
+A remote token minted without `--sources`, or an agent stdio connection with
+no binding, has no source grant: it reads the `default` source plus every
+federated source. Because a new source is not federated, a brain whose pages
+all live in such sources would answer that connection's every search with an
+empty result that reads like a clean miss.
+
+So an unscoped `search`, `query`, `recall` or `list_pages` from such a
+connection is refused with `sources_not_readable` when the sources it reads
+hold no page at all while other sources on the brain hold pages. The refusal
+never names a source the connection cannot read. Its fix is host-side: the
+user picks the source these connections should read and the brain host runs
+`gbrain sources federate <source>`, or grants the connection its sources
+(`gbrain auth rescope --token <name> --sources <ids>`).
+
+Nothing else changes. A read whose sources hold pages but match nothing
+answers empty, as does a brain where no source holds a page. A token granted
+sources, an OAuth client, a bound connection and a read that names
+`source_id` or `source_ids` are never refused: the refusal only ever stops a
+call, never widens what it reads. Federating a source never shows its
+`visibility: private` pages to a remote connection.
+
+`gbrain sources add` warns on stderr when a new source is not federated, and
+when the sources an unscoped connection reads hold no page it also prints the
+next step on stdout (`next: gbrain sources federate <id>`), and as `next`
+(`command`, `argv`, `why`) under `--json`.
+
### Explicit reads from a bound agent connection
An agent connection started with `GBRAIN_SOURCE=<id>` (or inside a
@@ -286,7 +314,7 @@ recorded mode (preview it first without `--apply`; see
```
-gbrain sources add <id> --path <p> [--name <n>] [--federated|--no-federated] [--force]
+gbrain sources add <id> --path <p> [--name <n>] [--federated|--no-federated] [--force] [--json]
Register a source. id: [a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?
--path must be a git repo (or a subdirectory of one) — see
"The git requirement for --path sources" below. --force
diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.md
index a0cac789cb..46ab70428b 100644
--- a/docs/guides/search-modes.md
+++ b/docs/guides/search-modes.md
@@ -419,6 +419,7 @@ on user_asks_about(topic):
4. **Token budget awareness.** A full page via `gbrain get` can be large. Read the search chunks first to confirm relevance before pulling the full page. "Did anyone mention the Series A?" -- search results (chunks) are probably enough. "Tell me everything about Alice" -- get the full page.
5. **Full hybrid needs embeddings to have been run.** If `gbrain query` returns nothing but `gbrain search` finds results, the embeddings haven't been generated yet. Run the embedding pipeline first.
6. **A populated `gbrain search` result set is not proof you found everything.** Neither verb expands by default, so synonym- and outcome-phrased matches can be missed even when a search returns plenty of hits. For "find every / all / the landscape of" questions, use `gbrain query`, adding `--expand` (one call to the configured expansion model, which needs an expansion provider) when the wording is likely to differ from the notes; expanded results are still a ranked top-K; for literal exhaustive enumeration ("list every page of type X"), use `list_pages` pagination. A nonzero count is not a completeness signal.
+7. **A remote `search` or `query` with no `limit` returns at most a few pages that matched only by meaning.** Over MCP (HTTP or stdio), every page that matched the query's words, a name, an alias or an exact identity comes back, but pages that only the vector arm found fill the result only up to `search.remote_page_cap` distinct pages in total (default 3). Without the cap, an embedding-backed search on a small brain returned most of the brain on every call, pages the asking person may not be allowed to read included. When the cap leaves pages out, a line after the results says how many (`_meta.retrieval.page_cap` counts them); pass `limit` for the full ranked list, which landscape and "find every" questions usually want. Local CLI calls, an explicit `limit` and paged calls are never capped. Set the cap with `gbrain config set search.remote_page_cap <n>`; `0` turns it off.
### How to Verify
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index db6c8efd29..f25bae1f79 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -30,13 +30,13 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 conne
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
src/core/minions/worker.ts 1795 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts); +6 GBRA-133 2a.4 sync-queue wake: IdleWaiter import and field, claimStarted before each claim, the idle poll through it, and stop/requestShutdown ending its wait (logic in minions/idle-wait.ts); +1 GBRA-158 #7239: refusal.ts import (a deterministic refusal ends the job at once; classification in minions/refusal.ts); +3 #7242 lane reservation: lanes import and the longJobNames/shortJobReservedSlots defaults (the claim passes claimExclusions; policy in minions/lanes.ts); +2 #7242 terminal hook: onJobSettled default and the settle call (logic in terminal-hook.ts); #7252 x #7249 merge: both sides grew the file, re-summed (1794 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (1795 measured)
-src/commands/sources.ts 2086 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured)
+src/commands/sources.ts 2093 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +1 GBRA-133: sources reset-upstream help row (body in sources-reset-upstream.ts); fix wave 20 integration: lane 3 (#6827) and master growth compose at 2062 measured; +3 GBRA-150: sources resolve-path dispatch and help rows (body in sources-resolve-path.ts); +10 #7326: sources status parses --holds/--limit/--cursor and passes the git_holds listing mode, plus 4 help lines (bounding logic in persistence/connector-status.ts gitHoldStatusJson); +2 GBRA-133 Q1: sources set-sync dispatch and help row (body in sources-sync-enabled.ts); +4 G1 git-canonical: sources git-gap dispatch, doc line and help rows (body in sources-git-gap.ts); +4 G3 git-canonical: sources reindex dispatch, doc line and help rows (body in sources-reindex.ts); +1 GBRA-156: the sources add non-federated warning line; re-summed at the master 33d73cb5 merge (2086 measured); GBRA-156: sources add --json and its next step (logic in sources-add-next.ts)
src/core/link-extraction.ts 2424 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1); +3 G5 (GBRA-60): extractBodyLinks masks the ## Links fence (links-fence.ts), whose rows are projected as their own edges
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)
+src/core/config.ts 2013 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts)
src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
diff --git a/src/commands/sources-add-next.ts b/src/commands/sources-add-next.ts
new file mode 100644
index 0000000000..8e74fe67ef
--- /dev/null
+++ b/src/commands/sources-add-next.ts
@@ -0,0 +1,32 @@
+/**
+ * GBRA-156: the next command `gbrain sources add` prints when a new
+ * non-federated source leaves the no-grant floor holding no page.
+ *
+ * A remote token or agent connection with no source grant reads the default
+ * source plus the federated ones. When none of those holds a page, such a
+ * connection is refused (`sources_not_readable`) until a source is federated
+ * or the connection is granted sources, so the add says which command makes
+ * the new source readable. The stored federation default is unchanged.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { localFederatedSourceIds } from '../core/source-resolver.ts';
+
+export interface SourcesAddNext {
+ command: string;
+ argv: string[];
+ why: string;
+}
+
+/** The federate step for `id` when the no-grant floor holds no live page, else null. */
+export async function noGrantFloorNext(engine: BrainEngine, id: string): Promise<SourcesAddNext | null> {
+ const floor = (await localFederatedSourceIds(engine, 'default', 'seed_default')) ?? ['default'];
+ const [row] = await engine.executeRaw<{ holds: boolean }>(
+ `SELECT EXISTS (SELECT 1 FROM pages WHERE source_id = ANY($1::text[]) AND deleted_at IS NULL) AS holds`, [floor]);
+ if (row?.holds) return null;
+ const argv = ['gbrain', 'sources', 'federate', id];
+ return {
+ command: argv.join(' '),
+ argv,
+ why: `Connections with no source grant read only the default source and federated sources, and none of them holds a page, so their reads are refused until "${id}" is federated or they are granted sources.`,
+ };
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 8801cf3253..c72215bbf4 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -58,6 +58,7 @@ import {
import { isValidRepoName } from '../core/github-source.ts';
import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID } from '../core/google/types.ts';
import { defaultGoogleAddTuning, parseGoogleAddFlag } from './sources-google-flags.ts';
+import { noGrantFloorNext } from './sources-add-next.ts';
import {
resolveSourceWithTier,
SOURCE_TIER_NAMES,
@@ -147,7 +148,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
if (!id) {
console.error(
'Usage: gbrain sources add <id> [--path <path> | --url <https-url> | --kind github|google] ' +
- '[--name <display>] [--federated|--no-federated] [--clone-dir <path>] [--force]\n' +
+ '[--name <display>] [--federated|--no-federated] [--clone-dir <path>] [--force] [--json]\n' +
' github kind: [--token-env <env>] [--scope auto|repos] ' +
'[--repos owner/name,...] [--dir <path>] ' +
'[--app-id <n> --app-pem <path>] [--app-install <n>]\n' +
@@ -166,6 +167,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
let patFile: string | undefined;
let noHarden = false;
let force = false;
+ let json = false;
// v0.46 github-kind flags.
let ghKind = false;
let ghTokenEnv: string | undefined;
@@ -195,6 +197,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
if (a === '--pat-file') { patFile = args[++i]; continue; }
if (a === '--no-harden') { noHarden = true; continue; }
if (a === '--force') { force = true; continue; }
+ if (a === '--json') { json = true; continue; }
if (a === '--kind') {
const kind = args[++i];
if (kind === 'github') {
@@ -445,18 +448,21 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
: created.local_path
? ` → ${created.local_path}`
: '';
- console.log(
+ const say = json ? console.error : console.log;
+ say(
`Created source "${id}"${displayName && displayName !== id ? ` (name: ${displayName})` : ''}${tail}`,
);
if (finalRemoteUrl) {
- console.log(` clone path: ${created.local_path}`);
+ say(` clone path: ${created.local_path}`);
}
- console.log(
+ say(
` federated: ${fed}${fed ? ' — appears in cross-source default search' : ' — only searched when explicitly named via --source'}`,
);
if (!fed && federated === null) console.error(`Warning: source "${id}" is not federated. A remote token or agent connection with no source grant cannot read its pages, so its searches answer empty for them. Run \`gbrain sources federate ${id}\` to let every such connection read it, or grant one token with \`gbrain auth rescope --token <name> --sources ${id}\`.`);
+ const next = !fed && federated === null ? await noGrantFloorNext(engine, id) : null;
+ if (next) say(` next: ${next.command} — ${next.why}`);
if (ghKind || gKind) {
- console.log(` sync: run \`gbrain sync --source ${id}\` once; after its first sync, autopilot keeps it synced on the autopilot interval.`);
+ say(` sync: run \`gbrain sync --source ${id}\` once; after its first sync, autopilot keeps it synced on the autopilot interval.`);
}
// v0.42.44 — auto-harden managed clones for git durability the moment a brain
@@ -488,6 +494,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
console.error(` Run \`gbrain sources harden ${id}\` to retry.`);
}
}
+ if (json) console.log(JSON.stringify({ id, name: created.name, local_path: created.local_path, remote_url: finalRemoteUrl ?? null, federated: fed, ...(next ? { next } : {}) }));
}
/**
@@ -1963,7 +1970,7 @@ Subcommands:
connect <path> --brain <id> --source <id> [--profile company-brain] [--yes] [--json]
Preview, approve, import and verify a new company source; --plan <file> reuses a saved inspection.
demo company-brain [--json] Run a fictional company through the real import and graph pipeline offline.
- add <id> --path <p> [--name <n>] [--federated|--no-federated] [--force]
+ add <id> --path <p> [--name <n>] [--federated|--no-federated] [--force] [--json]
Register a new source. --path must be a git repo
with committed files; --force skips that check.
list [--json] List registered sources with page counts.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 632e6cc838..67b2df09e9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1268,6 +1268,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.452.0', id: 'starter_tools_list_params_gbra156', text: 'The starter MCP tool list is about 27% smaller: it leaves out parameters MCP callers cannot use (local-only, server-set provenance) and rarely needed ones (legacy, admin, versioned skill catalog, image and code search, tuning and recovery knobs with safe defaults). Every left-out parameter is still accepted, and `request_tools {tools: [names]}` now returns each tool\'s full schema with every optional parameter, also on a server capped at starter. Memory verb descriptions no longer start with `MEMORY VERB (v1):`. The verbs and full surfaces list every parameter as before.' },
{ 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: 'remote_page_cap_gbra156', text: 'A remote `search` or `query` that names no `limit` now returns every page that matched its words, a name or an exact identity, plus pages that matched only by meaning up to 3 pages in total (`search.remote_page_cap`, default 3; `0` turns it off). A line after the results says how many pages were left out, and `_meta.retrieval.page_cap` counts them. An explicit `limit`, a paged call and every local CLI call return the same rows as before.' },
+ { since: 'TBD', id: 'sources_not_readable_refusal_gbra156', text: 'An unscoped remote `search`, `query`, `recall` or `list_pages` from a connection with no source grant, when every source it reads holds no page and other sources do, is now refused with `sources_not_readable` (host fix `gbrain sources federate <source>` with the source the user picks, or a grant for the token) instead of answering empty with a degraded notice. A scope that holds pages but matched nothing, a brain with no pages, granted tokens, OAuth clients, bound connections and reads that name a source behave as before.' },
+ { since: 'TBD', id: 'sources_add_next_gbra156', text: '`gbrain sources add` without `--federated` or `--no-federated`, on a brain where connections with no source grant read no page, now prints `next: gbrain sources federate <id>` on stdout. `--json` prints `{id, name, local_path, remote_url, federated, next?}` on stdout and moves the human lines to stderr.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/config.ts b/src/core/config.ts
index 0a95052dce..a386498507 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1366,6 +1366,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.image_query.daily_budget_usd_per_client',
'search.image_query.remote_max_bytes',
'search.mcp_keyword_only',
+ 'search.remote_page_cap', // GBRA-156: distinct-page cap of a remote search/query without limit (search/remote-page-cap.ts)
REMOTE_PRIVATE_PAGES_KEY,
'search.track_retrieval',
// Retrieval feedback (feedback/settings.ts).
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 24e4090ac1..6aa69eb5e1 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -670,6 +670,7 @@ export const CODES = {
source_referenced: { class: 'caller', summary: "OAuth clients still reference this source." },
source_root_conflict: { class: 'caller', summary: "Multiple active sources alias this canonical skill root; resolve ownership before publishing." },
source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },
+ sources_not_readable: { class: 'host_only', retryable: false, summary: "An unscoped search, query, recall or list_pages was refused before it ran: every source this connection can read (the default source and federated sources) holds no page, while other sources on the brain hold pages it cannot read (not federated, and no source grant).", why: "Answering would return an empty result that reads like a clean miss. The refusal names the host command that federates a source or grants this connection the sources it should read; it never names a hidden source and never widens access. A scope that holds pages but matched nothing, a granted token, an OAuth client, a bound connection and a read that names a source are never refused.", docs: 'docs/guides/multi-source-brains.md#an-unscoped-connection-whose-sources-hold-no-pages' },
split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },
split_unparseable: { class: 'caller', summary: "Split unparseable." },
stable_channel_unresolved: { class: 'unavailable', reasons: ['unreadable', 'no_stable', 'no_release_tag'], summary: "`gbrain upgrade --channel stable` (or `self_upgrade.channel stable`) could not name the stable release: the repository's tags could not be read, no release has been promoted to stable yet, or the `stable` tag does not share a commit with a `v<version>` release tag. Nothing was changed.", why: "The stable channel installs only a release a maintainer promoted after the production-shaped soak passed on its exact tree; without that answer it installs nothing rather than guess.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel', suggestion: 'Retry later, or upgrade on the latest channel with `gbrain upgrade --channel latest`.' },
@@ -862,7 +863,6 @@ export const NOTICE_CODES = {
mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },
degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },
source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },
- sources_not_readable: { kind: 'degraded', summary: 'An unscoped search, query, recall or list_pages came back empty because every source this connection can read holds no page, while other sources on the brain hold pages it cannot read (not federated, and no source grant). The result is not proof of absence; the fix is the host command that federates a source or grants this connection the sources it should read. Hidden sources are never named.' },
degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },
facts_calibration_unmeasured: { kind: 'info', summary: 'recall --question ranked facts with semantic matching on an embedding model whose fact admission floors were never measured (`facts_calibration: {status: "unmeasured", model_key}`); a short facts list is weaker evidence of "nothing matched". Once per brain per session; the fix is the read-only `gbrain doctor --only fact_admission_floors --json`.' },
private_fact_not_pushed: { kind: 'info', summary: 'remember saved a private fact: only local CLI recall reads it, and session hooks never push it into a new agent session.' },
diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.ts
index fbcdd41f03..f332813b4b 100644
--- a/src/core/notice-ledger.ts
+++ b/src/core/notice-ledger.ts
@@ -34,7 +34,7 @@ export const COACHING_BUDGET_PER_SESSION = 2;
/** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */
export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);
/** Notices that describe THIS call's result (never deduped unless the notice carries a `dedupe_key`): the diagnosis must ride every affected call. */
-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'sources_not_readable', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'references_unavailable', 'record_types_undeclared', 'alias_fanout', 'facts_unembedded']);
+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'references_unavailable', 'record_types_undeclared', 'alias_fanout', 'facts_unembedded']);
/** How long a shown coverage state (a notice's `escalation`) stays shown. */
export const COVERAGE_NOTICE_WINDOW_MS = 30 * 60 * 1000;
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 6f11a42d0b..4fd7e941ad 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -70,6 +70,7 @@ import type { TrustTier } from '../trust/tier.ts';
import type { Operation, OperationContext } from './contract.ts';
import { invalidParam, paramUse, readFix } from './op-fix.ts';
import { parseSourceIdsParam, requestSourceScope, SOURCE_IDS_PARAM } from './search-source-scope.ts';
+import { capVectorOnlyPages, remotePageCap } from '../search/remote-page-cap.ts';
import {
parseSourceIdParam,
resolvePerCallMode,
@@ -817,6 +818,7 @@ const search: Operation = {
const keywordCount = timings.overlap('keyword_count', startKeywordCount(ctx.engine, queryText, types, readOpts, searchDone.promise));
const resolving = offset === 0 ? startEntityResolution(ctx, queryText, { ...scope, excludePrivate }) : undefined;
const explainPrep = await setup(() => prepareExplainTarget(ctx, p, scope, excludePrivate, 'search'));
+ const pageCap = await setup(() => remotePageCap(ctx, p));
const searchOpts = {
limit,
offset,
@@ -835,9 +837,10 @@ const search: Operation = {
...(plan?.rankCut ? { pageRankCut: plan.rankCut } : {}),
_timings: timings,
};
- const primary = await hybridSearchCached(ctx.engine, queryText, {
+ const capped = capVectorOnlyPages(await hybridSearchCached(ctx.engine, queryText, {
...searchOpts, onMeta: (m) => { capturedMeta = m; }, explain: p.explain === true, explainTarget: explainPrep?.trace,
- }).finally(searchDone.resolve);
+ }).finally(searchDone.resolve), pageCap);
+ const primary = capped.rows;
const declarations = new DeclarationMemo();
const fanned = offset === 0
? await timings.stage('alias_fanout', () => withAliasFanOut(ctx.engine, primary, queryText, { ...scope, excludePrivate },
@@ -852,7 +855,7 @@ const search: Operation = {
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap, timings,
- async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity, filterHintFor: { op: 'search', p }, timings })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
+ async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity, filterHintFor: { op: 'search', p }, timings })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}), ...(capped.meta ? { page_cap: capped.meta } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
keywordCountMeta(await timings.part('response', 'keyword_count', () => keywordCount), offset + limit)));
},
scope: 'read', mutating: false,
@@ -1037,11 +1040,12 @@ const query: Operation = {
types = typeFilter.types;
let capturedMeta: HybridSearchMeta | null = null; let queryEmbedding: Float32Array | null = null; const resolving = startEntityResolution(ctx, queryText, { ...querySourceScope, excludePrivate });
const explainPrep = await setup(() => prepareExplainTarget(ctx, p, querySourceScope, excludePrivate, 'query'));
+ const pageCap = await setup(() => remotePageCap(ctx, p));
// v0.32.x search-lite: route the query op through hybridSearchCached so
// token budget and intent weighting apply at the operation boundary.
// Semantic cache reuse is suspended in the wrapper.
// (#1663: `let` — the CRAG gate below may swap in an escalated run.)
- let results = await hybridSearchCached(ctx.engine, queryText, {
+ let capped = capVectorOnlyPages(await hybridSearchCached(ctx.engine, queryText, {
// #4356 — was a hard `|| 20`, independent of the mode-resolution
// hybridSearchCached applies when `limit` is falsy (undefined OR 0):
// `opts?.limit || resolvedMode.searchLimit` (hybrid.ts). Passing
@@ -1096,7 +1100,8 @@ const query: Operation = {
// v0.43 — relational recall override. Omitted = smart default (mode bundle).
relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
explain: p.explain === true, explainTarget: explainPrep?.trace, _timings: timings,
- });
+ }), pageCap);
+ let results = capped.rows;
const declarations = new DeclarationMemo();
const primaryRows = results;
const fanned = await timings.stage('alias_fanout', () => withAliasFanOut(ctx.engine, primaryRows, queryText, { ...querySourceScope, excludePrivate },
@@ -1182,7 +1187,8 @@ const query: Operation = {
crag.escalated = true;
crag.escalated_confidence = regraded.level;
if (confidenceRank(regraded.level) > confidenceRank(grade.level)) {
- results = escalated.slice(0, effectiveLimit);
+ capped = capVectorOnlyPages(escalated.slice(0, effectiveLimit), pageCap);
+ results = capped.rows;
capturedMeta = escalatedMeta;
grade = regraded;
crag.confidence = regraded.level;
@@ -1263,7 +1269,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap, timings,
- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity, filterHintFor: { op: 'query', p }, timings })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
+ async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity, filterHintFor: { op: 'query', p }, timings })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}), ...(capped.meta ? { page_cap: capped.meta } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/search/remote-page-cap.ts b/src/core/search/remote-page-cap.ts
new file mode 100644
index 0000000000..c90e1b07c7
--- /dev/null
+++ b/src/core/search/remote-page-cap.ts
@@ -0,0 +1,67 @@
+/**
+ * GBRA-156: the default page cap of a remote `search` or `query` that names no `limit`.
+ *
+ * The keyword arm returns only pages that matched the query. With an embedding
+ * model on, the vector arm fills the rest of the mode's row limit with every
+ * page it can reach, however weakly related, so an agent asking one question
+ * read most of a small brain (a median 12 pages a call against keyword's 2 on
+ * the harness ladder, and with them pages the asking person may not read).
+ * Cosine does not separate those rows: on a small corpus the filler often
+ * scores above the keyword hit, so a similarity floor cannot drop them.
+ *
+ * The cap keeps every page with lexical evidence (a keyword or title hit, an
+ * alias or exact identity match, a pinned relational answer), exactly the
+ * pages the keyword path returns, and lets vector-only pages fill the result
+ * only up to `search.remote_page_cap` distinct pages in total. A query with
+ * no lexical match still gets its top vector pages. An explicit `limit`, a
+ * paged call (offset > 0) and every trusted local caller keep today's rows;
+ * `0` turns the cap off.
+ */
+import type { OperationContext } from '../ops/contract.ts';
+import type { SearchResult } from '../types.ts';
+
+export const REMOTE_PAGE_CAP_KEY = 'search.remote_page_cap';
+export const DEFAULT_REMOTE_PAGE_CAP = 3;
+
+/** `_meta.retrieval.page_cap` when the cap left pages out. */
+export interface RemotePageCapMeta {
+ cap: number;
+ kept_pages: number;
+ dropped_pages: number;
+}
+
+/** The cap for one call, or null when it does not apply. */
+export async function remotePageCap(ctx: OperationContext, p: Record<string, unknown>): Promise<number | null> {
+ if (ctx.remote === false || p.limit || p.offset) return null;
+ const raw = await ctx.engine.getConfig(REMOTE_PAGE_CAP_KEY).catch(() => null);
+ const n = raw === null || raw.trim() === '' ? Number.NaN : Number(raw);
+ const cap = Number.isInteger(n) && n >= 0 ? n : DEFAULT_REMOTE_PAGE_CAP;
+ return cap === 0 ? null : cap;
+}
+
+/** The model-visible line when the cap left pages out (hosts that show only `content[]` never see `_meta`). */
+export function pageCapLine(retrieval: unknown): string | null {
+ const m = (retrieval as { page_cap?: RemotePageCapMeta } | null)?.page_cap;
+ if (!m) return null;
+ return `[gbrain search] Showing ${m.kept_pages} pages: ${m.dropped_pages} more matched only by meaning and were left out (default remote cap ${m.cap}). Pass limit to read them.`;
+}
+
+function hasLexicalEvidence(r: SearchResult): boolean {
+ return r.keyword_hit === true || r.alias_hit === true || r.exact_lookup !== undefined || r.relational_pinned === true;
+}
+
+/** Keeps every lexically matched page and the top vector-only pages up to `cap` distinct pages. */
+export function capVectorOnlyPages(rows: SearchResult[], cap: number | null): { rows: SearchResult[]; meta?: RemotePageCapMeta } {
+ if (cap === null) return { rows };
+ const pageOf = (r: SearchResult) => `${r.source_id ?? ''}\u0000${r.slug}`;
+ const pages = new Set(rows.filter(hasLexicalEvidence).map(pageOf));
+ const dropped = new Set<string>();
+ const kept = rows.filter((r) => {
+ const page = pageOf(r);
+ if (pages.has(page)) return true;
+ if (pages.size < cap) { pages.add(page); return true; }
+ dropped.add(page);
+ return false;
+ });
+ return dropped.size === 0 ? { rows } : { rows: kept, meta: { cap, kept_pages: pages.size, dropped_pages: dropped.size } };
+}
diff --git a/src/core/sources-not-readable.ts b/src/core/sources-not-readable.ts
new file mode 100644
index 0000000000..afd90baa69
--- /dev/null
+++ b/src/core/sources-not-readable.ts
@@ -0,0 +1,63 @@
+/**
+ * GBRA-156: `sources_not_readable`, the refusal of an unscoped remote read
+ * whose readable sources hold no page while other sources hold pages.
+ *
+ * A connection with no source grant (a token minted without --sources, or
+ * an unbound agent stdio connection) reads the default source plus the
+ * federated ones. A new source is not federated by default, so such a
+ * connection could answer every search with an empty result that reads like
+ * a clean miss. The read is refused before it runs instead, naming the host
+ * command that makes the pages readable without naming any source the
+ * connection cannot read. A scope that holds pages but matched nothing, and a
+ * brain where no source holds a page, read as before. A connection whose
+ * operator granted it sources (every OAuth client carries at least its bound
+ * source), a connection bound to a source, or a read that names a source is
+ * never refused here: that scope is deliberate. The refusal only ever
+ * narrows what a call returns, and federation never exposes private pages.
+ */
+import type { OperationContext } from './ops/contract.ts';
+import { opError } from './ops/contract.ts';
+import { federatedSearchScope } from './ops/context.ts';
+import { hostFix } from './ops/op-fix.ts';
+
+const UNSCOPED_READ_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'list_pages']);
+
+function namesSources(params: Record<string, unknown>): boolean {
+ const ids = params.source_ids;
+ return params.source_id !== undefined || (Array.isArray(ids) ? ids.length > 0 : typeof ids === 'string' && ids.trim() !== '');
+}
+
+/** Throws `sources_not_readable` before an unscoped remote read that can only come back empty. */
+export async function assertUnscopedReadReachesPages(op: string, params: Record<string, unknown>, ctx: OperationContext): Promise<void> {
+ if (ctx.remote === false || !UNSCOPED_READ_OPS.has(op) || namesSources(params)) return;
+ if (ctx.explicitReadBinding || ctx.auth?.allowedSources !== undefined || ctx.auth?.hasSourceGrant === true) return;
+ let refuse = false;
+ try {
+ const scope = federatedSearchScope(ctx);
+ const readable = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);
+ if (!readable) return;
+ const [row] = await ctx.engine.executeRaw<{ refuse: boolean }>(
+ `SELECT CASE WHEN EXISTS (SELECT 1 FROM pages WHERE source_id = ANY($1::text[]) AND deleted_at IS NULL) THEN false
+ ELSE EXISTS (SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id
+ WHERE p.deleted_at IS NULL AND s.archived IS NOT TRUE AND NOT (p.source_id = ANY($1::text[])))
+ END AS refuse`,
+ [readable],
+ );
+ refuse = row?.refuse === true;
+ } catch {
+ return;
+ }
+ if (!refuse) return;
+ throw opError('sources_not_readable',
+ `This connection reads only the default source and federated sources, and none of them holds a page, so this ${op} could only come back empty.`,
+ 'Other sources on this brain hold pages, but they are not federated and this connection has no source grant. Ask the user which source these connections should read; '
+ + 'the brain host\'s operator federates it (command in fix) or grants this connection its sources (`gbrain auth rescope --token <name> --sources <ids>`).',
+ {
+ why: 'A connection with no source grant reads the default source plus federated sources, and a new source is not federated unless `sources add --federated` or `sources federate` made it so.',
+ fix: {
+ ...hostFix(ctx, ['gbrain', 'sources', 'federate', '<source>'],
+ 'Makes the source readable by every connection without a source grant; only the trusted CLI on the brain host changes federation.'),
+ inputs: [{ name: 'source', how: 'Ask the user which source these connections should read (`gbrain sources list` on the brain host shows them).' }],
+ },
+ });
+}
diff --git a/src/core/unreadable-sources-notice.ts b/src/core/unreadable-sources-notice.ts
deleted file mode 100644
index 43fae126aa..0000000000
--- a/src/core/unreadable-sources-notice.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * GBRA-156: `sources_not_readable`, the notice on an unscoped remote read
- * that reached no source holding a page while other sources hold pages.
- *
- * A connection with no source grant (a token minted without --sources, or
- * an unbound agent stdio connection) reads the default source plus the
- * federated ones. A new source is not federated by default, so such a
- * connection can answer every search with an empty result that reads like a
- * clean miss. This notice says the pages are elsewhere and names the host
- * command that makes them readable, without naming any source the connection
- * cannot read. A connection whose operator granted it sources (every OAuth
- * client carries at least its bound source), or a read that names a source,
- * never gets it: that scope is deliberate.
- */
-import type { Notice } from './agent-output.ts';
-import { emptyRead } from './interop-notices.ts';
-import type { OperationContext } from './ops/contract.ts';
-import { federatedSearchScope } from './ops/context.ts';
-import { hostFix } from './ops/op-fix.ts';
-
-const UNSCOPED_READ_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'list_pages']);
-
-function namesSources(params: Record<string, unknown>): boolean {
- const ids = params.source_ids;
- return params.source_id !== undefined || (Array.isArray(ids) ? ids.length > 0 : typeof ids === 'string' && ids.trim() !== '');
-}
-
-/** The notice for one successful call, or null. Never throws. */
-export async function unreadableSourcesNotice(
- op: string, params: Record<string, unknown>, result: unknown, ctx: OperationContext,
-): Promise<Notice | null> {
- if (ctx.remote === false || !UNSCOPED_READ_OPS.has(op) || !emptyRead(op, result) || namesSources(params)) return null;
- if (ctx.explicitReadBinding || ctx.auth?.allowedSources !== undefined || ctx.auth?.hasSourceGrant === true) return null;
- try {
- const scope = federatedSearchScope(ctx);
- const readable = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);
- if (!readable) return null;
- const [row] = await ctx.engine.executeRaw<{ in_scope: boolean; elsewhere: boolean }>(
- `SELECT EXISTS (SELECT 1 FROM pages WHERE source_id = ANY($1::text[]) AND deleted_at IS NULL) AS in_scope,
- EXISTS (SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id
- WHERE p.deleted_at IS NULL AND s.archived IS NOT TRUE AND NOT (p.source_id = ANY($1::text[]))) AS elsewhere`,
- [readable],
- );
- if (!row || row.in_scope || !row.elsewhere) return null;
- return {
- code: 'sources_not_readable',
- kind: 'degraded',
- why: `This unscoped ${op} read every source this connection can read (the default source and any federated source), and none of them holds a page. `
- + 'Other sources on this brain hold pages, but they are not federated and this connection has no source grant, so it cannot read them. '
- + 'The empty result is not proof the brain has nothing on this. The brain host\'s operator can federate a source so every connection without a grant reads it (command in fix), '
- + 'or grant this connection the sources it should read (`gbrain auth rescope --token <name> --sources <ids>`).',
- fix: {
- ...hostFix(ctx, ['gbrain', 'sources', 'federate', '<source>'],
- 'Makes the source readable by every connection without a source grant; only the trusted CLI on the brain host changes federation.'),
- inputs: [{ name: 'source', how: 'Ask the user which source these connections should read (`gbrain sources list` on the brain host shows them).' }],
- },
- };
- } catch {
- return null;
- }
-}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 8007d03b52..ae908bb653 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -23,9 +23,10 @@ import { hostFix, scopeDeniedError } from '../core/ops/op-fix.ts';
import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger, type NoticeAudience } from '../core/notice-ledger.ts';
import { logVerbUsage, recordsFiring, type RecordsFiring } from '../core/verbs/usage-log.ts';
import { searchCountLine } from '../core/search/keyword-paging.ts';
+import { pageCapLine } from '../core/search/remote-page-cap.ts';
import { dateLabelLine } from '../core/search/date-labels.ts';
import { hiddenTakesNotice, localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';
-import { unreadableSourcesNotice } from '../core/unreadable-sources-notice.ts';
+import { assertUnscopedReadReachesPages } from '../core/sources-not-readable.ts';
import { hiddenToolHint, hiddenToolNext, hiddenToolRoute, type ToolConnection } from './hidden-tool-hint.ts';
import { opAllowedForBoundClient } from '../core/ops/context.ts';
import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';
@@ -393,7 +394,7 @@ export function summarizeMcpParams(opName: string, params: unknown): ParamSummar
/**
* Model-visible notices the search/query ops attach to `_meta.retrieval`: the
* D8 empty-retrieval diagnosis, a reconciled type filter, other names declared in the evidence, and saved
- * facts that match the query, search's keyword count line and the row-date label. Each rides as its own text block after the
+ * facts that match the query, search's keyword count line, the remote page cap line and the row-date label. Each rides as its own text block after the
* results (content[0] stays the bare result array for thin clients).
*/
export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): string[] {
@@ -422,6 +423,8 @@ export function retrievalNoticeBlocks(result: unknown, retrieval: unknown): stri
// F2: which set the rows are and which set the keyword count covers, on every search call.
const countLine = searchCountLine(result, retrieval);
if (countLine) blocks.push(countLine);
+ const capLine = pageCapLine(retrieval);
+ if (capLine) blocks.push(capLine);
// F4: what each row's effective_date is (document, event or fallback date), never contractual validity.
const dateLine = dateLabelLine(result);
if (dateLine) blocks.push(dateLine);
@@ -1074,6 +1077,7 @@ async function dispatchResolvedCall(
enforceBoundClientOpAllowList(ctx.auth, op);
// #5575 CEO-18: a floored connection only reaches read ops that enforce its floor.
enforceReadTrustFloor(ctx.auth, op);
+ await assertUnscopedReadReachesPages(name, safeParams, ctx);
// GBRA-156: a read op does not change what the hook reads, so it runs beside the handler (a degraded engine's reconnect stays the handler's).
const earlyMeta = opts.metaHook && op.mutating === false && !isEngineDegraded(engine) ? runMetaHook(opts.metaHook, name, ctx) : undefined;
const sharedStdio = ctx.transport === 'stdio' && !ctx.auth &&
@@ -1129,8 +1133,6 @@ async function dispatchResolvedCall(
const rerankDegradedCalls = recordRerankDegradation(responseMeta, opts);
notices.push(...recallInteropNotices(name, result, responseMeta, safeParams,
{ config: ctx.config, transport: dispatchRenderContext(opts).transport, binding: ctx.explicitReadBinding, rerankDegradedCalls }));
- const unreadable = await unreadableSourcesNotice(name, safeParams, result, ctx);
- if (unreadable) notices.push(unreadable);
notices.push(...await hiddenContentNotices(engine, name, result, ctx, opts));
// Monthly backup-coverage: one AGGREGATE notice per process (counts only —
// never a local path or source id). The refresher runs on the stdio
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index b63b563e9f..4210e7eefe 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -25,6 +25,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.image_query.daily_budget_usd_per_client', // ops/image.ts
'search.image_query.remote_max_bytes', // ops/image.ts
'search.mcp_keyword_only', // ops/search.ts
+ 'search.remote_page_cap', // search/remote-page-cap.ts (ops/search.ts)
REMOTE_PRIVATE_PAGES_KEY, // search/private-visibility.ts
'search.track_retrieval', // last-retrieved.ts
'search.intent_patterns', // search/query-intent.ts
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index be6172718a..76831f6f36 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6468,7 +6468,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/mcp-unreadable-sources-notice.test.ts b/test/mcp-sources-not-readable.test.ts
similarity index 55%
rename from test/mcp-unreadable-sources-notice.test.ts
rename to test/mcp-sources-not-readable.test.ts
index d8fc327721..300ed57f44 100644
--- a/test/mcp-unreadable-sources-notice.test.ts
+++ b/test/mcp-sources-not-readable.test.ts
@@ -1,18 +1,19 @@
/**
- * GBRA-156: an unscoped remote read that reaches no source holding a page,
- * while pages sit in sources the connection cannot read, says so.
+ * GBRA-156: an unscoped remote read whose readable sources hold no page,
+ * while other sources hold pages, is refused instead of answering empty.
*
* 1. Protects: a token with no source grant reads the default source plus the
* federated ones. A new source is not federated by default, so a brain
- * whose pages all live in such sources answered every search with `[]`
- * and an `empty_retrieval` notice calling it a clean miss. The read now
- * carries a `sources_not_readable` notice whose fix is the host command
- * that makes the pages readable (federate the source, or grant the
- * connection), without naming any source the connection cannot read.
- * 2. Fails when: the notice is missing on an empty unscoped read whose scope
- * holds no page, it names a hidden source, it fires on a real miss inside
- * a scope that holds pages, or it fires for a connection whose operator
- * granted it sources (a token granted sources, or an OAuth client).
+ * whose pages all live in such sources answered every search with `[]`,
+ * which reads like a clean miss. The read is now refused with
+ * `sources_not_readable` (class host_only), whose fix is the host command
+ * that makes the pages readable (federate a source, with the user choosing
+ * which), without naming any source the connection cannot read.
+ * 2. Fails when: the refusal is missing on an unscoped read whose scope holds
+ * no page, it leaks a hidden source id or page text, it fires on a real
+ * miss inside a scope that holds pages, on a brain where no source holds a
+ * page, or for a connection whose operator granted it sources (a token
+ * granted sources, or an OAuth client), or for a read that names a source.
* 3. Existing coverage: `source_binding_narrowed` covers a bound stdio
* connection only (mcp-notice-channels).
* 4. No production seam: production serve-http app, real tokens.
@@ -22,24 +23,27 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importFromContent } from '../src/core/import-file.ts';
import { mintLegacyToken } from '../src/core/token-mint.ts';
-import { callTool, clientCredentialsToken, legacyToken, ownerCookie, registerOAuthClient, startServeHttp, type LiveServeHttp, type ToolResultWire } from './helpers/live-mcp-servers.ts';
+import { callTool, clientCredentialsToken, envelopeOf, legacyToken, ownerCookie, registerOAuthClient, startServeHttp, type LiveServeHttp, type ToolResultWire } from './helpers/live-mcp-servers.ts';
import { testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
const HIDDEN = 'source-hidden';
const CANARY = 'harbourcanary';
const QUERY = 'quillmarsh ledger';
-
-function noticeBlock(result: ToolResultWire, code: string): string | undefined {
- return result.content.map(c => c.text).find(t => t.startsWith(`[gbrain notice ${code} `));
-}
+const READS = [
+ ['search', { query: QUERY }],
+ ['search', { query: QUERY, match: 'keyword' }],
+ ['query', { query: QUERY, expand: false }],
+ ['list_pages', {}],
+ ['recall', { query: QUERY }],
+] as const;
function rows(result: ToolResultWire): unknown {
return JSON.parse(result.content[0]!.text);
}
for (const kind of testBackends()) {
- describe(`sources_not_readable notice (${kind})`, () => {
+ describe(`sources_not_readable refusal (${kind})`, () => {
let engine: BrainEngine;
let close: () => Promise<void>;
let serve: LiveServeHttp;
@@ -51,7 +55,6 @@ for (const kind of testBackends()) {
if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1), ('source-empty', 'source-empty') ON CONFLICT (id) DO NOTHING`, [HIDDEN]);
- await importFromContent(engine, 'notes/quillmarsh-ledger', `# Ledger\nThe quillmarsh ledger for the harbour team, ${CANARY}.`, { sourceId: HIDDEN, noEmbed: true });
serve = await startServeHttp(engine, { surface: 'full' });
noGrant = await legacyToken(engine, ['read']);
granted = (await mintLegacyToken(engine, { name: 'granted-empty', takesHolders: ['world'], scopes: ['read'], sourceGrant: ['source-empty'] })).token;
@@ -64,54 +67,69 @@ for (const kind of testBackends()) {
await close?.();
}, 60_000);
- for (const [tool, args] of [
- ['search', { query: QUERY }],
- ['search', { query: QUERY, match: 'keyword' }],
- ['query', { query: QUERY, expand: false }],
- ['list_pages', {}],
- ['recall', { query: QUERY }],
- ] as const) {
- test(`${tool} ${JSON.stringify(args)}: a no-grant token whose sources hold no page is told the pages are elsewhere`, async () => {
+ test('a brain where no source holds a page answers empty, as before', async () => {
+ const out = await callTool(serve.base, noGrant, 'search', { query: QUERY });
+ expect(out.isError).not.toBe(true);
+ expect(rows(out)).toEqual([]);
+ }, 60_000);
+
+ test('pages arrive in a source the no-grant floor cannot read', async () => {
+ await importFromContent(engine, 'notes/quillmarsh-ledger', `# Ledger\nThe quillmarsh ledger for the harbour team, ${CANARY}.`, { sourceId: HIDDEN, noEmbed: true });
+ });
+
+ for (const [tool, args] of READS) {
+ test(`${tool} ${JSON.stringify(args)}: a no-grant token whose sources hold no page is refused with the host fix`, async () => {
const out = await callTool(serve.base, noGrant, tool, args);
- expect(out.isError).not.toBe(true);
- expect(JSON.stringify(out.content)).not.toContain(CANARY);
- const block = noticeBlock(out, 'sources_not_readable');
- expect(block).toBeDefined();
- expect(block).toContain('kind=degraded');
- expect(block).toContain('gbrain sources federate');
- expect(block).not.toContain(HIDDEN);
+ expect(out.isError).toBe(true);
+ const env = envelopeOf(out);
+ expect(env.code).toBe('sources_not_readable');
+ expect(env.class).toBe('host_only');
+ expect(env.fix.argv).toEqual(['gbrain', 'sources', 'federate', '<source>']);
+ expect(env.fix.inputs?.[0]?.name).toBe('source');
+ const text = JSON.stringify(out.content);
+ expect(text).not.toContain(HIDDEN);
+ expect(text).not.toContain(CANARY);
}, 60_000);
}
- test('an OAuth client always carries a grant (at least its bound source), so it gets no notice', async () => {
+ test('an OAuth client always carries a grant (at least its bound source), so it is not refused', async () => {
const out = await callTool(serve.base, oauth, 'search', { query: QUERY });
+ expect(out.isError).not.toBe(true);
expect(rows(out)).toEqual([]);
- expect(noticeBlock(out, 'sources_not_readable')).toBeUndefined();
}, 60_000);
- test('a token the operator granted a source gets no notice (its scope is deliberate)', async () => {
+ test('a token the operator granted a source is not refused (its scope is deliberate)', async () => {
const out = await callTool(serve.base, granted, 'search', { query: QUERY });
+ expect(out.isError).not.toBe(true);
expect(rows(out)).toEqual([]);
- expect(noticeBlock(out, 'sources_not_readable')).toBeUndefined();
}, 60_000);
- test('naming a source explicitly gets no notice', async () => {
- const out = await callTool(serve.base, noGrant, 'search', { query: QUERY, source_id: 'default' });
- expect(rows(out)).toEqual([]);
- expect(noticeBlock(out, 'sources_not_readable')).toBeUndefined();
+ test('naming a source explicitly is not refused', async () => {
+ for (const scope of [{ source_id: 'default' }, { source_ids: ['default'] }]) {
+ const out = await callTool(serve.base, noGrant, 'search', { query: QUERY, ...scope });
+ expect(out.isError).not.toBe(true);
+ expect(rows(out)).toEqual([]);
+ }
}, 60_000);
- test('once the source is federated the same token reads the page, and a real miss carries no notice', async () => {
+ test('once the source is federated the same token reads the page, and a real miss is not refused', async () => {
await engine.executeRaw(`UPDATE sources SET config = COALESCE(config, '{}'::jsonb) || '{"federated": true}'::jsonb WHERE id = $1`, [HIDDEN]);
try {
const hit = await callTool(serve.base, noGrant, 'search', { query: QUERY });
expect(JSON.stringify(rows(hit))).toContain('quillmarsh-ledger');
const miss = await callTool(serve.base, noGrant, 'search', { query: 'zzyzx nothing matches this' });
+ expect(miss.isError).not.toBe(true);
expect(rows(miss)).toEqual([]);
- expect(noticeBlock(miss, 'sources_not_readable')).toBeUndefined();
} finally {
await engine.executeRaw(`UPDATE sources SET config = config - 'federated' WHERE id = $1`, [HIDDEN]);
}
}, 60_000);
+
+ test('a default source that holds a page but matches nothing answers empty, not refused', async () => {
+ await importFromContent(engine, 'notes/floor-note', '# Floor\nAn unrelated note in the default source.', { sourceId: 'default', noEmbed: true });
+ const out = await callTool(serve.base, noGrant, 'search', { query: QUERY });
+ expect(out.isError).not.toBe(true);
+ expect(rows(out)).toEqual([]);
+ }, 60_000);
});
}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 015b3eeec9..87b6ba8057 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -243,7 +243,7 @@ test/managed-sync-pinned-reads.test.ts
test/managed-sync-preparation-stalled-holds.test.ts
test/managed-sync-row-parity.test.ts
test/managed-sync-stale-group-head.test.ts
-test/mcp-unreadable-sources-notice.test.ts
+test/mcp-sources-not-readable.test.ts
test/migration-persistence-request-id-index.test.ts
test/migration-persistence-request-slug-index.test.ts
test/on-commit-embedding.serial.test.ts
@@ -423,6 +423,8 @@ test/schema-missing-tables.test.ts
test/schema-replay-deadlock-6143.test.ts
test/scripts/test-stress-postgres.test.ts
test/search-read-keyword-bound.test.ts
+test/search-remote-page-cap.test.ts
+test/search-vector-scope-parity.test.ts
test/search/page-rank-cut.test.ts
test/search/rerank-gate-hybrid.test.ts
test/search/rerank-gate-telemetry.test.ts
diff --git a/test/search-remote-page-cap.test.ts b/test/search-remote-page-cap.test.ts
new file mode 100644
index 0000000000..737a93b6cd
--- /dev/null
+++ b/test/search-remote-page-cap.test.ts
@@ -0,0 +1,149 @@
+/**
+ * GBRA-156: a remote `search` or `query` without `limit` returns every lexically
+ * matched page and at most `search.remote_page_cap` distinct pages in total.
+ *
+ * 1. Protects: with an embedding model on, the vector arm filled the mode's
+ * row limit with every page it could reach, so one remote question read
+ * most of a small brain (a median 12 pages a call against keyword's 2 on
+ * the harness ladder). Vector-only pages now only fill the result up to
+ * the cap; keyword, title and identity matches are never cut.
+ * 2. Fails when: a remote call without limit returns more vector-only pages
+ * than the cap, a lexically matched page is dropped, an explicit limit, a
+ * trusted local call or a cap of 0 is cut, or the cut is not reported in
+ * `_meta.retrieval.page_cap`.
+ * 3. Existing coverage: autocut and adaptive return trim results only with a
+ * reranker or an opt-in config; nothing bounded a remote default.
+ * 4. No production seam: production serve-http app and real tokens; the
+ * embedding provider is a deterministic in-process transport.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { DEFAULT_REMOTE_PAGE_CAP, REMOTE_PAGE_CAP_KEY, capVectorOnlyPages } from '../src/core/search/remote-page-cap.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { callTool, legacyToken, startServeHttp, type LiveServeHttp, type ToolResultWire } from './helpers/live-mcp-servers.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const VEC = Array.from({ length: 1536 }, (_, i) => (i === 0 ? 1 : 0.01));
+const LEXICAL = ['alpha', 'bravo', 'charlie', 'delta', 'echo'];
+const VECTOR_ONLY = ['foxtrot', 'golf', 'hotel', 'india', 'juliet', 'kilo', 'lima'];
+
+function slugsOf(out: ToolResultWire): string[] {
+ return [...new Set((JSON.parse(out.content[0]!.text) as Array<{ slug: string }>).map(r => r.slug))];
+}
+
+function row(slug: string, extra: Partial<SearchResult> = {}): SearchResult {
+ return { slug, page_id: 1, title: slug, type: 'note', chunk_text: '', chunk_source: 'compiled_truth', chunk_id: 1, chunk_index: 0, score: 1, stale: false, source_id: 'default', ...extra } as SearchResult;
+}
+
+describe('capVectorOnlyPages', () => {
+ test('keeps every lexical page and fills with vector-only pages up to the cap, in rank order', () => {
+ const rows = [row('v1'), row('k1', { keyword_hit: true }), row('v2'), row('v1', { chunk_id: 2 }), row('v3'), row('t1', { alias_hit: true }), row('v4')];
+ const out = capVectorOnlyPages(rows, 3);
+ expect(out.rows.map(r => r.slug)).toEqual(['v1', 'k1', 'v1', 't1']);
+ expect(out.meta).toEqual({ cap: 3, kept_pages: 3, dropped_pages: 3 });
+ });
+
+ test('more lexical pages than the cap are all kept and no vector-only page is added', () => {
+ const rows = [row('k1', { keyword_hit: true }), row('v1'), row('k2', { exact_lookup: 'slug' }), row('k3', { relational_pinned: true }), row('k4', { keyword_hit: true, keyword_relaxed: true })];
+ expect(capVectorOnlyPages(rows, 2).rows.map(r => r.slug)).toEqual(['k1', 'k2', 'k3', 'k4']);
+ });
+
+ test('pages are distinct per source, and a null cap or a set under the cap is returned untouched', () => {
+ const rows = [row('same', { source_id: 'source-a' }), row('same', { source_id: 'source-b' }), row('other')];
+ expect(capVectorOnlyPages(rows, 2).rows.map(r => r.source_id)).toEqual(['source-a', 'source-b']);
+ expect(capVectorOnlyPages(rows, null)).toEqual({ rows });
+ expect(capVectorOnlyPages(rows, 5)).toEqual({ rows });
+ });
+});
+
+for (const kind of testBackends()) {
+ describe(`remote page cap (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let serve: LiveServeHttp;
+ let token: string;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ for (const name of [...LEXICAL, ...VECTOR_ONLY]) {
+ const text = LEXICAL.includes(name) ? `The quillmarsh ledger, page ${name}.` : `Notes on page ${name}.`;
+ await engine.putPage(`notes/${name}`, { type: 'note', title: `Page ${name}`, compiled_truth: text, timeline: '' });
+ await installFixtureChunks(engine, `notes/${name}`, [{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: new Float32Array(VEC), modality: 'text' }]);
+ }
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async (args: any) => ({ embeddings: args.values.map(() => VEC) }) as any);
+ serve = await startServeHttp(engine, { surface: 'full' });
+ token = await legacyToken(engine, ['read']);
+ }, 180_000);
+
+ afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await serve?.close();
+ await close?.();
+ }, 60_000);
+
+ for (const tool of ['search', 'query'] as const) {
+ const base = tool === 'query' ? { expand: false } : {};
+
+ test(`${tool}: a query no page matches lexically returns the top vector pages up to the default cap, and says so in _meta and to the model`, async () => {
+ const out = await callTool(serve.base, token, tool, { query: 'saltpan orbit', ...base });
+ expect(slugsOf(out)).toHaveLength(DEFAULT_REMOTE_PAGE_CAP);
+ const dropped = LEXICAL.length + VECTOR_ONLY.length - DEFAULT_REMOTE_PAGE_CAP;
+ expect((out._meta as any)?.retrieval?.page_cap).toEqual({ cap: DEFAULT_REMOTE_PAGE_CAP, kept_pages: DEFAULT_REMOTE_PAGE_CAP, dropped_pages: dropped });
+ expect(out.content.slice(1).map(c => c.text)).toContain(`[gbrain search] Showing ${DEFAULT_REMOTE_PAGE_CAP} pages: ${dropped} more matched only by meaning and were left out (default remote cap ${DEFAULT_REMOTE_PAGE_CAP}). Pass limit to read them.`);
+ }, 60_000);
+
+ test(`${tool}: a call the cap leaves alone carries no cap line`, async () => {
+ const out = await callTool(serve.base, token, tool, { query: 'saltpan orbit', limit: 20, ...base });
+ expect((out._meta as any)?.retrieval?.page_cap).toBeUndefined();
+ expect(out.content.slice(1).some(c => c.text.includes('default remote cap'))).toBe(false);
+ }, 60_000);
+
+ test(`${tool}: every lexically matched page survives the cap, and vector-only pages are left out`, async () => {
+ const slugs = slugsOf(await callTool(serve.base, token, tool, { query: 'quillmarsh ledger', ...base }));
+ expect(slugs.sort()).toEqual(LEXICAL.map(n => `notes/${n}`).sort());
+ }, 60_000);
+
+ test(`${tool}: with no embedding model every keyword match comes back, past the cap`, async () => {
+ resetGateway();
+ try {
+ const out = await callTool(serve.base, token, tool, { query: 'quillmarsh ledger', ...base });
+ expect(slugsOf(out).sort()).toEqual(LEXICAL.map(n => `notes/${n}`).sort());
+ expect((out._meta as any)?.retrieval?.page_cap).toBeUndefined();
+ } finally {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async (args: any) => ({ embeddings: args.values.map(() => VEC) }) as any);
+ }
+ }, 60_000);
+
+ test(`${tool}: an explicit limit keeps today's rows`, async () => {
+ const slugs = slugsOf(await callTool(serve.base, token, tool, { query: 'saltpan orbit', limit: 20, ...base }));
+ expect(slugs).toHaveLength(LEXICAL.length + VECTOR_ONLY.length);
+ }, 60_000);
+
+ test(`${tool}: search.remote_page_cap sets the cap and 0 turns it off`, async () => {
+ try {
+ await engine.setConfig(REMOTE_PAGE_CAP_KEY, '5');
+ expect(slugsOf(await callTool(serve.base, token, tool, { query: 'saltpan orbit', ...base }))).toHaveLength(5);
+ await engine.setConfig(REMOTE_PAGE_CAP_KEY, '0');
+ expect(slugsOf(await callTool(serve.base, token, tool, { query: 'saltpan orbit', ...base })).length).toBeGreaterThan(5);
+ } finally {
+ await engine.unsetConfig(REMOTE_PAGE_CAP_KEY);
+ }
+ }, 60_000);
+
+ test(`${tool}: a trusted local call is not capped`, async () => {
+ const ctx = { engine, config: null, logger: console, dryRun: false, remote: false } as never;
+ const rows = await operationsByName[tool]!.handler(ctx, { query: 'saltpan orbit', ...base }) as Array<{ slug: string }>;
+ expect(new Set(rows.map(r => r.slug)).size).toBeGreaterThan(DEFAULT_REMOTE_PAGE_CAP);
+ }, 60_000);
+ }
+ });
+}
diff --git a/test/search-vector-scope-parity.test.ts b/test/search-vector-scope-parity.test.ts
new file mode 100644
index 0000000000..5d18550dba
--- /dev/null
+++ b/test/search-vector-scope-parity.test.ts
@@ -0,0 +1,145 @@
+/**
+ * GBRA-156: every vector path of `search` and `query` reads exactly the source
+ * scope the keyword path reads, for a remote caller.
+ *
+ * 1. Protects: a token's grant (default floor plus federated sources, a
+ * scalar OAuth binding, a multi-source grant, no grant at all) and the
+ * per-call `source_id` / `source_ids` narrowing hold on the hybrid vector
+ * arm, the embed-failure keyword fallback (searchVectorFallback), the
+ * no-provider keyword path, `match: "keyword"`, query's text path and
+ * query's image branch, not only on keyword search.
+ * 2. Fails when: any path returns a page from a source outside the caller's
+ * scope, or a path misses a source the caller may read (every page is
+ * equally similar to the query, so a correct path returns them all).
+ * 3. Existing coverage: keyword search under member grants
+ * (e2e/serve-http-member-tokens), local federation
+ * (local-federated-search-scope); none drove the vector arm, the vector
+ * fallback, the no-provider path or the image branch under each grant.
+ * 4. No production seam: the production serve-http app and real tokens; the
+ * embedding providers are a deterministic in-process transport and a
+ * loopback stand-in for the multimodal endpoint.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { callTool, clientCredentialsToken, envelopeOf, legacyToken, ownerCookie, registerOAuthClient, startServeHttp, type LiveServeHttp, type ToolResultWire } from './helpers/live-mcp-servers.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const SOURCES = ['default', 'source-a', 'source-b', 'source-c'] as const;
+const FEDERATED = 'source-a';
+const QUERY = 'quillmarsh ledger';
+// Matches no page lexically, so only the vector arm can return a row.
+const VECTOR_QUERY = 'saltpan orbit';
+const TEXT_VEC = Array.from({ length: 1536 }, (_, i) => (i === 0 ? 1 : 0.01));
+const IMAGE_VEC = Array.from({ length: 1024 }, (_, i) => (i === 0 ? 1 : 0.01));
+const IMAGE = Buffer.from('fixture image bytes').toString('base64');
+
+type Provider = 'vector' | 'embed_fails' | 'no_provider';
+
+let voyage: ReturnType<typeof Bun.serve>;
+
+function useProvider(provider: Provider): void {
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ embedding_multimodal_model: 'voyage:voyage-multimodal-3',
+ base_urls: { voyage: `http://127.0.0.1:${voyage.port}/v1` },
+ env: provider === 'no_provider' ? {} : { OPENAI_API_KEY: 'sk-test', VOYAGE_API_KEY: 'vk-test' },
+ });
+ __setEmbedTransportForTests(async (args: any) => {
+ if (provider === 'embed_fails') throw new Error('embedding provider unavailable (fixture)');
+ return { embeddings: args.values.map(() => TEXT_VEC) } as any;
+ });
+}
+
+function sourcesOf(out: ToolResultWire): string[] {
+ const rows = JSON.parse(out.content[0]!.text) as Array<{ slug: string }>;
+ return [...new Set(rows.map(r => r.slug.split('/')[1]!.replace(/^(?:note|image)-/, '')))].sort();
+}
+
+for (const kind of testBackends()) {
+ describe(`vector paths read the keyword path's source scope (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let serve: LiveServeHttp;
+ const tokens: Record<string, string> = {};
+
+ beforeAll(async () => {
+ voyage = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: async (req) => {
+ const body = await req.json() as { inputs?: unknown[]; documents?: unknown[] };
+ if (new URL(req.url).pathname.endsWith('/rerank')) {
+ return Response.json({ data: (body.documents ?? []).map((_, index) => ({ index, relevance_score: 0.5 })), usage: { total_tokens: 1 } });
+ }
+ return Response.json({ data: (body.inputs ?? []).map(() => ({ embedding: IMAGE_VEC })), usage: { total_tokens: 1 } });
+ } });
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ for (const id of SOURCES.slice(1)) {
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::text::jsonb) ON CONFLICT (id) DO NOTHING`,
+ [id, JSON.stringify(id === FEDERATED ? { federated: true } : {})]);
+ }
+ for (const sourceId of SOURCES) {
+ const text = `The quillmarsh ledger kept by ${sourceId}.`;
+ await engine.putPage(`notes/note-${sourceId}`, { type: 'note', title: `Ledger ${sourceId}`, compiled_truth: text, timeline: '' }, { sourceId });
+ await installFixtureChunks(engine, `notes/note-${sourceId}`, [{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: new Float32Array(TEXT_VEC), modality: 'text' }], { sourceId });
+ await engine.putPage(`photos/image-${sourceId}`, { type: 'image', page_kind: 'image', title: `Photo ${sourceId}`, compiled_truth: '', timeline: '' } as never, { sourceId });
+ await installFixtureChunks(engine, `photos/image-${sourceId}`, [{ chunk_index: 0, chunk_text: `photo ${sourceId}`, chunk_source: 'image_asset', embedding_image: new Float32Array(IMAGE_VEC), modality: 'image' } as never], { sourceId });
+ }
+ serve = await startServeHttp(engine, { surface: 'full' });
+ tokens.floor = await legacyToken(engine, ['read']);
+ tokens.granted = (await mintLegacyToken(engine, { name: 'granted-bc', takesHolders: ['world'], scopes: ['read'], sourceGrant: ['source-b', 'source-c'] })).token;
+ tokens.none = (await mintLegacyToken(engine, { name: 'granted-none', takesHolders: ['world'], scopes: ['read'], sourceGrant: [] })).token;
+ const client = await registerOAuthClient(serve, await ownerCookie(serve), 'read');
+ tokens.oauth = await clientCredentialsToken(serve, client.clientId, client.clientSecret, 'read');
+ }, 180_000);
+
+ afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await serve?.close();
+ await close?.();
+ voyage?.stop(true);
+ }, 60_000);
+
+ // Each case: the token, the per-call scope params, and the sources it must read (null: refused).
+ const CASES: Array<{ name: string; token: string; scope: Record<string, unknown>; reads: string[] | null }> = [
+ { name: 'no grant: the default source plus federated sources', token: 'floor', scope: {}, reads: ['default', 'source-a'] },
+ { name: 'no grant, source_id names a federated source', token: 'floor', scope: { source_id: 'source-a' }, reads: ['source-a'] },
+ { name: 'no grant, source_id names a non-federated source', token: 'floor', scope: { source_id: 'source-b' }, reads: null },
+ { name: 'OAuth client: its scalar bound source', token: 'oauth', scope: {}, reads: ['default'] },
+ { name: 'granted two sources', token: 'granted', scope: {}, reads: ['source-b', 'source-c'] },
+ { name: 'granted two sources, source_ids narrows to one', token: 'granted', scope: { source_ids: ['source-c'] }, reads: ['source-c'] },
+ { name: 'granted two sources, source_ids names one outside the grant', token: 'granted', scope: { source_ids: ['source-a'] }, reads: null },
+ { name: 'granted two sources, source_id and source_ids intersect', token: 'granted', scope: { source_id: 'source-b', source_ids: ['source-b', 'source-c'] }, reads: ['source-b'] },
+ { name: 'grant naming no source', token: 'none', scope: {}, reads: null },
+ ];
+ const PATHS: Array<{ name: string; provider: Provider; tool: 'search' | 'query'; args: Record<string, unknown> }> = [
+ { name: 'search, hybrid vector arm', provider: 'vector', tool: 'search', args: { query: VECTOR_QUERY } },
+ { name: 'search, hybrid with both arms', provider: 'vector', tool: 'search', args: { query: QUERY } },
+ { name: 'search, embed failure keyword fallback', provider: 'embed_fails', tool: 'search', args: { query: QUERY } },
+ { name: 'search, no-provider keyword path', provider: 'no_provider', tool: 'search', args: { query: QUERY } },
+ { name: 'search, match keyword', provider: 'vector', tool: 'search', args: { query: QUERY, match: 'keyword' } },
+ { name: 'query, text vector arm', provider: 'vector', tool: 'query', args: { query: VECTOR_QUERY, expand: false } },
+ { name: 'query, embed failure keyword fallback', provider: 'embed_fails', tool: 'query', args: { query: QUERY, expand: false } },
+ { name: 'query, image branch', provider: 'vector', tool: 'query', args: { image: IMAGE, image_mime: 'image/png' } },
+ ];
+
+ for (const path of PATHS) {
+ test(`${path.name}: every grant and per-call scope reads exactly its sources`, async () => {
+ useProvider(path.provider);
+ for (const c of CASES) {
+ const out = await callTool(serve.base, tokens[c.token]!, path.tool, { ...path.args, ...c.scope, limit: 50 });
+ if (c.reads === null) {
+ expect({ case: c.name, isError: out.isError, code: envelopeOf(out).code }).toMatchObject({ case: c.name, isError: true });
+ expect(JSON.stringify(out.content)).not.toContain('quillmarsh ledger kept');
+ continue;
+ }
+ expect({ case: c.name, isError: out.isError === true, sources: sourcesOf(out) }).toEqual({ case: c.name, isError: false, sources: c.reads });
+ }
+ }, 120_000);
+ }
+ });
+}
diff --git a/test/sources-add-federation-warning.test.ts b/test/sources-add-federation-warning.test.ts
index bde50d65e5..a23e865504 100644
--- a/test/sources-add-federation-warning.test.ts
+++ b/test/sources-add-federation-warning.test.ts
@@ -6,9 +6,14 @@
* never reads its pages, and its searches answer empty. The stored default
* stays non-federated; the command now says what that means on stderr,
* with the two commands that change it.
+ * When the sources such a connection reads (the default source and the
+ * federated ones) hold no page, the add also prints the federate command
+ * as its next step on stdout, and as `next` under --json.
* 2. Fails when: the default add prints no warning, the warning lacks the
* federate or grant command, a --federated or explicit --no-federated add
- * warns, or the stored default flips to federated.
+ * warns, the stored default flips to federated, the next step is missing
+ * while the no-grant floor holds no page, or it is printed while the floor
+ * holds pages.
* 3. Existing coverage: the stdout `federated: false` line only.
* 4. No production seam: the real command on PGLite, console spies only.
*/
@@ -75,5 +80,30 @@ describe('sources add federation warning', () => {
const { stdout, stderr } = await add(['source-c', '--no-federated']);
expect(stdout).toContain('federated: false');
expect(stderr).not.toContain('is not federated');
+ expect(stdout).not.toContain('next:');
+ });
+});
+
+describe('sources add next step when the no-grant floor holds no page', () => {
+ test('a default add on a brain whose default and federated sources hold no page prints the federate command on stdout', async () => {
+ const { stdout } = await add(['source-d']);
+ expect(stdout).toContain('next: gbrain sources federate source-d');
+ });
+
+ test('--json carries the same step as next, with the human lines on stderr', async () => {
+ const { stdout, stderr } = await add(['source-e', '--json']);
+ const out = JSON.parse(stdout);
+ expect(out).toMatchObject({ id: 'source-e', federated: false, next: { command: 'gbrain sources federate source-e', argv: ['gbrain', 'sources', 'federate', 'source-e'] } });
+ expect(stderr).toContain('Created source "source-e"');
+ });
+
+ test('once the floor holds a page, the add warns but prints no next step', async () => {
+ await engine.putPage('notes/floor-page', { type: 'note', title: 'Floor', compiled_truth: 'A page in the default source.', timeline: '' });
+ const human = await add(['source-f']);
+ expect(human.stderr).toContain('source "source-f" is not federated');
+ expect(human.stdout).not.toContain('next:');
+ const json = JSON.parse((await add(['source-g', '--json'])).stdout);
+ expect(json).toMatchObject({ id: 'source-g', federated: false });
+ expect(json.next).toBeUndefined();
});
});