Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): per-request source_ids on search and query (GBRA-156 item 3)
garrytana6f5b14f16c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c75d688c3a..3135e19a75 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,23 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.433.0] - 2026-10-24++**`search` and `query` take `source_ids`: one request can be narrowed to the sources the person it serves may see, on a shared brain with one source per member or project. The list only narrows; the token's grant stays the boundary.**++### What changed++| Situation | Before | Now |+|---|---|---|+| An agent acting for one member of a shared brain searches | every source the token can read came back; only one `source_id` (or all) could be named | `source_ids: ["source-a", "source-c"]` (CLI `--source-ids source-a,source-c`) reads only those sources, in every arm: keyword, vector, title, other names, entity anchoring, saved facts, the CRAG re-run, think escalation and evidence delivery |+| A remote agent lists a source outside its grant | not possible | `permission_denied` for the whole request, as for `source_id`; a removed or archived source is `unknown_source` |+| `source_ids` with `source_id`, or an empty list | not possible | the request reads the sources in both; when none remain, nothing is searched and an `empty_retrieval` notice says why (never a fallback to the wider scope) |++### What to watch for after you upgrade++- For a bot acting for several members, give each member a token granted only that member's sources (`gbrain auth rescope --token <name> --sources <ids>`, or `--client <client_id>`); `source_ids` narrows inside a grant and is not a separation between members. See [multi-source brains](docs/guides/multi-source-brains.md#a-bot-acting-for-many-members).+- Nothing is rewritten on upgrade, and there is no schema migration.+## [0.60.428.0] - 2026-10-24**Production agents can now follow a stable release channel: a release a maintainer promotes only after the production-shaped soak passed on its exact git tree. `gbrain upgrade` also restarts every gbrain process on the host onto the new build and verifies that one build runs, and doctor fails when two builds run.**diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 2d0c277458..162e66d804 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -50,7 +50,8 @@ 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`). `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`).+- `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 it 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`).+- `src/core/ops/search-source-scope.ts` — the per-request source scope of `search` and `query`: `source_id` through `federatedSearchScope`, narrowed by `source_ids` (`parseSourceIdsParam`: trimmed, deduped, validated; `__all__` refused). 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` so the handlers search nothing. Tests: `test/search/search-source-ids.test.ts` (PGLite; Postgres via `test/e2e/search-source-ids-postgres.test.ts`), `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/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 2119485405..4da53e7980 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -137,6 +137,50 @@ still go to the bound source only.rule: an explicit `source_id` must be inside the connection's own source orgrant.+### Narrow one request with `source_ids`++`search` and `query` take `source_ids`, a list of source ids (CLI:+`--source-ids source-a,source-b`). The request reads only those sources:++- Each id is checked exactly like an explicit `source_id`. A remote agent+ naming a source outside its grant gets `permission_denied` for the whole+ request, and a removed or archived source gets `unknown_source`. So the+ list can narrow a request but never widen it.+- With `source_id` as well, the request reads the sources in both+ (`source_id: "__all__"` keeps the list). If none are left, or the list is+ empty, nothing is searched: the result is empty with an+ `empty_retrieval` notice, never a fallback to the wider scope.+- `__all__` and malformed ids in the list are `invalid_params`.++Every part of the request reads the narrowed sources: keyword, vector and+title matches, other names, entity anchoring, saved facts, the CRAG re-run,+think escalation and evidence delivery.++**Say to your agent:** *"Search my brain for the acme-example renewal, but+only in source-a."*++### A bot acting for many members++A shared brain often holds one source per member or project, with one bot+answering for several people. Give each member their own token, granted only+the sources that member may read, and send each member's requests with that+member's token:++```bash+gbrain auth create bot-alice-example+gbrain auth rescope --token bot-alice-example --sources source-a+# OAuth client instead of a bearer token:+gbrain auth rescope --client <client_id> --sources source-a+```++The token's grant is the security boundary: the server scopes every call to+the grant of the token that made it, whatever the call's arguments say.+`source_ids` is a convenience inside that boundary. A bot holding one token+granted several sources can pass `source_ids` to keep one request to the+current member's sources, but a prompt-injected or buggy bot can omit it, so+it does not separate members who must not see each other's pages. Use+per-member tokens for that, and `source_ids` to narrow further.+### Links, backlinks and the graph across sources`gbrain links`, `gbrain backlinks` and `gbrain graph` (MCP: `get_links`,diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex eaa2a4592e..9108149760 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -229,6 +229,11 @@ requests. Added scopes require a fresh token; refresh cannot widen the originaltoken's scope ceiling. Native OAuth clients must reconnect and obtain freshowner approval. TTL changes affect future tokens only.+For one bot acting for several members of a shared brain, give each member a+separate client or token restricted to that member's sources. The grant is the+security boundary; a request's `source_ids` can only narrow inside it. See+[a bot acting for many members](../guides/multi-source-brains.md#a-bot-acting-for-many-members).+New `memory-reader`, `memory-writer` and `coding-agent` grants are callable andlisted on the full surface; their operation snapshot is still the ceiling, so areader still has no write operation. `delegating-agent` grants keep the starterdiff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 2ee7cf1e52..9326030f7d 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -1304,6 +1304,13 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "string","description": "One source, or '__all__'."},+ "source_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Narrow to these sources ([] = none)."+ },"types": {"type": "array","items": {@@ -1519,6 +1526,13 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "string","description": "One source, or '__all__'."},+ "source_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Narrow to these sources ([] = none)."+ },"cross_modal": {"type": "string","enum": [diff --git a/src/core/ops/search-source-scope.ts b/src/core/ops/search-source-scope.tsnew file mode 100644index 0000000000..e8065a44ba--- /dev/null+++ b/src/core/ops/search-source-scope.ts@@ -0,0 +1,61 @@+/**+ * The per-request source scope of `search` and `query`: the explicit+ * `source_id` and the narrowing `source_ids` list, resolved through the one+ * trust+grant resolver (`federatedSearchScope`) and the #4620 liveness check.+ *+ * Each `source_ids` entry is authorized exactly as an explicit `source_id`+ * is: a remote caller naming a source outside its grant (or explicit-read+ * set) gets permission_denied for the whole request, and a removed or+ * archived source gets unknown_source. So the list can only narrow a request+ * to sources the caller could already read; the token's grant stays the+ * security boundary. With `source_id` too, the request reads their+ * intersection (`__all__` keeps the list). An empty result searches+ * nothing: the handlers return no rows rather than fall back to the ambient+ * or full scope, and an `empty_retrieval` notice says why.+ */+import { ALL_SOURCES, isValidSourceId } from '../source-id.ts';+import type { OperationContext } from './contract.ts';+import { assertExplicitSourceLive, federatedSearchScope } from './context.ts';+import { invalidParam } from './op-fix.ts';++export const SOURCE_IDS_PARAM = {+ type: 'array' as const,+ items: { type: 'string' as const },+ description: 'Narrow to these sources ([] = none).',+};++/** `source_ids` as distinct, trimmed source ids; undefined when absent. */+export function parseSourceIdsParam(ctx: OperationContext, tool: 'search' | 'query', raw: unknown): string[] | undefined {+ if (raw === undefined || raw === null) return undefined;+ const example = ctx.remote === false ? 'source-a,source-b' : ['source-a', 'source-b'];+ if (!Array.isArray(raw)) throw invalidParam(ctx, tool, 'source_ids', '`source_ids` must be an array of source ids.', { example });+ const ids = new Set<string>();+ for (const entry of raw) {+ const id = typeof entry === 'string' ? entry.trim() : entry;+ if (id === ALL_SOURCES) {+ throw invalidParam(ctx, tool, 'source_ids', `\`source_ids\` narrows a request to named sources; '${ALL_SOURCES}' is not one. Omit source_ids to read every source you can.`, { example });+ }+ if (typeof id !== 'string' || !isValidSourceId(id)) {+ throw invalidParam(ctx, tool, 'source_ids', `\`source_ids\` entry ${JSON.stringify(entry)} is not a source id (1-32 lowercase letters, digits or interior hyphens).`, { example });+ }+ ids.add(id);+ }+ return [...ids];+}++/** The sources one search/query request reads; `sourceIds: []` means it reads none. */+export async function requestSourceScope(ctx: OperationContext, sourceIdParam: string | undefined, sourceIds: string[] | undefined): Promise<{ sourceId?: string; sourceIds?: string[] }> {+ const scope = federatedSearchScope(ctx, sourceIdParam);+ if (sourceIds === undefined) {+ await assertExplicitSourceLive(ctx, sourceIdParam);+ return scope;+ }+ for (const id of sourceIds) federatedSearchScope(ctx, id);+ for (const id of [sourceIdParam, ...sourceIds]) await assertExplicitSourceLive(ctx, id);+ const narrowed = sourceIdParam === undefined || sourceIdParam === ALL_SOURCES ? sourceIds : sourceIds.filter(id => id === sourceIdParam);+ if (narrowed.length === 0) {+ ctx.emitNotice?.({ code: 'empty_retrieval', kind: 'info',+ why: sourceIds.length === 0 ? 'source_ids was empty, so no source was searched.' : `source_ids does not include source_id '${sourceIdParam}', so no source was searched.` });+ }+ return { sourceIds: narrowed };+}diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 6af0998086..a1dc232feb 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -69,9 +69,8 @@ import { loadPageTrust, stampPageTrust } from '../eligibility/stamp.ts';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 {- assertExplicitSourceLive,- federatedSearchScope,parseSourceIdParam,resolvePerCallMode,stampDeepResearchIds,@@ -99,9 +98,9 @@ async function resolveEffectiveLimit(ctx: OperationContext, p: Record<string, untype SourceScope = { sourceId?: string; sourceIds?: string[]; minTrust?: TrustTier };-/** The caller's source scope plus its effective read floor (#5575: token floor, `min_trust`, read policy). */-async function trustedSearchScope(ctx: OperationContext, p: Record<string, unknown>, sourceIdParam: string | undefined): Promise<SourceScope> {- const scope = federatedSearchScope(ctx, sourceIdParam);+/** The caller's source scope (`source_id`, narrowed by `source_ids`) plus its effective read floor (#5575: token floor, `min_trust`, read policy). */+async function trustedSearchScope(ctx: OperationContext, p: Record<string, unknown>, sourceIdParam: string | undefined, sourceIds?: string[]): Promise<SourceScope> {+ const scope = await requestSourceScope(ctx, sourceIdParam, sourceIds);const { floor } = await resolveReadEligibility(ctx, { minTrust: p.min_trust });return floor ? { ...scope, minTrust: floor } : scope;}@@ -719,6 +718,7 @@ const search: Operation = {// #4398: per-call source scope, mirroring `query` — MCP clients passed it// here, got 'unknown parameter ignored', and read UNSCOPED results.source_id: { type: 'string', description: SOURCE_ID_PARAM_DESCRIPTION },+ source_ids: SOURCE_IDS_PARAM,// #3985: multi-type filter (plumbing shipped v0.33; exposed here).types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },where: WHERE_PARAM,@@ -756,11 +756,11 @@ const search: Operation = {// (invalid ids throw invalid_params) then resolved through the single// trust+grant resolver (resolveRequestedScope inside federatedSearchScope)// — out-of-grant ids throw permission_denied, and #2561's unqualified- // trusted-local federated span is unchanged.+ // trusted-local federated span is unchanged. `source_ids` only narrows it+ // (search-source-scope.ts); #4620 liveness runs after the grant check.const sourceIdParam = parseSourceIdParam(p.source_id, 'search', { allowAll: true });- const scope = await setup(() => trustedSearchScope(ctx, p, sourceIdParam));- // #4620: an explicit source_id must name a live source (after the grant check).- await setup(() => assertExplicitSourceLive(ctx, sourceIdParam));+ const scope = await setup(() => trustedSearchScope(ctx, p, sourceIdParam, parseSourceIdsParam(ctx, 'search', p.source_ids)));+ if (scope.sourceIds?.length === 0) return [];// #4352 — untrusted callers never see `visibility: private` pages// (config-gated; trusted local CLI unchanged).const excludePrivate = await setup(() => resolveExcludePrivatePages(ctx.engine, ctx.remote));@@ -916,6 +916,7 @@ const query: Operation = {since: { type: 'string', description: 'On/after: YYYY-MM-DD or 7d/2w/1y.' },until: { type: 'string', description: 'On/before.' },source_id: { type: 'string', description: SOURCE_ID_PARAM_DESCRIPTION },+ source_ids: SOURCE_IDS_PARAM,cross_modal: { type: 'string', enum: ['text', 'image', 'both', 'auto'], description: 'Default auto.' },embedding_column: { type: 'string', description: 'Registered embedding column.' },adaptive_return: { type: 'boolean', description: 'true for one answer (fewer rows, never empty); omit for breadth.' },@@ -952,9 +953,9 @@ const query: Operation = {const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;// #2561: unqualified trusted-local query spans federated sources (per-call// source_id / remote grants still resolve through resolveRequestedScope).- const querySourceScope = await setup(() => trustedSearchScope(ctx, p, sourceIdParam));- // #4620: an explicit source_id must name a live source (after the grant check).- await setup(() => assertExplicitSourceLive(ctx, sourceIdParam));+ // `source_ids` only narrows it (search-source-scope.ts); #4620 liveness runs after the grant check.+ const querySourceScope = await setup(() => trustedSearchScope(ctx, p, sourceIdParam, parseSourceIdsParam(ctx, 'query', p.source_ids)));+ if (querySourceScope.sourceIds?.length === 0) return [];// #4352 — same enforcement for the full-control query op (both the image// searchVector branch and the text hybrid path below).const excludePrivate = await setup(() => resolveExcludePrivatePages(ctx.engine, ctx.remote));diff --git a/test/e2e/search-source-ids-postgres.test.ts b/test/e2e/search-source-ids-postgres.test.tsnew file mode 100644index 0000000000..637373d8f9--- /dev/null+++ b/test/e2e/search-source-ids-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../search/search-source-ids.test.ts'));diff --git a/test/e2e/serve-http-member-tokens.test.ts b/test/e2e/serve-http-member-tokens.test.tsnew file mode 100644index 0000000000..79d0528cf0--- /dev/null+++ b/test/e2e/serve-http-member-tokens.test.ts@@ -0,0 +1,134 @@+/**+ * Per-member tokens on one shared brain: two bearer tokens, one granted+ * source-a and one granted source-b, call `search` and `query` concurrently+ * from one process against one real `gbrain serve --http` on Postgres. Each+ * token's results stay inside its own grant on every call, and `source_ids`+ * cannot carry either token into the other member's source.+ *+ * 1. Protects: the multi-member bot pattern (one token per member, each+ * narrowed to that member's sources) over the real HTTP transport.+ * 2. Fails when: the server resolves a call's scope from anything but that+ * call's own token, or `source_ids` widens a token past its grant.+ * 3. Existing coverage (serve-http-source-grant) pins one token at a time.+ * 4. No production seam.+ *+ * Run: DATABASE_URL=... GBRAIN_TEST_ALLOW_DATABASE_URL=1 \+ * bun test test/e2e/serve-http-member-tokens.test.ts+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { setupDB, teardownDB, getConn, hasDatabase } from './helpers.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { hashToken, generateToken } from '../../src/core/utils.ts';+import { importFromContent } from '../../src/core/import-file.ts';++const skip = !hasDatabase();+const describeE2E = skip ? describe.skip : describe;+if (skip) console.log('Skipping E2E serve-http-member-tokens tests (DATABASE_URL not set)');++const PORT = 19158;+const BASE = `http://localhost:${PORT}`;+const MEMBERS = { a: 'mt-source-a', b: 'mt-source-b' } as const;+const CANARY = { a: 'canaryalpha', b: 'canarybravo' } as const;++describeE2E('/mcp per-member tokens on one shared brain', () => {+ let serverProcess: ReturnType<typeof import('child_process').spawn> | null = null;+ let engine: PostgresEngine;+ const tokens = { a: '', b: '' };++ async function insertToken(name: string, sourceId: string): Promise<string> {+ const token = generateToken('gbrain_');+ await getConn().unsafe(+ `INSERT INTO access_tokens (id, name, token_hash, permissions) VALUES (gen_random_uuid(), $1, $2, $3::text::jsonb)`,+ [name, hashToken(token), JSON.stringify({ takes_holders: ['world'], source_id: sourceId })],+ );+ return token;+ }++ beforeAll(async () => {+ engine = await setupDB();+ const conn = getConn();+ await conn.unsafe(`DELETE FROM access_tokens WHERE name LIKE 'mt-e2e-%'`);+ for (const member of ['a', 'b'] as const) {+ await conn.unsafe(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{}'::jsonb)`, [MEMBERS[member]]);+ const imported = await importFromContent(engine, `notes/ledger-${member}`,+ `# Quarry ledger\nQuarry ledger notes for member ${member}, ${CANARY[member]}.`, { sourceId: MEMBERS[member], noEmbed: true });+ expect(imported.status).toBe('imported');+ tokens[member] = await insertToken(`mt-e2e-${member}`, MEMBERS[member]);+ }+ const { spawn } = await import('child_process');+ serverProcess = spawn('bun', ['run', 'src/cli.ts', 'serve', '--http', '--port', String(PORT), '--public-url', BASE], {+ cwd: process.cwd(), env: { ...process.env }, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stderr = '';+ serverProcess.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });+ for (let i = 0; i < 30; i++) {+ try { if ((await fetch(`${BASE}/health`)).ok) return; } catch { /* not up yet */ }+ await new Promise(r => setTimeout(r, 500));+ }+ throw new Error('Server failed to start within 15s.\nstderr: ' + stderr.slice(-500));+ }, 60_000);++ afterAll(async () => {+ if (serverProcess) {+ serverProcess.kill('SIGTERM');+ await new Promise(r => setTimeout(r, 1000));+ if (!serverProcess.killed) serverProcess.kill('SIGKILL');+ }+ try {+ const conn = getConn();+ await conn.unsafe(`DELETE FROM access_tokens WHERE name LIKE 'mt-e2e-%'`);+ await conn.unsafe(`DELETE FROM pages WHERE source_id IN ($1, $2)`, [MEMBERS.a, MEMBERS.b]);+ await conn.unsafe(`DELETE FROM sources WHERE id IN ($1, $2)`, [MEMBERS.a, MEMBERS.b]);+ } catch (e: any) {+ console.error(`[afterAll] fixture cleanup failed: ${e.message}`);+ }+ await teardownDB();+ }, 30_000);++ async function call(token: string, tool: 'search' | 'query', args: Record<string, unknown>): Promise<{ isError?: boolean; text: string }> {+ const res = await fetch(`${BASE}/mcp`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }),+ });+ expect(res.status).toBe(200);+ const body = (await res.text()).trim();+ const rpc = JSON.parse(body.startsWith('{') ? body : body.split('\n').filter(l => l.startsWith('data:')).pop()!.slice(5).trim());+ expect(rpc.error).toBeUndefined();+ return { isError: rpc.result.isError, text: rpc.result.content.map((c: { text: string }) => c.text).join('\n') };+ }++ function expectOwnOnly(member: 'a' | 'b', out: { isError?: boolean; text: string }): void {+ const other = member === 'a' ? 'b' : 'a';+ expect(out.isError).not.toBe(true);+ expect(out.text).toContain(CANARY[member]);+ expect(out.text).not.toContain(CANARY[other]);+ expect(out.text).not.toContain(MEMBERS[other]);+ }++ test('interleaved concurrent search and query calls never cross between the two tokens', async () => {+ const calls: Array<Promise<void>> = [];+ for (let round = 0; round < 8; round++) {+ for (const member of ['a', 'b'] as const) {+ for (const tool of ['search', 'query'] as const) {+ const args = { query: 'quarry ledger notes', fields: 'full', ...(tool === 'query' ? { expand: false } : {}), ...(round % 2 ? { source_ids: [MEMBERS[member]] } : {}) };+ calls.push(call(tokens[member], tool, args).then(out => expectOwnOnly(member, out)));+ }+ }+ }+ await Promise.all(calls);+ }, 60_000);++ test("source_ids naming the other member's source is refused for both tokens", async () => {+ for (const [member, other] of [['a', 'b'], ['b', 'a']] as const) {+ for (const tool of ['search', 'query'] as const) {+ for (const sourceIds of [[MEMBERS[other]], [MEMBERS[member], MEMBERS[other]]]) {+ const out = await call(tokens[member], tool, { query: 'quarry ledger notes', source_ids: sourceIds });+ expect(out.isError).toBe(true);+ expect(out.text).toContain('permission_denied');+ expect(out.text).not.toContain(CANARY[other]);+ }+ }+ }+ }, 60_000);+});diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 3fc491bd6d..105aee779d 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -745,6 +745,7 @@" --since On/after: YYYY-MM-DD or 7d/2w/1y."," --until On/before."," --source-id One source, or '__all__'.",+ " --source-ids Narrow to these sources ([] = none)."," --cross-modal Default auto."," --embedding-column Registered embedding column."," --adaptive-return true for one answer (fewer rows, never empty); omit for breadth.",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 7400005fa8..afc2031295 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 262702,- "stdoutSha256": "bfd962a82f16847c7969963ab23410170196491231dcdef214ab3863873b495e",+ "stdoutBytes": 263140,+ "stdoutSha256": "1c472b785ce9480da19240c8b8fd36d52593149294542069d6ba20813ef4c192","toolNames": ["remember","entity",@@ -1625,6 +1625,7 @@"salience": "string?","snippet_chars": "number?","source_id": "string?",+ "source_ids": "array?","token_budget": "number?","types": "array?","where": "object?"@@ -1721,6 +1722,13 @@"description": "One source, or '__all__'.","type": "string"},+ "source_ids": {+ "description": "Narrow to these sources ([] = none).",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"token_budget": {"description": "Default 6000.","type": "number"@@ -1777,6 +1785,7 @@"since": "string?","snippet_chars": "number?","source_id": "string?",+ "source_ids": "array?","symbol_kind": "string?","token_budget": "number?","types": "array?",@@ -1926,6 +1935,13 @@"description": "One source, or '__all__'.","type": "string"},+ "source_ids": {+ "description": "Narrow to these sources ([] = none).",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"symbol_kind": {"description": "Code symbol type.","type": "string"diff --git a/test/search/search-source-ids.test.ts b/test/search/search-source-ids.test.tsnew file mode 100644index 0000000000..01adc76248--- /dev/null+++ b/test/search/search-source-ids.test.ts@@ -0,0 +1,352 @@+/**+ * GBRA-156 item 3: per-request `source_ids` on the `search` and `query` ops.+ *+ * 1. Protects: a shared brain (one brain, several sources) lets an agent+ * acting for one member narrow a single search/query to the sources that+ * member may see. The request reads the intersection of `source_ids` and+ * the caller's readable sources; each id is authorized exactly as an+ * explicit `source_id` is (out-of-grant ids refuse with permission_denied+ * for remote callers, non-live ids refuse with unknown_source), and an+ * empty narrowed scope searches nothing.+ * 2. Fails when: the param is dropped or unknown (local callers read every+ * source), any arm (keyword, vector, title, alias fan-out, entity+ * anchoring, facts arm, saved facts, CRAG re-run, think escalation,+ * evidence delivery, keyword paging) reads past the narrowed scope, or an+ * empty narrowed scope falls back to the ambient or full scope.+ * 3. Existing coverage pins only the scalar `source_id` (search-op-source-id).+ * 4. No production seam: the gateway embed transport stub and an engine proxy+ * that records each search call's scope.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';+import { parseOpArgs } from '../../src/cli/main.ts';+import * as think from '../../src/core/think/index.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const DIMS = 1536;+const CANARY = 'canarybravo';++function vectorFor(text: string): number[] {+ const v = new Array<number>(DIMS).fill(0);+ for (const w of text.toLowerCase().match(/[a-z]+/g) ?? []) {+ let h = 0;+ for (const ch of w) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ v[h % DIMS] += 1;+ }+ const n = Math.hypot(...v) || 1;+ return v.map(x => x / n);+}++type Call = { method: string; opts: Record<string, unknown> | undefined };+type Outcome = { rows: Array<Record<string, unknown>>; meta: Record<string, unknown>; notices: Array<{ code: string; why: string }>; calls: Call[] };++const GRANTED_A = { token: 'gbrain_at_test', clientId: 'gbrain_cl_test', scopes: ['read'], allowedSources: ['source-a'] };+const GRANTED_AB = { ...GRANTED_A, allowedSources: ['source-a', 'source-b'] };++for (const kind of testBackends()) {+ describe(`search/query source_ids (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ /** Every engine search call the op makes, with the scope it passed. */+ function recording(calls: Call[]): BrainEngine {+ return new Proxy(engine, {+ get(target, key) {+ const value = Reflect.get(target, key, target);+ if (typeof value !== 'function') return value;+ if (typeof key === 'string' && /^search/.test(key)) {+ return (...args: unknown[]) => {+ calls.push({ method: key, opts: args.find(a => a !== null && typeof a === 'object' && !(a instanceof Float32Array) && !Array.isArray(a)) as Record<string, unknown> | undefined });+ return (value as (...a: unknown[]) => unknown).apply(target, args);+ };+ }+ return value.bind(target);+ },+ });+ }++ async function run(op: 'search' | 'query', params: Record<string, unknown>, ctxOver: Partial<OperationContext> = {}): Promise<Outcome> {+ const calls: Call[] = [];+ const meta: Record<string, unknown> = {};+ const notices: Array<{ code: string; why: string }> = [];+ const ctx = {+ engine: recording(calls), config: { engine: kind }, dryRun: false, remote: false, sourceId: 'source-a',+ localFederatedSourceIds: ['source-a', 'source-b', 'source-c'],+ logger: { info() {}, warn() {}, error() {} },+ emitResponseMeta: (k: string, v: unknown) => { meta[k] = v; },+ emitNotice: (n: { code: string; why: string }) => { notices.push(n); },+ ...ctxOver,+ } as unknown as OperationContext;+ const rows = await operationsByName[op].handler(ctx, op === 'query' ? { expand: false, ...params } : params) as Array<Record<string, unknown>>;+ return { rows, meta, notices, calls };+ }++ /** No source-b page, fact or text anywhere in the rows or the response meta, and every engine search call scoped inside `allowed`. */+ function expectNoSourceB(out: Outcome, allowed: string[] = ['source-a']): void {+ const wire = JSON.stringify({ rows: out.rows, meta: out.meta, notices: out.notices });+ expect(wire).not.toContain(CANARY);+ expect(wire).not.toContain('"source_id":"source-b"');+ for (const r of out.rows) expect(String(r.slug ?? r.page_slug ?? '')).not.toContain('bravo');+ for (const c of out.calls) {+ const ids = c.opts?.sourceIds as string[] | undefined;+ const id = c.opts?.sourceId as string | undefined;+ expect({ method: c.method, scoped: ids !== undefined || id !== undefined }).toEqual({ method: c.method, scoped: true });+ for (const s of ids ?? [id!]) expect(allowed).toContain(s);+ }+ }++ function slugs(out: Outcome): string[] {+ return out.rows.map(r => String(r.slug ?? r.page_slug ?? ''));+ }++ async function refusal(promise: Promise<unknown>): Promise<string> {+ try {+ await promise;+ } catch (e) {+ return (e as { code?: string }).code ?? String(e);+ }+ return 'no_error';+ }++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);+ 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 ['source-a', 'source-b', 'source-c']) {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [id]);+ }+ await engine.executeRaw(`INSERT INTO sources (id, name, archived) VALUES ('source-gone', 'source-gone', true) ON CONFLICT (id) DO NOTHING`);+ const pages: Array<[string, string, string]> = [+ ['source-a', 'notes/orchard-alpha', '# Zephyrblatt orchard\nZephyrblatt orchard harvest notes for the alpha team.'],+ ['source-b', 'notes/orchard-bravo', `# Zephyrblatt orchard\nZephyrblatt orchard harvest notes ${CANARY}.`],+ ['source-b', 'notes/zephyrblatt-orchard-harvest-bravo', `# Zephyrblatt Orchard Harvest\nThe ${CANARY} harvest ledger.`],+ ['source-c', 'notes/orchard-charlie', '# Zephyrblatt orchard\nZephyrblatt orchard harvest notes for the charlie team.'],+ ['source-a', 'companies/acme-example', '# Customer: Acme Example\nAcme Example renewal terms. Account code: ZORBIX.'],+ ['source-a', 'notes/zorbix-alpha', '# Amendment alpha\nZORBIX renewal amendment for the alpha team.'],+ ['source-b', 'notes/zorbix-bravo', `# Amendment\nZORBIX renewal amendment ${CANARY}.`],+ ];+ for (const [sourceId, slug, body] of pages) await importFromContent(engine, slug, body, { sourceId });+ const fact = (text: string, sourceId: string) => engine.insertFact({ fact: text, kind: 'fact', entity_slug: 'zephyrblatt-orchard', source: 'notes', visibility: 'world', valid_from: new Date('2026-07-01T00:00:00Z') }, { source_id: sourceId });+ await fact('Zephyrblatt orchard harvest moved to May for the alpha team.', 'source-a');+ await fact(`Zephyrblatt orchard harvest moved to June ${CANARY}.`, 'source-b');+ }, 180_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('the op contracts carry source_ids', () => {+ for (const op of ['search', 'query'] as const) {+ expect(operationsByName[op].params.source_ids).toMatchObject({ type: 'array', items: { type: 'string' } });+ }+ });++ test('the CLI maps --source-ids to the array on both commands', () => {+ for (const op of ['search', 'query'] as const) {+ expect(parseOpArgs(operationsByName[op], ['zephyrblatt orchard', '--source-ids', 'source-a, source-b']).source_ids).toEqual(['source-a', 'source-b']);+ }+ });++ test('fixture control: an unnarrowed local read reaches source-b in every arm under test', async () => {+ const search = await run('search', { query: 'zephyrblatt orchard harvest', source_id: '__all__' });+ expect(slugs(search)).toContain('notes/orchard-bravo');+ const query = await run('query', { query: 'zephyrblatt orchard harvest', source_id: '__all__' });+ expect(JSON.stringify(query.rows)).toContain(CANARY);+ const fanout = await run('query', { query: 'Acme Example renewal', source_id: '__all__' });+ expect(slugs(fanout)).toContain('notes/zorbix-bravo');+ expect((fanout.meta.retrieval as { fanout?: { aliases_searched: Array<{ alias: string }> } }).fanout?.aliases_searched.map(a => a.alias)).toEqual(['ZORBIX']);+ });++ describe('local trusted caller', () => {+ for (const op of ['search', 'query'] as const) {+ test(`${op}: narrowing to one source returns zero cross-source pages`, async () => {+ const out = await run(op, { query: 'zephyrblatt orchard harvest', source_ids: ['source-a'] });+ expect(slugs(out)).toContain('notes/orchard-alpha');+ expectNoSourceB(out);+ expect(JSON.stringify(out.rows)).not.toContain('charlie');+ });++ test(`${op}: narrowing to two sources reads both and nothing else`, async () => {+ const out = await run(op, { query: 'zephyrblatt orchard harvest', source_ids: ['source-a', 'source-c'] });+ expect(slugs(out)).toEqual(expect.arrayContaining(['notes/orchard-alpha', 'notes/orchard-charlie']));+ expectNoSourceB(out, ['source-a', 'source-c']);+ });++ test(`${op}: the alias fan-out stays inside the narrowed scope`, async () => {+ const out = await run(op, { query: 'Acme Example renewal', source_ids: ['source-a'] });+ expect(slugs(out)).toContain('notes/zorbix-alpha');+ expect((out.meta.retrieval as { fanout?: { aliases_searched: Array<{ alias: string }> } }).fanout?.aliases_searched.map(a => a.alias)).toEqual(['ZORBIX']);+ expectNoSourceB(out);+ });++ test(`${op}: an empty array searches nothing and says so`, async () => {+ const out = await run(op, { query: 'zephyrblatt orchard harvest', source_ids: [] });+ expect(out.rows).toEqual([]);+ expect(out.calls).toEqual([]);+ expect(out.notices.map(n => n.code)).toContain('empty_retrieval');+ });++ test(`${op}: source_id intersects source_ids (disjoint pair searches nothing)`, async () => {+ const both = await run(op, { query: 'zephyrblatt orchard harvest', source_id: 'source-c', source_ids: ['source-a', 'source-c'] });+ expect(slugs(both)).toContain('notes/orchard-charlie');+ expect(slugs(both)).not.toContain('notes/orchard-alpha');+ expectNoSourceB(both, ['source-c']);+ const disjoint = await run(op, { query: 'zephyrblatt orchard harvest', source_id: 'source-b', source_ids: ['source-a'] });+ expect(disjoint.rows).toEqual([]);+ expect(disjoint.calls).toEqual([]);+ const all = await run(op, { query: 'zephyrblatt orchard harvest', source_id: '__all__', source_ids: ['source-a'] });+ expectNoSourceB(all);+ });++ test(`${op}: unknown, archived and malformed ids refuse`, async () => {+ expect(await refusal(run(op, { query: 'zephyrblatt', source_ids: ['source-a', 'source-missing'] }))).toBe('unknown_source');+ expect(await refusal(run(op, { query: 'zephyrblatt', source_ids: ['source-gone'] }))).toBe('unknown_source');+ expect(await refusal(run(op, { query: 'zephyrblatt', source_ids: ['Source-A'] }))).toBe('invalid_params');+ expect(await refusal(run(op, { query: 'zephyrblatt', source_ids: ['__all__'] }))).toBe('invalid_params');+ expect(await refusal(run(op, { query: 'zephyrblatt', source_ids: 'source-a' }))).toBe('invalid_params');+ expect(await refusal(run(op, { query: 'zephyrblatt', source_ids: [7] }))).toBe('invalid_params');+ });+ }++ test('search: keyword paging and the keyword-only opt-out honor the narrowed scope', async () => {+ expectNoSourceB(await run('search', { query: 'zephyrblatt orchard', match: 'keyword', source_ids: ['source-a'] }));+ await engine.setConfig('search.mcp_keyword_only', 'true');+ try {+ const out = await run('search', { query: 'zephyrblatt orchard', source_ids: ['source-a'] });+ expect(slugs(out)).toContain('notes/orchard-alpha');+ expectNoSourceB(out);+ } finally {+ await engine.setConfig('search.mcp_keyword_only', 'false');+ }+ });++ test('query: entity anchoring, evidence delivery and the facts arm honor the narrowed scope', async () => {+ await engine.setConfig('search.entity_anchoring', 'true');+ try {+ for (const params of [{}, { return_unit: 'page' }, { return_unit: 'window' }, { detail: 'high' }]) {+ const out = await run('query', { query: 'zephyrblatt orchard harvest', source_ids: ['source-a'], ...params });+ expect(slugs(out)).toContain('notes/orchard-alpha');+ expectNoSourceB(out);+ }+ } finally {+ await engine.setConfig('search.entity_anchoring', 'false');+ }+ });++ test('query: the CRAG re-run and think escalation read the narrowed scope', async () => {+ await engine.setConfig('search.crag_escalation', 'true');+ await engine.setConfig('search.crag_think', 'true');+ const thinkCalls: Array<Record<string, unknown>> = [];+ const spy = spyOn(think, 'runThink').mockImplementation((async (_engine: unknown, opts: Record<string, unknown>) => {+ thinkCalls.push(opts);+ return { answer: 'stub', citations: [], modelUsed: 'stub' };+ }) as never);+ try {+ const out = await run('query', { query: 'zxqv nonexistent quux', source_ids: ['source-a'] });+ const crag = (out.meta.retrieval as { crag?: { escalated?: boolean } }).crag;+ expect(crag?.escalated).toBe(true);+ expect(out.calls.filter(c => c.method === 'searchKeyword').length).toBeGreaterThan(1);+ expectNoSourceB(out);+ expect(thinkCalls).toHaveLength(1);+ expect(thinkCalls[0]!.allowedSources).toEqual(['source-a']);+ expect(thinkCalls[0]!.sourceId).toBeUndefined();+ } finally {+ spy.mockRestore();+ await engine.setConfig('search.crag_escalation', 'false');+ await engine.setConfig('search.crag_think', 'false');+ }+ }, 60_000);+ });++ describe('remote token narrowing inside its grant', () => {+ for (const op of ['search', 'query'] as const) {+ test(`${op}: a token granted source-a and source-b narrows to source-a`, async () => {+ const out = await run(op, { query: 'zephyrblatt orchard harvest', source_ids: ['source-a'], fields: 'full' }, { remote: true, auth: GRANTED_AB as never });+ expect(slugs(out)).toContain('notes/orchard-alpha');+ expectNoSourceB(out);+ });+ }+ });++ describe('adversarial widening: a token granted source-a only', () => {+ const remote = { remote: true, auth: GRANTED_A as never };+ const refused: Array<[string, Record<string, unknown>, string]> = [+ ['source-a plus source-b', { source_ids: ['source-a', 'source-b'] }, 'permission_denied'],+ ['source-b alone', { source_ids: ['source-b'] }, 'permission_denied'],+ ['the __all__ sentinel', { source_ids: ['__all__'] }, 'invalid_params'],+ ['source-b with a duplicate source-a', { source_ids: ['source-a', 'source-b', 'source-a'] }, 'permission_denied'],+ ['an upper-case variant', { source_ids: ['SOURCE-B'] }, 'invalid_params'],+ ['a whitespace variant', { source_ids: [' source-b '] }, 'permission_denied'],+ ['an embedded-space variant', { source_ids: ['source -b'] }, 'invalid_params'],+ ['source_id source-b with source_ids source-a', { source_id: 'source-b', source_ids: ['source-a'] }, 'permission_denied'],+ ['source_id source-a with source_ids source-b', { source_id: 'source-a', source_ids: ['source-b'] }, 'permission_denied'],+ ['source_id __all__ with source_ids source-b', { source_id: '__all__', source_ids: ['source-b'] }, 'permission_denied'],+ ];+ for (const op of ['search', 'query'] as const) {+ for (const [label, params, code] of refused) {+ test(`${op}: ${label} is refused (${code})`, async () => {+ expect(await refusal(run(op, { query: 'zephyrblatt orchard harvest', ...params }, remote))).toBe(code);+ });+ }++ const allowed: Array<[string, Record<string, unknown>]> = [+ ['duplicates of source-a', { source_ids: ['source-a', 'source-a'] }],+ ['a whitespace variant of source-a', { source_ids: [' source-a '] }],+ ['source_id __all__ with source_ids source-a', { source_id: '__all__', source_ids: ['source-a'] }],+ ['source_id source-a with source_ids source-a', { source_id: 'source-a', source_ids: ['source-a'] }],+ ];+ for (const [label, params] of allowed) {+ test(`${op}: ${label} reads source-a only`, async () => {+ const out = await run(op, { query: 'zephyrblatt orchard harvest', fields: 'full', ...params }, remote);+ expect(slugs(out)).toContain('notes/orchard-alpha');+ expectNoSourceB(out);+ });+ }++ test(`${op}: an empty array searches nothing`, async () => {+ const out = await run(op, { query: 'zephyrblatt orchard harvest', source_ids: [] }, remote);+ expect(out.rows).toEqual([]);+ expect(out.calls).toEqual([]);+ });++ test(`${op}: the alias fan-out cannot reach source-b`, async () => {+ expectNoSourceB(await run(op, { query: 'Acme Example renewal', source_ids: ['source-a'], fields: 'full' }, remote));+ });+ }++ test('query: the CRAG re-run cannot reach source-b', async () => {+ await engine.setConfig('search.crag_escalation', 'true');+ try {+ const out = await run('query', { query: 'zxqv nonexistent quux', source_ids: ['source-a'] }, remote);+ expect((out.meta.retrieval as { crag?: { escalated?: boolean } }).crag?.escalated).toBe(true);+ expectNoSourceB(out);+ } finally {+ await engine.setConfig('search.crag_escalation', 'false');+ }+ }, 60_000);++ test('query: anchoring, evidence delivery and the facts arm cannot reach source-b', async () => {+ await engine.setConfig('search.entity_anchoring', 'true');+ try {+ for (const params of [{}, { return_unit: 'page' }, { return_unit: 'window' }]) {+ expectNoSourceB(await run('query', { query: 'zephyrblatt orchard harvest', source_ids: ['source-a'], fields: 'full', ...params }, remote));+ }+ } finally {+ await engine.setConfig('search.entity_anchoring', 'false');+ }+ });++ test('search: keyword paging cannot reach source-b', async () => {+ expectNoSourceB(await run('search', { query: 'zephyrblatt orchard', match: 'keyword', source_ids: ['source-a'], fields: 'full' }, remote));+ });+ });+ });+}