Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(mcp): allow explicit federated reads from a GBRAIN_SOURCE-bound stdio connection (#5081)

garrytaneab8661f158c
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 6e91b02c4c..9504a982e6 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_versions` filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, partial, wedged, skipped_future}` block stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read).
-- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`.
+- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`).
- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 22cf7ca243..e700abd45c 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed). `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.
-- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.
+- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.
- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`, `sources purge`, the `sources_remove` op, expired-archive purge) deletes the `sources` row and that incarnation's `persistence_source_bindings` row in one statement; bindings have no FK to `sources`. Bindings of other incarnations are left to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only a binding of the source's current incarnation.
- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling.
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 52538b6401..148a1e1320 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -115,6 +115,27 @@ behave as you'd expect — every page appears in search.
Flip later with `gbrain sources federate <id>` / `unfederate <id>`.
+### Explicit reads from a bound agent connection
+
+An agent connection started with `GBRAIN_SOURCE=<id>` (or inside a
+directory pinned by `.gbrain-source`) is bound to that source. Its
+unqualified reads stay on the bound source. It may still name another
+source in an explicit `source_id` read (`search`, `query`, `get_page`,
+`list_pages`, `resolve_slugs`, `recall`) when that source is
+`federated=true`; the result holds only the named source's rows. Writes
+still go to the bound source only.
+
+| Refusal hint | Why | Fix (on the brain host) |
+|--------------|-----|-------------------------|
+| `<id> is not federated` | The named source is not federated. | `gbrain sources federate <id>`, or start the connection without the binding. |
+| `<id> opted out of federation` | The named source was unfederated. | `gbrain sources federate <id>` if it should be readable from other sources. |
+| `<bound> opted out of federation …, so it reads no other source` | The bound source itself is isolated (`federated=false`), so it never reads another source. | `gbrain sources federate <bound>`, or start the connection without the binding. |
+| `Your token is not granted <id>` | An HTTP token or OAuth client whose grant does not include the source. | `gbrain auth rescope-client <client_id> --federated-read <ids>` for an OAuth client. |
+
+`search_by_image`, `open_loops` and the code-intel tools keep their stricter
+rule: an explicit `source_id` must be inside the connection's own source or
+grant.
+
## Commands
The most-used subcommands (run `gbrain sources --help` for the full,
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index 1c94d5356d..0bb8d9eba4 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -597,10 +597,16 @@ export function linkReadScopeOpts(ctx: OperationContext): { sourceId?: string; s
* trusted local (remote === false) → `{}` (spans the whole brain)
* remote → the caller's grant (sourceScopeOpts)
* - explicit `source_id`:
- * remote + federated grant that doesn't include it → permission_denied
+ * remote, outside the caller's grant or scalar scope, and outside
+ * `explicitReads` (when passed) → permission_denied
* otherwise → `{ sourceId }`
* - neither → the caller's grant (sourceScopeOpts).
*
+ * `explicitReads` (#5081) is the explicit-read admission set; only
+ * `federatedSearchScope` passes it. The other callers (image, loops,
+ * code-intel) pass nothing and keep denying every id outside the scope, with
+ * the original hint.
+ *
* `code_traversal_cache_clear` is intentionally NOT a caller — it is localOnly
* and carries its own destructive D8 all_sources guard.
*/
@@ -608,6 +614,7 @@ export function resolveRequestedScope(
ctx: OperationContext,
sourceIdParam: string | undefined,
allSourcesParam = false,
+ explicitReads?: readonly string[],
): { sourceId?: string; sourceIds?: string[] } {
const wantsAll = allSourcesParam || sourceIdParam === ALL_SOURCES;
if (wantsAll) {
@@ -618,11 +625,14 @@ export function resolveRequestedScope(
const granted = scope.sourceIds !== undefined
? scope.sourceIds.includes(sourceIdParam)
: scope.sourceId === sourceIdParam;
- if (ctx.remote !== false && !granted) {
+ if (ctx.remote !== false && !granted && !explicitReads?.includes(sourceIdParam)) {
throw new OperationError(
'permission_denied',
'Requested source is outside your granted sources',
- 'Request access to this source, or omit source_id to search within your grant.',
+ explicitReads === undefined
+ ? 'Request access to this source, or omit source_id to search within your grant.'
+ : explicitReadDeniedHint(ctx, sourceIdParam),
+ explicitReads === undefined ? undefined : EXPLICIT_READ_DOCS,
);
}
return { sourceId: sourceIdParam };
@@ -630,6 +640,53 @@ export function resolveRequestedScope(
return sourceScopeOpts(ctx);
}
+const EXPLICIT_READ_DOCS = 'docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection';
+
+/**
+ * #5081 / DX-O6(c): why an explicit read was refused, with the exact command
+ * that would admit it. A granted token is told about its grant; a connection
+ * bound by GBRAIN_SOURCE or a .gbrain-source pin is told about the binding
+ * (its own opt-out, the target's opt-out, or a target that was never
+ * federated); an unbound connection is told the target is not federated.
+ */
+function explicitReadDeniedHint(ctx: OperationContext, id: string): string {
+ const auth = ctx.auth;
+ if (auth !== undefined && (auth.allowedSources !== undefined || auth.hasSourceGrant !== false)) {
+ const granted = auth.allowedSources ?? (auth.sourceId !== undefined ? [auth.sourceId] : []);
+ return auth.principal?.kind === 'oauth_client'
+ ? `Your token is not granted ${id}; ask the brain owner to grant it ` +
+ `(gbrain auth rescope-client ${auth.principal.id} --federated-read ${[...granted, id].join(',')}).`
+ : `Your token is not granted ${id}; ask the brain owner to grant it.`;
+ }
+ const binding = ctx.explicitReadBinding;
+ if (binding === undefined) {
+ return `${id} is not federated; the brain owner can run \`gbrain sources federate ${id}\` on the brain host, ` +
+ 'or omit source_id to read within this connection\'s sources.';
+ }
+ const bound = `This connection is bound to source ${binding.sourceId} (${binding.via}).`;
+ const unbind = binding.via === 'GBRAIN_SOURCE'
+ ? 'start this connection without GBRAIN_SOURCE'
+ : 'start this connection outside the directory pinned by .gbrain-source';
+ if (binding.optedOut.includes(binding.sourceId)) {
+ return `${bound} ${binding.sourceId} opted out of federation (federated: false), so it reads no other source; ` +
+ `the brain owner can run \`gbrain sources federate ${binding.sourceId}\` on the brain host, or ${unbind}.`;
+ }
+ const reason = binding.optedOut.includes(id) ? 'opted out of federation (federated: false)' : 'is not federated';
+ return `${bound} ${id} ${reason}; the brain owner can run \`gbrain sources federate ${id}\` on the brain host, or ${unbind}.`;
+}
+
+/**
+ * #5081: the sources an explicit `source_id` read may name beyond the scope.
+ * A grant (`ctx.auth.allowedSources`) governs alone. Otherwise a bound stdio
+ * connection uses its binding's set, and an unbound connection uses the set
+ * its unqualified reads already span (`localFederatedSourceIds`), so an
+ * explicit read there is never wider than an unqualified one.
+ */
+function explicitReadAdmission(ctx: OperationContext): readonly string[] {
+ if (ctx.auth?.allowedSources !== undefined) return [];
+ return ctx.explicitReadBinding?.sourceIds ?? ctx.localFederatedSourceIds ?? [];
+}
+
/**
* #4329: parse a per-call `source_id` param. Pre-fix, get_page / delete_page /
* restore_page had NO source_id in their contracts, so an agent-passed
@@ -675,6 +732,10 @@ export function parseSourceIdParam(
* unqualified reads (#3242 — pages ingested into a `federated: true` source
* were invisible to get_page/search/list_pages while resolve_slugs leaked them).
*
+ * An explicit per-call `source_id` is admitted inside the explicit-read set
+ * (#5081, `explicitReadAdmission`): the binding's set for a connection bound
+ * by GBRAIN_SOURCE or a .gbrain-source pin, otherwise the federated set.
+ *
* The expansion NEVER applies when:
* - a concrete per-call `source_id` was passed (explicit wins);
* - the resolver already produced a federated array (OAuth grant governs);
@@ -694,7 +755,7 @@ export function federatedSearchScope(
ctx: OperationContext,
sourceIdParam?: string,
): { sourceId?: string; sourceIds?: string[] } {
- const scope = resolveRequestedScope(ctx, sourceIdParam);
+ const scope = resolveRequestedScope(ctx, sourceIdParam, false, explicitReadAdmission(ctx));
if (
(sourceIdParam === undefined || sourceIdParam === ALL_SOURCES) &&
ctx.auth?.allowedSources === undefined &&
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index c543b341b4..791729e2e2 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -465,6 +465,29 @@ export interface OperationContext {
* wins, and a context without this field never widens.
*/
localFederatedSourceIds?: string[];
+ /**
+ * #5081 — explicit-read admission for a stdio connection bound by an
+ * explicit tier (`GBRAIN_SOURCE` or a `.gbrain-source` pin). Set ONLY by
+ * the stdio transport (src/mcp/server.ts), never from caller params and
+ * never for an HTTP token. Unlike `localFederatedSourceIds` it never widens
+ * an unqualified read; `federatedSearchScope` only uses it to admit an
+ * explicit per-call `source_id` inside `sourceIds`.
+ */
+ explicitReadBinding?: ExplicitReadBinding;
+}
+
+/**
+ * #5081 — the bound source, how it was bound, the sources an explicit
+ * `source_id` read may name (the bound source first, then every non-archived
+ * `config.federated === true` source; just the bound source when it opted out
+ * with `config.federated === false`), and the sources that opted out, which
+ * only shape the denial hint.
+ */
+export interface ExplicitReadBinding {
+ sourceId: string;
+ via: 'GBRAIN_SOURCE' | '.gbrain-source';
+ sourceIds: string[];
+ optedOut: string[];
}
export interface Operation {
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index 0eb01df9b9..8a1fe3cb6f 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -16,6 +16,7 @@
import { readFileSync, lstatSync, type Stats } from 'fs';
import { join, dirname, resolve } from 'path';
import type { BrainEngine } from './engine.ts';
+import type { ExplicitReadBinding } from './ops/contract.ts';
import { isSourceFederated, parseSourceConfig } from './sources-load.ts';
import { SOURCE_ID_RE, isValidSourceId, ALL_SOURCES } from './source-id.ts';
import { isTrustedDotfile, realpathOrResolve, realpathOrResolveAsync } from './path-confine.ts';
@@ -882,16 +883,51 @@ export async function localFederatedSourceIds(
tier: SourceTier,
): Promise<string[] | undefined> {
if (tier === 'flag' || tier === 'env' || tier === 'dotfile') return undefined;
- let rows: Array<{ id: string; config: unknown; archived?: boolean }>;
+ return federatedSetFor(await liveSourceRows(engine), sourceId);
+}
+
+/**
+ * #5081 — explicit-read admission for a stdio connection bound by
+ * `GBRAIN_SOURCE` (tier `env`) or a `.gbrain-source` pin (tier `dotfile`).
+ * The admitted set is exactly what `localFederatedSourceIds` would compute for
+ * the same source on a non-explicit tier (one shared `federatedSetFor`), so a
+ * bound connection may NAME the sources an unbound one reads unqualified. The
+ * #2928 isolated anchor (`config.federated === false`) admits only itself.
+ * Unqualified reads of a bound connection stay scalar: the result goes on
+ * `OperationContext.explicitReadBinding`, never `localFederatedSourceIds`.
+ * Returns undefined for every other tier (no extra query).
+ */
+export async function explicitReadBinding(
+ engine: BrainEngine,
+ sourceId: string,
+ tier: SourceTier,
+): Promise<ExplicitReadBinding | undefined> {
+ if (tier !== 'env' && tier !== 'dotfile') return undefined;
+ const rows = await liveSourceRows(engine);
+ return {
+ sourceId,
+ via: tier === 'env' ? 'GBRAIN_SOURCE' : '.gbrain-source',
+ sourceIds: federatedSetFor(rows, sourceId) ?? [sourceId],
+ optedOut: rows.filter((row) => parseSourceConfig(row.config).federated === false).map((row) => row.id),
+ };
+}
+
+async function liveSourceRows(engine: BrainEngine): Promise<Array<{ id: string; config: unknown; archived?: boolean }>> {
try {
- rows = await engine.executeRaw<{ id: string; config: unknown; archived?: boolean }>(
+ return await engine.executeRaw<{ id: string; config: unknown; archived?: boolean }>(
`SELECT id, config, archived FROM sources WHERE archived = false ORDER BY id`,
);
} catch {
- rows = await engine.executeRaw<{ id: string; config: unknown }>(
+ return await engine.executeRaw<{ id: string; config: unknown }>(
`SELECT id, config FROM sources ORDER BY id`,
);
}
+}
+
+function federatedSetFor(
+ rows: Array<{ id: string; config: unknown; archived?: boolean }>,
+ sourceId: string,
+): string[] | undefined {
// #2928: an EXPLICITLY isolated anchor (`sources unfederate` /
// `--no-federated` → config.federated = false) opted out of cross-source
// read mixing — never widen it into the federated set (which would drag
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 220881b286..9e413b0d4e 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -165,6 +165,12 @@ export interface DispatchOpts {
* caller params. See OperationContext.localFederatedSourceIds.
*/
localFederatedSourceIds?: string[];
+ /**
+ * #5081: explicit-read admission for a stdio connection bound by
+ * GBRAIN_SOURCE or a .gbrain-source pin. Stdio transport only; see
+ * OperationContext.explicitReadBinding.
+ */
+ explicitReadBinding?: OperationContext['explicitReadBinding'];
/**
* `gbrain serve --source-guard` (plugin lanes): when set, write/admin ops
* are blocked unless the source resolution tier proves the binding is
@@ -485,6 +491,7 @@ export function buildOperationContext(
sourceId: opts.sourceId ?? 'default',
...(sessionId ? { sessionId } : {}),
...(opts.localFederatedSourceIds ? { localFederatedSourceIds: opts.localFederatedSourceIds } : {}),
+ ...(opts.explicitReadBinding ? { explicitReadBinding: opts.explicitReadBinding } : {}),
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
auth: opts.auth,
};
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index f96df71f56..ab410e2e97 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -27,7 +27,12 @@ import { assertStdioSourceBindable } from './source-preflight.ts';
export async function resolveMcpStdioSourceScope(
engine: BrainEngine,
cwd: string = process.cwd(),
-): Promise<{ sourceId: string; localFederatedSourceIds?: string[]; tier: import('../core/source-resolver.ts').SourceTier }> {
+): Promise<{
+ sourceId: string;
+ localFederatedSourceIds?: string[];
+ explicitReadBinding?: import('../core/ops/contract.ts').ExplicitReadBinding;
+ tier: import('../core/source-resolver.ts').SourceTier;
+}> {
// Degraded mode (db-availability 4c): short-circuit WITHOUT touching the
// engine. This site runs before EVERY dispatch and its catch below
// swallows errors into sourceId 'default' — letting it hit a degraded
@@ -47,12 +52,14 @@ export async function resolveMcpStdioSourceScope(
: { sourceId: 'default', tier: 'seed_default' };
}
try {
- const { resolveSourceWithTier, localFederatedSourceIds } = await import('../core/source-resolver.ts');
+ const { resolveSourceWithTier, localFederatedSourceIds, explicitReadBinding } = await import('../core/source-resolver.ts');
const resolved = await resolveSourceWithTier(engine, null, cwd);
const federated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
+ const binding = await explicitReadBinding(engine, resolved.source_id, resolved.tier);
return {
sourceId: resolved.source_id,
...(federated ? { localFederatedSourceIds: federated } : {}),
+ ...(binding ? { explicitReadBinding: binding } : {}),
tier: resolved.tier,
};
} catch {
@@ -327,6 +334,9 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
...(sourceScope.localFederatedSourceIds
? { localFederatedSourceIds: sourceScope.localFederatedSourceIds }
: {}),
+ ...(sourceScope.explicitReadBinding
+ ? { explicitReadBinding: sourceScope.explicitReadBinding }
+ : {}),
// --source-guard (plugin lanes): thread the winning resolution tier so
// dispatch can fail-close ambient-tier writes. Off (undefined) unless
// the serve was started with the flag.
diff --git a/test/all-sources-sentinel.test.ts b/test/all-sources-sentinel.test.ts
index 7284b216da..0e5c707fcc 100644
--- a/test/all-sources-sentinel.test.ts
+++ b/test/all-sources-sentinel.test.ts
@@ -160,9 +160,11 @@ describe('__all__ is never narrower than an unqualified read', () => {
expect(federatedSearchScope(ctx, '__all__')).toEqual({
sourceIds: ['default', 'src-a', 'src-b'],
});
- // Transport federation preserves unqualified reads; it does not grant an
- // arbitrary explicit source to a caller without a durable source grant.
- expect(() => federatedSearchScope(ctx, 'src-a')).toThrow('outside your granted sources');
+ // #5081 (CEO-A12): an explicit source inside the transport's federated
+ // set is admitted (never wider than the unqualified read above); any
+ // other explicit source is still refused.
+ expect(federatedSearchScope(ctx, 'src-a')).toEqual({ sourceId: 'src-a' });
+ expect(() => federatedSearchScope(ctx, 'src-z')).toThrow('outside your granted sources');
});
test('remote scalar scope stays pinned when no transport federation exists', () => {
diff --git a/test/explicit-read-admission-5081.test.ts b/test/explicit-read-admission-5081.test.ts
new file mode 100644
index 0000000000..7108ff97ca
--- /dev/null
+++ b/test/explicit-read-admission-5081.test.ts
@@ -0,0 +1,298 @@
+/**
+ * #5081 — a stdio connection bound by GBRAIN_SOURCE (or a .gbrain-source pin)
+ * may name a federated source in an explicit `source_id` read.
+ *
+ * Pre-fix, `resolveRequestedScope` denied every explicit id outside the
+ * scalar bound source, because `localFederatedSourceIds` returns undefined
+ * for the explicit tiers. The fix (ENG-O6): the stdio transport computes
+ * `explicitReadBinding` (bound source + non-archived `federated === true`
+ * sources; just the bound source when it opted out, E-T2) and
+ * `federatedSearchScope` alone passes it to `resolveRequestedScope` as the
+ * explicit-read admission set. Unqualified reads stay scalar; image, loops
+ * and code-intel keep denying; `requireWritablePage` is unchanged.
+ *
+ * Contexts are built by the real stdio scope resolver
+ * (`resolveMcpStdioSourceScope`) and calls go through `dispatchToolCall`, the
+ * same path `gbrain serve` uses. The subprocess transport test lives in
+ * test/serve-stdio-bound-explicit-read.test.ts.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
+import type { AuthInfo, OperationContext } from '../src/core/operations.ts';
+import { requireWritablePage, resolveCodeIntelScope } from '../src/core/ops/context.ts';
+import { dispatchToolCall, buildOperationContext, type DispatchOpts } from '../src/mcp/dispatch.ts';
+import { resolveMcpStdioSourceScope } from '../src/mcp/server.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let outsideCwd: string;
+const SOURCES = ['default', 'work', 'notes', 'private', 'iso'] as const;
+const MARKER = 'zebratelescope';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ outsideCwd = mkdtempSync(join(tmpdir(), 'gbrain-5081-cwd-'));
+ // Seeded 'default' is federated=true. work: the bound anchor (federated
+ // unset). notes: federated. private: never federated. iso: opted out.
+ const configs: Record<string, string> = {
+ work: '{}', notes: '{"federated": true}', private: '{}', iso: '{"federated": false}',
+ };
+ for (const [id, config] of Object.entries(configs)) {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)`,
+ [id, mkdtempSync(join(tmpdir(), `gbrain-5081-${id}-`)), config],
+ );
+ }
+ for (const id of SOURCES) {
+ const result = await importFromContent(engine, `topics/${id}-topic`,
+ serializeMarkdown({}, `the ${MARKER} lives in ${id}`, '', { type: 'note', title: `Topic in ${id}`, tags: [] }),
+ { sourceId: id, noEmbed: true, forceRechunk: true });
+ expect(result.status).toBe('imported');
+ }
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+/** Dispatch options exactly as src/mcp/server.ts builds them for one call. */
+async function stdioOpts(env: Record<string, string | undefined>, cwd = outsideCwd): Promise<DispatchOpts> {
+ const scope = await withEnv(env, () => resolveMcpStdioSourceScope(engine, cwd));
+ return {
+ remote: true,
+ transport: 'stdio',
+ takesHoldersAllowList: ['world'],
+ sourceId: scope.sourceId,
+ ...(scope.localFederatedSourceIds ? { localFederatedSourceIds: scope.localFederatedSourceIds } : {}),
+ ...(scope.explicitReadBinding ? { explicitReadBinding: scope.explicitReadBinding } : {}),
+ };
+}
+
+const bound = (id = 'work') => stdioOpts({ GBRAIN_SOURCE: id });
+
+async function call(opts: DispatchOpts, name: string, params: Record<string, unknown>) {
+ const result = await dispatchToolCall(engine, name, params, opts);
+ return { isError: result.isError === true, body: JSON.parse(result.content[0].text) };
+}
+
+function sourcesOf(body: unknown): string[] {
+ const rows = Array.isArray(body) ? body : ((body as { results?: unknown[] }).results ?? []);
+ return [...new Set(rows.map((row) => (row as { source_id: string }).source_id))].sort();
+}
+
+/** Each fixture page is `topics/<source>-topic`, so a slug names its source. */
+function sourcesOfSlugs(slugs: string[]): string[] {
+ return [...new Set(slugs.map((slug) => slug.replace(/^topics\/(.*)-topic$/, '$1')))].sort();
+}
+
+const reads: Array<[name: string, params: (sourceId: string) => Record<string, unknown>, sources: (body: any) => string[]]> = [
+ ['search', (s) => ({ query: MARKER, source_id: s }), sourcesOf],
+ ['query', (s) => ({ query: MARKER, expand: false, source_id: s }), sourcesOf],
+ ['get_page', (s) => ({ slug: `topics/${s}-topic`, source_id: s }), (b) => [b.source_id]],
+ ['list_pages', (s) => ({ source_id: s }), sourcesOf],
+ ['resolve_slugs', (s) => ({ partial: 'topics', source_id: s }), (b) => sourcesOfSlugs(b)],
+ ['recall', (s) => ({ query: MARKER, source_id: s }), (b) => sourcesOfSlugs(b.results.map((r: { slug: string }) => r.slug))],
+];
+
+describe('#5081 — transport computes the explicit-read binding', () => {
+ test('GBRAIN_SOURCE binding: bound source + federated sources; unqualified scope stays scalar', async () => {
+ const scope = await withEnv({ GBRAIN_SOURCE: 'work' }, () => resolveMcpStdioSourceScope(engine, outsideCwd));
+ expect(scope.tier).toBe('env');
+ expect(scope.localFederatedSourceIds).toBeUndefined();
+ expect(scope.explicitReadBinding).toEqual({
+ sourceId: 'work', via: 'GBRAIN_SOURCE', sourceIds: ['work', 'default', 'notes'], optedOut: ['iso'],
+ });
+ });
+
+ test('E-T2: an isolated anchor (federated: false) admits only itself', async () => {
+ const scope = await withEnv({ GBRAIN_SOURCE: 'iso' }, () => resolveMcpStdioSourceScope(engine, outsideCwd));
+ expect(scope.explicitReadBinding?.sourceIds).toEqual(['iso']);
+ });
+
+ test('.gbrain-source pin produces a dotfile binding', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5081-pin-'));
+ writeFileSync(join(dir, '.gbrain-source'), 'work\n');
+ const scope = await withEnv({ GBRAIN_SOURCE: undefined }, () => resolveMcpStdioSourceScope(engine, dir));
+ expect(scope.tier).toBe('dotfile');
+ expect(scope.explicitReadBinding?.via).toBe('.gbrain-source');
+ expect(scope.explicitReadBinding?.sourceIds).toEqual(['work', 'default', 'notes']);
+ });
+
+ test('an unbound stdio connection gets no binding (its federated widening is unchanged)', async () => {
+ const scope = await withEnv({ GBRAIN_SOURCE: undefined }, () => resolveMcpStdioSourceScope(engine, outsideCwd));
+ expect(scope.explicitReadBinding).toBeUndefined();
+ expect(scope.localFederatedSourceIds).toEqual(['default', 'notes']);
+ });
+});
+
+describe('#5081 — explicit reads from a GBRAIN_SOURCE-bound stdio connection', () => {
+ for (const [name, params, sources] of reads) {
+ test(`${name}: an explicit federated source is admitted and returns only that source`, async () => {
+ const { isError, body } = await call(await bound(), name, params('notes'));
+ expect(isError).toBe(false);
+ expect(sources(body)).toEqual(['notes']);
+ });
+
+ test(`${name}: a source that is not federated is denied with the bound-connection hint`, async () => {
+ const { isError, body } = await call(await bound(), name, params('private'));
+ expect(isError).toBe(true);
+ expect(['permission_denied', 'scope_denied']).toContain(body.error);
+ expect(body.suggestion).toBe(
+ 'This connection is bound to source work (GBRAIN_SOURCE). private is not federated; the brain owner can run '
+ + '`gbrain sources federate private` on the brain host, or start this connection without GBRAIN_SOURCE.',
+ );
+ });
+ }
+
+ test('denials carry the docs anchor', async () => {
+ const { body } = await call(await bound(), 'search', { query: MARKER, source_id: 'private' });
+ expect(body.docs).toBe('docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection');
+ });
+
+ test('a target that opted out is named as opted out', async () => {
+ const { body } = await call(await bound(), 'search', { query: MARKER, source_id: 'iso' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toContain('iso opted out of federation (federated: false)');
+ expect(body.suggestion).toContain('`gbrain sources federate iso`');
+ });
+
+ test('unqualified reads stay scalar on the bound source', async () => {
+ expect(sourcesOf((await call(await bound(), 'search', { query: MARKER })).body)).toEqual(['work']);
+ expect(sourcesOf((await call(await bound(), 'list_pages', {})).body)).toEqual(['work']);
+ const hidden = await call(await bound(), 'get_page', { slug: 'topics/notes-topic' });
+ expect(hidden.isError).toBe(true);
+ });
+
+ test('__all__ is unchanged: it stays on the bound source', async () => {
+ const { body } = await call(await bound(), 'search', { query: MARKER, source_id: '__all__' });
+ expect(sourcesOf(body)).toEqual(['work']);
+ });
+
+ test('E-T2: an isolated anchor is refused with its own opt-out hint', async () => {
+ const { isError, body } = await call(await bound('iso'), 'search', { query: MARKER, source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.suggestion).toBe(
+ 'This connection is bound to source iso (GBRAIN_SOURCE). iso opted out of federation (federated: false), so it '
+ + 'reads no other source; the brain owner can run `gbrain sources federate iso` on the brain host, or start this '
+ + 'connection without GBRAIN_SOURCE.',
+ );
+ const own = await call(await bound('iso'), 'search', { query: MARKER, source_id: 'iso' });
+ expect(sourcesOf(own.body)).toEqual(['iso']);
+ });
+
+ test('.gbrain-source binding names the pin in its hint', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5081-pin-'));
+ writeFileSync(join(dir, '.gbrain-source'), 'work\n');
+ const opts = await stdioOpts({ GBRAIN_SOURCE: undefined }, dir);
+ expect(sourcesOf((await call(opts, 'search', { query: MARKER, source_id: 'notes' })).body)).toEqual(['notes']);
+ const { body } = await call(opts, 'search', { query: MARKER, source_id: 'private' });
+ expect(body.suggestion).toBe(
+ 'This connection is bound to source work (.gbrain-source). private is not federated; the brain owner can run '
+ + '`gbrain sources federate private` on the brain host, or start this connection outside the directory pinned by .gbrain-source.',
+ );
+ });
+});
+
+describe('#5081 — callers that pass no admission set keep denying (ENG-O6 pins)', () => {
+ const ORIGINAL_HINT = 'Request access to this source, or omit source_id to search within your grant.';
+
+ test('search_by_image still denies an explicit federated source', async () => {
+ const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
+ const { isError, body } = await call(await bound(), 'search_by_image', { image_data: png, source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(ORIGINAL_HINT);
+ });
+
+ test('open_loops still denies an explicit federated source', async () => {
+ const { isError, body } = await call(await bound(), 'open_loops', { source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(ORIGINAL_HINT);
+ });
+
+ test('code-intel scope resolution still denies an explicit federated source', async () => {
+ // The code_* ops are closed to agent callers outright, so pin the resolver they share.
+ const ctx = buildOperationContext(engine, {}, await bound()) as OperationContext;
+ expect(() => resolveCodeIntelScope(ctx, 'notes')).toThrow(expect.objectContaining({
+ code: 'permission_denied', suggestion: ORIGINAL_HINT,
+ }));
+ });
+
+ test('requireWritablePage is unchanged: a page in an admitted source is still not writable or disclosed', async () => {
+ const opts = await bound();
+ const ctx = buildOperationContext(engine, {}, opts) as OperationContext;
+ await expect(requireWritablePage(ctx, 'topics/notes-topic', 'add_link', 'from')).rejects.toMatchObject({
+ code: 'page_not_found',
+ });
+ });
+});
+
+describe('#5081 — HTTP tokens and unbound stdio keep the no-widening rule', () => {
+ async function noGrantOpts(): Promise<DispatchOpts> {
+ const auth = { token: '', clientId: 'legacy', scopes: ['read'], sourceId: 'default', hasSourceGrant: false } as AuthInfo;
+ return {
+ remote: true, transport: 'http', sourceId: 'default', auth,
+ localFederatedSourceIds: await noGrantFederatedScope(engine, false, 'default'),
+ };
+ }
+
+ test('no-grant token: an explicit federated read is admitted and is a subset of its unqualified read', async () => {
+ const opts = await noGrantOpts();
+ const explicit = sourcesOf((await call(opts, 'search', { query: MARKER, source_id: 'notes' })).body);
+ const unqualified = sourcesOf((await call(opts, 'search', { query: MARKER })).body);
+ expect(explicit).toEqual(['notes']);
+ for (const id of explicit) expect(unqualified).toContain(id);
+ });
+
+ test('no-grant token: a source outside the federated set is denied as not federated', async () => {
+ const { body } = await call(await noGrantOpts(), 'search', { query: MARKER, source_id: 'private' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(
+ 'private is not federated; the brain owner can run `gbrain sources federate private` on the brain host, '
+ + 'or omit source_id to read within this connection\'s sources.',
+ );
+ });
+
+ test('unbound stdio: an explicit federated read is a subset of its unqualified read', async () => {
+ const opts = await stdioOpts({ GBRAIN_SOURCE: undefined });
+ const explicit = sourcesOf((await call(opts, 'search', { query: MARKER, source_id: 'notes' })).body);
+ const unqualified = sourcesOf((await call(opts, 'search', { query: MARKER })).body);
+ expect(explicit).toEqual(['notes']);
+ for (const id of explicit) expect(unqualified).toContain(id);
+ expect((await call(opts, 'search', { query: MARKER, source_id: 'private' })).isError).toBe(true);
+ });
+
+ test('a granted OAuth token is told about its grant, with the filled rescope command', async () => {
+ const auth = {
+ token: '', clientId: 'client-a', scopes: ['read'], sourceId: 'work', allowedSources: ['work'],
+ principal: { kind: 'oauth_client', id: 'client-a' },
+ } as AuthInfo;
+ const opts: DispatchOpts = {
+ remote: true, transport: 'http', sourceId: 'work', auth,
+ localFederatedSourceIds: ['work', 'default', 'notes'],
+ };
+ const { body } = await call(opts, 'search', { query: MARKER, source_id: 'notes' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(
+ 'Your token is not granted notes; ask the brain owner to grant it '
+ + '(gbrain auth rescope-client client-a --federated-read work,notes).',
+ );
+ });
+
+ test('a granted legacy token is told to ask for a grant', async () => {
+ const auth = { token: '', clientId: 'legacy', scopes: ['read'], sourceId: 'work', hasSourceGrant: true } as AuthInfo;
+ const { body } = await call({ remote: true, transport: 'http', sourceId: 'work', auth }, 'search', { query: MARKER, source_id: 'notes' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe('Your token is not granted notes; ask the brain owner to grant it.');
+ });
+});
diff --git a/test/mcp-stdio-source-resolution.test.ts b/test/mcp-stdio-source-resolution.test.ts
index 3a6b7ca3bc..3763001b12 100644
--- a/test/mcp-stdio-source-resolution.test.ts
+++ b/test/mcp-stdio-source-resolution.test.ts
@@ -52,7 +52,13 @@ describe('stdio MCP source resolution', () => {
dir,
);
- expect(scope).toEqual({ sourceId: 'team-alpha', tier: 'dotfile' });
+ // #5081: an explicit tier carries the explicit-read binding; no source
+ // in this fixture is federated, so it admits only the bound source.
+ expect(scope).toEqual({
+ sourceId: 'team-alpha',
+ tier: 'dotfile',
+ explicitReadBinding: { sourceId: 'team-alpha', via: '.gbrain-source', sourceIds: ['team-alpha'], optedOut: [] },
+ });
});
});
@@ -67,7 +73,11 @@ describe('stdio MCP source resolution', () => {
dir,
);
- expect(scope).toEqual({ sourceId: 'env-source', tier: 'env' });
+ expect(scope).toEqual({
+ sourceId: 'env-source',
+ tier: 'env',
+ explicitReadBinding: { sourceId: 'env-source', via: 'GBRAIN_SOURCE', sourceIds: ['env-source'], optedOut: [] },
+ });
});
});
});
diff --git a/test/serve-stdio-bound-explicit-read.test.ts b/test/serve-stdio-bound-explicit-read.test.ts
new file mode 100644
index 0000000000..7fb7425549
--- /dev/null
+++ b/test/serve-stdio-bound-explicit-read.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #5081 over the real stdio transport: `gbrain serve` started with
+ * GBRAIN_SOURCE=work (the harness `.mcp.json` shape from the report) may name
+ * a federated source in an explicit `source_id` read, gets only that source's
+ * rows back, is refused a source that is not federated with the
+ * bound-connection hint, and keeps unqualified reads on the bound source.
+ *
+ * PGLite, hermetic temp HOME; the MCP SDK spawns `gbrain serve` and performs
+ * the same initialize handshake Claude Code does. The in-process matrix over
+ * every affected read lives in test/explicit-read-admission-5081.test.ts.
+ *
+ * Lane: unit. Run: `bun test test/serve-stdio-bound-explicit-read.test.ts`.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { spawnSync } from 'child_process';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { cliDiagnostic } from './helpers/fixture-diagnostics.ts';
+
+const MARKER = 'halcyon-bound-read-5081';
+
+function execFixture(args: string[], env: Record<string, string>): void {
+ const result = spawnSync('bun', ['--no-env-file', ...args], { cwd: process.cwd(), env, encoding: 'utf8' });
+ if (result.status !== 0) throw new Error(cliDiagnostic(args[2] ?? 'stdio fixture', {
+ exitCode: result.status ?? -1, stdout: result.stdout ?? '', stderr: result.stderr ?? '',
+ }));
+}
+
+function textOf(result: unknown): string {
+ const content = (result as { content?: Array<{ text?: string }> })?.content;
+ return Array.isArray(content) ? content.map((c) => c?.text ?? '').join('\n') : '';
+}
+
+function sourcesOf(text: string): string[] {
+ const rows = JSON.parse(text) as Array<{ source_id?: string }>;
+ return [...new Set(rows.map((row) => row.source_id ?? ''))].sort();
+}
+
+describe('#5081 — GBRAIN_SOURCE-bound stdio serve, explicit source_id reads', () => {
+ let home: string;
+ let client: Client | null = null;
+ let transport: StdioClientTransport | null = null;
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-stdio-5081-'));
+ const env = keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,
+ });
+ delete env.GBRAIN_SOURCE;
+ execFixture(['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], env);
+ for (const [id, flag] of [['work', null], ['notes', '--federated'], ['private', null]] as const) {
+ const dir = join(home, id);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, `${id}-page.md`),
+ `---\ntitle: ${MARKER} in ${id}\n---\n\n# ${MARKER}\n\nThis ${MARKER} page lives in the ${id} source.\n`);
+ execFixture(['run', 'src/cli.ts', 'sources', 'add', id, '--path', dir, ...(flag ? [flag] : []), '--force'], env);
+ execFixture(['run', 'src/cli.ts', 'import', dir, '--no-embed', '--source-id', id], env);
+ }
+
+ transport = new StdioClientTransport({
+ command: 'bun',
+ args: ['--no-env-file', 'run', 'src/cli.ts', 'serve'],
+ cwd: process.cwd(),
+ env: { ...env, GBRAIN_SOURCE: 'work' },
+ });
+ client = new Client({ name: 'gbrain-stdio-5081', version: '1.0.0' }, { capabilities: {} });
+ await client.connect(transport);
+ }, 120_000);
+
+ afterAll(async () => {
+ if (client) { try { await client.close(); } catch { /* best-effort */ } }
+ if (transport) { try { await transport.close(); } catch { /* best-effort */ } }
+ if (home) { try { rmSync(home, { recursive: true, force: true }); } catch { /* best-effort */ } }
+ });
+
+ test('search, query and get_page name a federated source and return only its rows', async () => {
+ const search = await client!.callTool({ name: 'search', arguments: { query: MARKER, source_id: 'notes', limit: 10 } });
+ expect(search.isError).toBeFalsy();
+ expect(sourcesOf(textOf(search))).toEqual(['notes']);
+
+ const query = await client!.callTool({ name: 'query', arguments: { query: MARKER, source_id: 'notes', expand: false, limit: 10 } });
+ expect(query.isError).toBeFalsy();
+ expect(sourcesOf(textOf(query))).toEqual(['notes']);
+
+ const page = await client!.callTool({ name: 'get_page', arguments: { slug: 'notes-page', source_id: 'notes' } });
+ expect(page.isError).toBeFalsy();
+ expect(JSON.parse(textOf(page)).source_id).toBe('notes');
+ }, 60_000);
+
+ test('a source that is not federated is refused with the bound-connection hint', async () => {
+ const res = await client!.callTool({ name: 'search', arguments: { query: MARKER, source_id: 'private' } });
+ expect(res.isError).toBe(true);
+ const body = JSON.parse(textOf(res));
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toStartWith('This connection is bound to source work (GBRAIN_SOURCE). private ');
+ expect(body.suggestion).toContain('`gbrain sources federate private` on the brain host, or start this connection without GBRAIN_SOURCE.');
+ }, 60_000);
+
+ test('unqualified reads stay on the bound source', async () => {
+ const res = await client!.callTool({ name: 'search', arguments: { query: MARKER, limit: 10 } });
+ expect(sourcesOf(textOf(res))).toEqual(['work']);
+ }, 60_000);
+});