Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(mcp): no ambient hot memory on a call that names its own sources
garrytan28aa3b7a5ca9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0d817d6c58..f6d96a57a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,15 +12,17 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**`recall` and `list_pages` now honour `source_ids`, the per-request source narrowing `search` and `query` already had. Before, both ops ignored the list, so an agent narrowing each call to the asking member's sources still got other sources' facts and pages from these two tools.** A harness-evals run measured it: under per-request narrowing, `recall` returned a page from outside the requester's sources twice and `list_pages` 57 pages over three calls. Each id is checked like an explicit `source_id`, so the list can only narrow what the token's grant allows; an id outside a remote grant refuses the whole request, and an empty intersection with `source_id` returns nothing with an `empty_retrieval` notice.+**`recall` and `list_pages` now honour `source_ids`, the per-request source narrowing `search` and `query` already had. Before, both ops ignored the list, so an agent narrowing each call to the asking member's sources still got other sources' facts and pages from these two tools.** A harness-evals run measured it: under per-request narrowing, `recall` returned a page from outside the requester's sources twice and `list_pages` 57 pages over three calls. Each id is checked like an explicit `source_id`, so the list can only narrow what the token's grant allows; an id outside a remote grant refuses the whole request, and an empty intersection with `source_id` returns nothing with an `empty_retrieval` notice. A call that names its own sources also no longer gets `_meta.brain_hot_memory`, which reads the connection's source.### Itemized changes- `src/core/ops/facts.ts`: `recall` takes `source_ids` and reads every fact arm and its page-search arm inside the narrowed scope.- `src/core/ops/pages.ts`: `list_pages` takes `source_ids`.- `src/core/ops/search-source-scope.ts`: the shared parser and resolver serve all four ops.+- `src/mcp/dispatch.ts`: the hot-memory hook is skipped when a call names `source_ids` or a `source_id` other than the connection's.+- `docs/protocol/MCP_META_CHANNELS.md`: says when `brain_hot_memory` is left out.- `docs/guides/multi-source-brains.md`: "Narrow one request with `source_ids`" names all four ops.-- `test/recall-list-pages-source-ids.test.ts` (PGLite and Postgres): each recall arm and list_pages under narrowing, the grant refusal and the empty intersection; red on the old code.+- `test/recall-list-pages-source-ids.test.ts` (PGLite and Postgres): each recall arm and list_pages under narrowing, the grant refusal, the empty intersection, and starter-surface dispatch with the hot-memory hook; red on the old code.## [0.60.519.0] - 2026-10-30diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex e0f0d49089..a72c379ddd 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -42,7 +42,9 @@ in front of the model without a separate call.**When it is sent.** On a successful tool call over stdio (`gbrain serve`) andover HTTP (`gbrain serve --http`), except `recall`, `extract_facts` and-`forget_fact`, which already return facts. It is absent when there is nothing+`forget_fact`, which already return facts, and except a call that names its own+sources (a non-empty `source_ids`, or a `source_id` other than the connection's+source), so a narrowed request never carries another source's facts. It is absent when there is nothingto send, and it is best-effort: if it cannot be built, the key is left out andthe tool call still succeeds. It cannot be turned off per call.diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 98bc2d16ac..23dd931305 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -1078,7 +1078,12 @@ async function dispatchResolvedCall(// #5575 CEO-18: a floored connection only reaches read ops that enforce its floor.enforceReadTrustFloor(ctx.auth, op);// GBRA-156: a read op does not change what the hook reads, so it runs beside the handler (a degraded engine's reconnect stays the handler's).- const earlyMeta = opts.metaHook && op.mutating === false && !isEngineDegraded(engine) ? runMetaHook(opts.metaHook, name, ctx) : undefined;+ // The hot-memory hook reads ctx.sourceId only, so a call that names its own sources gets no ambient-source payload.+ const namedIds = safeParams.source_ids;+ const namesSources = (Array.isArray(namedIds) ? namedIds.length > 0 : typeof namedIds === 'string' && namedIds.trim() !== '')+ || (typeof safeParams.source_id === 'string' && safeParams.source_id !== '' && safeParams.source_id !== ctx.sourceId);+ const metaHook = namesSources ? undefined : opts.metaHook;+ const earlyMeta = metaHook && op.mutating === false && !isEngineDegraded(engine) ? runMetaHook(metaHook, name, ctx) : undefined;const sharedStdio = ctx.transport === 'stdio' && !ctx.auth &&(op.requiredScopes?.length || ['list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack'].includes(name));let registration: Awaited<ReturnType<typeof readLocalWriter>> | undefined;@@ -1170,8 +1175,8 @@ async function dispatchResolvedCall(// The hook is wrapped in its own try/catch — any DB blip / cache miss /// helper crash degrades to no hook keys rather than flipping the whole// tool call to error.- if (opts.metaHook) {- const { meta, failure } = await (earlyMeta ?? runMetaHook(opts.metaHook, name, ctx));+ if (metaHook) {+ const { meta, failure } = await (earlyMeta ?? runMetaHook(metaHook, name, ctx));if (meta && Object.keys(meta).length > 0) out._meta = { ...(out._meta ?? {}), ...meta };if (failure !== undefined) ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${failure}; degrading to no hook keys`);}diff --git a/test/recall-list-pages-source-ids.test.ts b/test/recall-list-pages-source-ids.test.tsindex b01110f98b..bb5d2c0402 100644--- a/test/recall-list-pages-source-ids.test.ts+++ b/test/recall-list-pages-source-ids.test.ts@@ -20,6 +20,10 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { importFromContent } from '../src/core/import-file.ts';import { operationsByName, type OperationContext } from '../src/core/operations.ts';import { testBackends } from './helpers/test-backends.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { allowedOpNames } from '../src/mcp/surface.ts';+import { getBrainHotMemoryMeta, __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';+import { operations } from '../src/core/operations.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';const CANARY = 'canarybravo';@@ -121,6 +125,43 @@ for (const kind of testBackends()) {expect(recall.notices.map(n => n.code)).toContain('empty_retrieval');});+ for (const extra of [{ supersessions: true }, { session_id: 's1' }, { include_pending: true, query: 'zephyrblatt', entity: 'zephyrblatt-orchard' }]) {+ test(`recall ${JSON.stringify(extra)}: an empty intersection reads nothing`, async () => {+ const { wire } = await run('recall', { ...extra, source_id: 'source-a', source_ids: ['source-c'] });+ expect(wire).not.toContain('Zephyrblatt');+ expect(wire).not.toContain(CANARY);+ });+ }++ describe('through dispatch on the starter surface', () => {+ const call = (name: string, args: Record<string, unknown>) => dispatchToolCall(engine, name, args, {+ remote: true, transport: 'http', sourceId: 'source-a', auth: GRANTED_ABC as never, surface: 'starter',+ allowedOps: allowedOpNames(operations as never, 'starter'), config: { engine: kind, embedding_disabled: true } as never,+ metaHook: getBrainHotMemoryMeta,+ } as never) as Promise<{ isError?: boolean; content: Array<{ text: string }>; _meta?: Record<string, unknown> }>;++ test('the hidden source_ids param still narrows recall and list_pages', async () => {+ const list = await call('list_pages', { source_ids: ['source-b'] });+ expect(list.content[0].text).toContain('chats/orchard-bravo');+ expect(list.content[0].text).not.toContain('orchard-alpha');+ const recall = await call('recall', { query: 'zephyrblatt orchard harvest', source_ids: ['source-b'] });+ expect(recall.content[0].text).toContain(CANARY);+ expect(recall.content[0].text).not.toContain('alpha team');+ });++ test('a call that names sources gets no ambient-source hot memory', async () => {+ __resetHotMemoryCacheForTests();+ const control = await call('list_pages', {});+ expect(JSON.stringify(control._meta?.brain_hot_memory ?? null)).toContain('alpha team');+ for (const [name, args] of [['list_pages', { source_ids: ['source-b'] }], ['search', { query: 'zephyrblatt', source_ids: ['source-b'] }], ['list_pages', { source_id: 'source-b' }]] as const) {+ const out = await call(name, args);+ expect(out.isError ?? false).toBe(false);+ expect(out._meta?.brain_hot_memory).toBeUndefined();+ expect(JSON.stringify(out)).not.toContain('alpha team');+ }+ });+ });+test('an empty array behaves exactly like omitting it', async () => {const omitted = (await run('list_pages', {})).wire;expect((await run('list_pages', { source_ids: [] })).wire).toBe(omitted);