Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-156: query handler stays within its size baseline; page-cap key-files entry joins the evidence page
garrytanbc060e32b539
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex dbcb1394e7..4e74cd4de0 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -27,7 +27,6 @@ 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-search-evidence.md b/docs/architecture/key-files/core-search-evidence.mdindex 63a810d935..9b135f8509 100644--- a/docs/architecture/key-files/core-search-evidence.md+++ b/docs/architecture/key-files/core-search-evidence.md@@ -1,7 +1,8 @@-# Key files: Core Search (evidence blocks)+# Key files: Core Search (evidence blocks, remote page cap)[Subsystem index](../KEY_FILES.md) · [Core Search (2/2)](core-search-2.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.- `src/core/search/evidence-tail-trim.ts` — the protected tail trim (`search.evidence_tail_trim`, default off, GBRA-156). `resolveEvidencePlan` sets `EvidencePlan.tailTrim` only for `unit: auto` with the key on; `deliverEvidence` calls `trimEvidenceTail(results, opts.query)` on the rank-order delivered rows after redaction and before the token totals, and only when `DeliverOptions.query` is set (`search`/`query` pass `p.query`; the library `assembleEvidenceForHits` passes `input.query` and frozen hits may carry `score`; the `assemble_evidence` op passes neither, so the trim never runs there). Rows past `TAIL_TRIM_PROTECTED` = 3 that are whole-conversation blocks (`delivered.reason` `conversation_type`/`conversation_slug`) and score under `TAIL_TRIM_SCORE_FRACTION` = 0.5 of rank one are dropped, unless their `chunk_text` holds at least `TAIL_TRIM_TERM_FRACTION` = 0.8 of rank one's share of the query's terms (`queryTerms`: letter/digit runs, stopwords and single characters dropped, cut to six characters). Rank one's score must be a positive finite number and every row's finite, or nothing changes. `delivery.tail_trim` is `{ dropped, kept_by_query_terms }`; `dropped_reasons.tail_trim` counts drops. Pinned by `test/evidence-tail-trim.test.ts` (the knowledge-update regression case).+- `src/core/search/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`). Every vector path (the hybrid vector arm, the embed-failure fallback, the `query` image branch) reads the keyword path's source scope (`test/search-vector-scope-parity.test.ts`).diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 6151ea912d..96d74abd8a 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`. 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.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-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/src/core/ops/search.ts b/src/core/ops/search.tsindex 4fd7e941ad..ec369d76e8 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -1039,13 +1039,12 @@ const query: Operation = {const typeFilter = await setup(() => reconcileTypeFilter(ctx, querySourceScope, excludePrivate, types));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));+ const [explainPrep, pageCap] = await setup(() => Promise.all([prepareExplainTarget(ctx, p, querySourceScope, excludePrivate, 'query'), 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 capped = capVectorOnlyPages(await hybridSearchCached(ctx.engine, queryText, {+ let { rows: results, meta: pageCapMeta } = 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@@ -1101,7 +1100,6 @@ const query: Operation = {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 },@@ -1187,8 +1185,7 @@ const query: Operation = {crag.escalated = true;crag.escalated_confidence = regraded.level;if (confidenceRank(regraded.level) > confidenceRank(grade.level)) {- capped = capVectorOnlyPages(escalated.slice(0, effectiveLimit), pageCap);- results = capped.rows;+ ({ rows: results, meta: pageCapMeta } = capVectorOnlyPages(escalated.slice(0, effectiveLimit), pageCap));capturedMeta = escalatedMeta;grade = regraded;crag.confidence = regraded.level;@@ -1269,7 +1266,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 } : {}), ...(capped.meta ? { page_cap: capped.meta } : {}) }, 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 } : {}), ...(pageCapMeta ? { page_cap: pageCapMeta } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));},scope: 'read', mutating: false,cliHints: { name: 'query', positional: ['query'] },