Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-200: a write-grant refusal names the writable source; remember retries there

garrytanecd2194ed3e6
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 2564b9525c..4faffdfda3 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -7,6 +7,7 @@
- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.
- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work; the call then rebuilds the withdrawn pages' text projections before acknowledging, because a CLI process has no resident projection worker (a failed rebuild stays queued). `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL; `test/withdrawal-followup-writes.test.ts` covers writes after a forget whose effects stay queued. #5836: an omitted `entity` is inferred before admission (`inferRememberTarget`), and the inferred slug is used only when `planRememberTarget`'s checks pass as predicates (plus withdrawal, fence parse, no owner claim); otherwise the save is unattributed with `warnings` (`NO_ENTITY`/`ENTITY_LINK_FAILED`) + `hint`. The `entity_inferred` intent marker makes preparation dedup exact text only (never supersede) and notes the context; `test/remember-entity-inference.test.ts`. `remember.replaces` (caller-directed replacement): `decideReplacement` (`facts/single-prepare.ts`) replaces the cosine decision when the intent names a target; it is checked at submission (fail fast) and again in `validate` with the target row locked `FOR UPDATE`, so two replacements of one fact serialize and the second sees `target_superseded`. Refusals are `invalid_params` with code prefixes (`target_withdrawn`, `target_superseded` naming the chain head, `target_expired`, `replaces_entity_mismatch`, `replaces_cross_page`, `replaces_duplicate`); remote callers get `not_found` for private targets; equal text is a `duplicate` no-op. Every `superseded` outcome carries `superseded_fact_id` (plus `replaced_by_caller` for `replaces`). `forget` responses gain `similar_active` (`facts/similar-active.ts`) after commit and on replay, and `semantic_review: false` keeps the claim out of overnight review. Pinned by `test/remember-replaces.test.ts`. remember's write intent carries the transport-resolved `ctx.sessionId` (MCP `_meta.session_id`, clamped to 256 characters), and preparation stores it as the fact's `source_session`, so `recall({session_id})` finds remembered facts; identity only, never an authorization input (`test/remember-session.test.ts`). #7248: a folder-less `entity` must resolve strictly or is refused with candidates; pending replies carry `write_request.target` (`test/remember-entity-target-7248.test.ts`).
+- `src/core/persistence/write-grant.ts` — the one refusal for a remote write naming a source outside the caller's write grant (remember and every page mutation): `writable_source_ids` lists only the caller's own grant source (`[]` for a sentinel), identical whether the named source exists; remember's `fix` repeats the call against that source (GBRA-200).
- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index cd9d3682ed..89d48a363f 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -325,6 +325,18 @@ rides the immediate refusal, the `items[]` error, the failed write receipt and
paraphrase, and its absence carries no meaning: the message prefix, code and
suggestion are unchanged.
+#### write-grant refusal detail (additive)
+
+A `remember` (or page write) naming a `source_id` outside the connection's write
+grant is refused `scope_denied` with `write_error: permission_denied`, and the
+envelope carries `writable_source_ids`: the sources this connection's own grant
+lets it write (one id, or `[]` when the grant holds no single writable source).
+It never names a source outside the grant, a federated read source included,
+and the refusal is identical whether the named source exists or not. On
+`remember` with one writable source, `fix` is the same call with `source_id` set
+to it (`next: run`, no `request_id`); page writes carry no fix, so their content
+is never echoed back.
+
#### remember replaces (additive)
`replaces` (string): the `fact_id` this fact replaces, caller-directed: the
diff --git a/llms-full.txt b/llms-full.txt
index d166308e64..1f62d13721 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -8852,6 +8852,18 @@ rides the immediate refusal, the `items[]` error, the failed write receipt and
paraphrase, and its absence carries no meaning: the message prefix, code and
suggestion are unchanged.
+#### write-grant refusal detail (additive)
+
+A `remember` (or page write) naming a `source_id` outside the connection's write
+grant is refused `scope_denied` with `write_error: permission_denied`, and the
+envelope carries `writable_source_ids`: the sources this connection's own grant
+lets it write (one id, or `[]` when the grant holds no single writable source).
+It never names a source outside the grant, a federated read source included,
+and the refusal is identical whether the named source exists or not. On
+`remember` with one writable source, `fix` is the same call with `source_id` set
+to it (`next: run`, no `request_id`); page writes carry no fix, so their content
+is never echoed back.
+
#### remember replaces (additive)
`replaces` (string): the `fact_id` this fact replaces, caller-directed: the
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index 29eefb2cc6..9bd18aa722 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -115,6 +115,8 @@ export interface AgentEnvelope {
fence?: Record<string, unknown>; fence_issues?: Array<Record<string, unknown>>;
/** A `fact_withdrawn` refusal's withdrawal (`at`, `subject`, `visibility`). */
withdrawn?: WithdrawnDetail;
+ /** A write-grant refusal's writable sources, from the caller's own grant only (GBRA-200). */
+ writable_source_ids?: string[];
}
export interface RenderContext {
@@ -387,6 +389,7 @@ export interface EnvelopeParts {
fence?: Record<string, unknown>;
fence_issues?: Array<Record<string, unknown>>;
withdrawn?: WithdrawnDetail;
+ writable_source_ids?: string[];
}
/** Replace each occurrence of `bare` that is a whole command (not followed by a word, path or more flags). */
@@ -436,6 +439,7 @@ export function buildEnvelope(p: EnvelopeParts, ctx: RenderContext): AgentEnvelo
...(p.fence !== undefined ? { fence: p.fence } : {}),
...(p.fence_issues?.length ? { fence_issues: p.fence_issues } : {}),
...(p.withdrawn !== undefined ? { withdrawn: p.withdrawn } : {}),
+ ...(p.writable_source_ids !== undefined ? { writable_source_ids: p.writable_source_ids } : {}),
...(p.reason !== undefined ? { reason: p.reason } : {}),
...(p.why !== undefined ? { why: p.why } : {}),
...(fix ? { fix } : {}),
@@ -579,6 +583,7 @@ const ROWS: Row[] = [
write_request: j.write_request, write_error: e.writeError,
...(e.fence ? { fence: e.fence } : {}), ...(e.fenceIssues?.length ? { fence_issues: e.fenceIssues } : {}),
...(e.withdrawn ? { withdrawn: e.withdrawn } : {}),
+ ...(e.writableSourceIds ? { writable_source_ids: e.writableSourceIds } : {}),
...(e.retryable !== undefined ? { retryable: e.retryable } : {}),
};
},
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d4e1494cbd..32569646e8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1294,6 +1294,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.452.0', id: 'sources_not_readable_gbra156', text: 'An unscoped `search`, `query`, `recall` or `list_pages` from a token or agent connection with no source grant that comes back empty, while every source it can read holds no page and other sources do, now carries a `sources_not_readable` notice (kind degraded). It says the empty result is not proof of absence, never names a hidden source, and its fix is `gbrain sources federate <source>` on the brain host, or a grant for the token. Granted tokens and OAuth clients never get it.' },
{ since: '0.60.452.0', id: 'sources_add_federation_warning_gbra156', text: '`gbrain sources add` without `--federated` or `--no-federated` now warns on stderr that the new source is not federated, so a remote token or agent connection with no source grant cannot read its pages, and names `gbrain sources federate <id>` and `gbrain auth rescope --token <name> --sources <id>`. The stored default is still non-federated.' },
// GBRA-200 (harness ask 6: stamp degraded replies). `since` is stamped at the merge slot.
+ { since: 'TBD', id: 'write_grant_refusal_gbra200', text: 'A `remember` or page write naming a `source_id` outside the connection\'s write grant is still refused `scope_denied`, and the refusal now carries `writable_source_ids`: the sources the connection\'s own grant lets it write, never another source, identical whether the named source exists or not. On `remember` the `fix` repeats the call against that source, so a harness can retry instead of giving up.' },
{ since: 'TBD', id: 'degraded_stamp_gbra200', text: 'Every degraded or partial read result now carries one stamp naming why with stable codes: an MCP result gets `_meta.degraded: { reasons: [...] }` and one extra text block, `[gbrain degraded: <reasons>] ...`, after the others; a CLI `--json` object gets a `degraded` key, and other CLI output (human text, a bare `--json` array such as search results) gets that line on stderr. It covers search, query, recall, find_experts, context_pack, delta, entity, get_page (`file_held`), think and synthesize, search_exact, open_loops and rank_entities. recall and think no longer drop their page search\'s degraded stages (an embed timeout, a failed arm, the keyword rank bound): recall reports them in `_meta.retrieval.degraded` and its `degraded_recall` notice, think and synthesize as `GATHER_DEGRADED:<stage>` warnings, and a keyword-only search or recall on Postgres reports `keyword_candidates_incomplete` when the rank bound applies. A clean result carries no stamp, and no existing field changed.' },
];
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 124bec4f4a..ae7ec1707e 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -96,6 +96,8 @@ export class OperationError extends Error {
public fenceIssues?: Array<Record<string, unknown>>;
/** A `fact_withdrawn` refusal's withdrawal: when and for which subject the exact claim was forgotten. Absence carries no meaning. */
public withdrawn?: WithdrawnDetail;
+ /** A write-grant refusal's writable sources: only ids the caller's own grant lets it write, never another source (GBRA-200). */
+ public writableSourceIds?: string[];
/** #6643: a managed-sync refusal's owner-side classification (knock-on root, cursor fence snapshot); stored as the receipt's error_detail, never in the envelope. */
public syncRefusal?: Record<string, unknown>;
/** Set to 1 by opError(); toJSON() emits `contract_version` only when set. */
@@ -162,6 +164,7 @@ export class OperationError extends Error {
...(this.fence ? { fence: this.fence } : {}),
...(this.fenceIssues?.length ? { fence_issues: this.fenceIssues } : {}),
...(this.withdrawn ? { withdrawn: this.withdrawn } : {}),
+ ...(this.writableSourceIds ? { writable_source_ids: this.writableSourceIds } : {}),
...(this.contractVersion !== undefined ? { contract_version: this.contractVersion } : {}),
};
}
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 6aa956c3f3..4885b67f32 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -24,6 +24,7 @@ import { declareDurablePersistence } from './protocol.ts';
import { resolveFactWriteTarget } from './fact-write-target.ts';
import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';
import { withCoordinatedWrite } from './context.ts';
+import { grantedWriteSource, writeGrantRefusal } from './write-grant.ts';
import { requestAttribution } from './attribution.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { prepareMemoryMutation } from './memory-prepare.ts';
@@ -49,9 +50,11 @@ async function submission(ctx: OperationContext, operation: string, params: Reco
const p: Record<string, unknown> = { ...params, ...parseMutationPrecondition(params) };
const requestId = typeof p.request_id === 'string' ? p.request_id : randomUUID();
const sourceId = typeof p.source_id === 'string' ? p.source_id : ctx.sourceId ?? 'default';
- if (ctx.remote !== false && sourceId !== (ctx.auth?.sourceId ?? ctx.sourceId ?? 'default')) {
- throw opError('permission_denied', 'This source is outside the current write grant.',
- `This connection may write only to source ${ctx.auth?.sourceId ?? ctx.sourceId ?? 'default'}. Omit source_id to write there, or ask the brain host's operator to grant source ${sourceId}.`);
+ const granted = grantedWriteSource(ctx);
+ if (ctx.remote !== false && sourceId !== granted) {
+ throw writeGrantRefusal(ctx,
+ `This connection may write only to source ${granted}. Omit source_id to write there, or ask the brain host's operator to grant source ${sourceId}.`,
+ { tool: operation, arguments: params });
}
await initializeLocalPersistence(ctx);
const principal = await requestPrincipalForContext(ctx);
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index aa17073e6d..fc5f40b7c8 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -6,6 +6,7 @@ import { realpathSync } from 'node:fs';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import type { OperationContext } from '../ops/contract.ts';
import { OperationError } from '../ops/contract.ts';
+import { grantedWriteSource, writeGrantRefusal } from './write-grant.ts';
import { VERSION } from '../../version.ts';
import { ownerBuildMismatch } from './publication-failure.ts';
import { enforceClientSlugFence, enforceSubagentSlugFence, isLegacyStoredPageSlug, normalizeSlugPrefix, parseSourceIdParam, requireWritablePage, validatePageSlug } from '../ops/context.ts';
@@ -135,9 +136,9 @@ export function pageMutationSource(ctx: OperationContext, params: Record<string,
throw new OperationError('invalid_params', 'A mutation must target exactly one source.',
`Pass source_id as one source (for example ${ctx.sourceId && ctx.sourceId !== '__all__' ? ctx.sourceId : 'default'}); writes never fan out across sources.`);
}
- const granted = ctx.auth?.sourceId ?? ctx.sourceId ?? 'default';
+ const granted = grantedWriteSource(ctx);
if (ctx.remote !== false && sourceId !== granted) {
- throw new OperationError('permission_denied', 'This source is outside the current write grant.',
+ throw writeGrantRefusal(ctx,
`This connection writes only to source ${granted}. Pass source_id ${granted} (or omit it), or ask the brain host's operator to grant write access to ${sourceId}.`);
}
return sourceId;
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index 9e3bfb1597..1369824f42 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -236,6 +236,8 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {
if (error.code === 'idempotency_conflict' && error.fix) frozen.fix = error.fix;
// #6608: an unbound-source refusal keeps its detail, docs and ask-the-user fix additively; the frozen code stays.
if (error.detail === 'unbound_source') Object.assign(frozen, { detail: error.detail, docs: error.docs, fix: error.fix, retryable: error.retryable });
+ // GBRA-200: a write-grant refusal keeps the caller's writable sources and its retry fix additively.
+ if (error.writableSourceIds) Object.assign(frozen, { writableSourceIds: error.writableSourceIds, fix: error.fix });
if (isWriteErrorCode(error.code)) frozen.writeError=error.code;
throw frozen;
}
diff --git a/src/core/persistence/write-grant.ts b/src/core/persistence/write-grant.ts
new file mode 100644
index 0000000000..c851febda5
--- /dev/null
+++ b/src/core/persistence/write-grant.ts
@@ -0,0 +1,28 @@
+import type { OperationContext } from '../ops/contract.ts';
+import { OperationError } from '../ops/contract.ts';
+import { ALL_SOURCES, NO_SOURCES } from '../source-id.ts';
+
+/** The one source a remote caller may write: its grant's source, else the connection's, else default. */
+export function grantedWriteSource(ctx: OperationContext): string {
+ return ctx.auth?.sourceId ?? ctx.sourceId ?? 'default';
+}
+
+/**
+ * GBRA-200: the refusal for a write naming a source outside the caller's write grant. It names the sources the
+ * caller's own grant lets it write (`writable_source_ids`, empty when the grant holds a sentinel) and never another
+ * source, so the envelope is identical whether the named source exists or not. `retry`, when given, is the same
+ * call aimed at the writable source, rendered as the fix.
+ */
+export function writeGrantRefusal(ctx: OperationContext, suggestion: string, retry?: { tool: string; arguments: Record<string, unknown> }): OperationError {
+ const granted = grantedWriteSource(ctx);
+ const writable = granted === ALL_SOURCES || granted === NO_SOURCES ? [] : [granted];
+ const e = new OperationError('permission_denied', 'This source is outside the current write grant.', suggestion);
+ e.writableSourceIds = writable;
+ if (retry && writable.length === 1) {
+ const args: Record<string, unknown> = { ...retry.arguments, source_id: writable[0] };
+ delete args.request_id;
+ e.fix = { mcp: { tool: retry.tool, arguments: args }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Repeats the call against ${writable[0]}, the source this connection may write.` };
+ }
+ return e;
+}
diff --git a/test/write-grant-refusal.test.ts b/test/write-grant-refusal.test.ts
new file mode 100644
index 0000000000..4be3f78a7a
--- /dev/null
+++ b/test/write-grant-refusal.test.ts
@@ -0,0 +1,77 @@
+/**
+ * GBRA-200 (HARN-1 gbrain-memory run): a write naming a source outside the caller's write grant used to answer
+ * `scope_denied` with prose only, so a harness gave up. The refusal now names the sources the caller's own grant lets
+ * it write (`writable_source_ids`) and, for remember, carries the same call aimed there as its fix. It never names a
+ * source outside the grant (a federated read source included), and it is identical whether the named source exists.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import type { AuthInfo } from '../src/core/operations.ts';
+
+type Out = { content: Array<{ text: string }>; isError?: boolean };
+const envelope = (out: Out): Record<string, any> => JSON.parse(out.content[0]!.text);
+const member = (sourceId: string): AuthInfo => ({ token: 't', clientId: 'member-example', principal: { kind: 'oauth_client', id: 'member-example' },
+ scopes: ['read', 'write'], sourceId, allowedSources: ['source-a', 'source-b'] } as AuthInfo);
+
+let engine: PGLiteEngine;
+const call = async (op: string, params: Record<string, unknown>, auth: AuthInfo = member('source-a')) =>
+ await dispatchToolCall(engine, op, { request_id: randomUUID(), ...params }, { remote: true, transport: 'stdio', sourceId: auth.sourceId, auth } as never) as Out;
+const fact = { fact: 'Alice Example prefers tea.', entity: 'alice-example', provenance: 'test' };
+const savedFacts = async () => (await engine.executeRaw<{ source_id: string }>("SELECT source_id FROM facts WHERE fact = $1 AND expired_at IS NULL", [fact.fact])).map(r => r.source_id);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.setConfig('sync.write_through', 'false');
+ for (const id of ['source-a', 'source-b', 'source-c']) await engine.executeRaw('INSERT INTO sources(id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING', [id]);
+ await engine.executeRaw("INSERT INTO oauth_clients(client_id, client_name, scope, source_id) VALUES ('member-example', 'Synthetic member client', 'read write', 'source-a')");
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+describe('remember outside the write grant (GBRA-200)', () => {
+ test('names only the writable source, never the federated read source, and saves nothing', async () => {
+ const out = await call('remember', { ...fact, source_id: 'source-c' });
+ expect(out.isError).toBe(true);
+ const e = envelope(out);
+ expect(e.error).toBe('scope_denied');
+ expect(e.writable_source_ids).toEqual(['source-a']);
+ expect(JSON.stringify(e)).not.toContain('source-b');
+ expect(await savedFacts()).toEqual([]);
+ });
+
+ test('the fix repeats the call against the writable source, and running it saves the fact there', async () => {
+ const e = envelope(await call('remember', { ...fact, source_id: 'source-c' }));
+ expect(e.fix).toMatchObject({ next: 'run', mcp: { tool: 'remember', arguments: { ...fact, source_id: 'source-a' } } });
+ expect(e.fix.mcp.arguments.request_id).toBeUndefined();
+ const retried = await call(e.fix.mcp.tool, e.fix.mcp.arguments);
+ expect(retried.isError).toBeFalsy();
+ expect(envelope(retried).status).toBe('inserted');
+ expect(await savedFacts()).toEqual(['source-a']);
+ });
+
+ test('a source that does not exist gets the same refusal as one that does', async () => {
+ const existing = envelope(await call('remember', { ...fact, source_id: 'source-c' }));
+ const missing = envelope(await call('remember', { ...fact, source_id: 'source-missing' }));
+ expect(JSON.stringify(missing).replaceAll('source-missing', 'source-c')).toBe(JSON.stringify(existing));
+ });
+
+ test('a grant whose source is a sentinel names no writable source and offers no retry', async () => {
+ const e = envelope(await call('remember', { ...fact, source_id: 'source-a' }, member('__all__')));
+ expect(e.error).toBe('scope_denied');
+ expect(e.writable_source_ids).toEqual([]);
+ expect(e.fix?.mcp?.tool).not.toBe('remember');
+ });
+});
+
+describe('page writes outside the write grant (GBRA-200)', () => {
+ test('put_page names the writable source too, without echoing the page back as a fix', async () => {
+ const content = '---\ntype: note\ntitle: Note\n---\n# Note\n\nBody.\n';
+ const existing = envelope(await call('put_page', { slug: 'notes/example', content, source_id: 'source-c' }));
+ expect(existing.writable_source_ids).toEqual(['source-a']);
+ expect(JSON.stringify(existing)).not.toContain('source-b');
+ expect(JSON.stringify(existing.fix ?? {})).not.toContain('Body.');
+ const missing = envelope(await call('put_page', { slug: 'notes/example', content, source_id: 'source-missing' }));
+ expect(JSON.stringify(missing).replaceAll('source-missing', 'source-c')).toBe(JSON.stringify(existing));
+ });
+});