Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(grants): slug-bound clients can remember; replaces answers not_found for a fact outside the prefixes (#5913)

garrytanf6394b0e53fb
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index 5ab4795733..52494509c7 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -448,8 +448,10 @@ activation lists it under `database_only_sources` and goes ahead (#6449). Page
writes to it publish to the database only (`write_through.skipped:
disabled_by_config`), `gbrain sync` on it refuses `owner_unavailable` naming the
claim, and turning `sync.write_through` back on does not claim it, not even on
-PGLite (activation records the listed sources in
-`persistence.database_only_sources`; deactivation clears it): the next write
+PGLite (activation records the listed source ids as a JSON array in the config
+key `persistence.database_only_sources`, deactivation clears it, and
+`gbrain config unset persistence.database_only_sources` is the escape hatch if a
+listing outlives its brain state; it is not a setting to edit by hand): the next write
refuses with `detail: unbound_source` and the `writer claim` to run (preview
with `--dry-run`), or stays database-only under
`persistence.unbound_write=database_only`. With `sync.write_through` on, the
diff --git a/docs/integrations/qm-harness.md b/docs/integrations/qm-harness.md
index 45ce9b086c..37c76835fd 100644
--- a/docs/integrations/qm-harness.md
+++ b/docs/integrations/qm-harness.md
@@ -46,7 +46,10 @@ Isolation model:
later (or one carrying a bespoke scope) is denied until it is explicitly
fenced and added to `CLIENT_FENCED_WRITE_OPS` (`src/core/operations.ts`).
`think` is allow-listed because remote callers cannot persist from it;
- `submit_agent` because it enforces this same column itself.
+ `submit_agent` because it enforces this same column itself; `remember`
+ (#5913) because it fences the one slug it writes and confines `replaces` to
+ the caller's entity. `forget`/`forget_fact` are not: a withdrawal's write set
+ reaches pages the fenced slug does not name.
- **Indirect write paths are gated too, not just the ops.** `put_page`'s
facts backstop would otherwise extract entities from the page body and
write fact rows (and a `## Facts` fence on git-backed sources) onto
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9cd8666821..f4a908aebd 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -446,6 +446,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.176.0', text: '`gbrain sources writer activate` no longer refuses `writer_registration_required` for a source that has a checkout path but no canonical owner when the brain\'s `sync.write_through` is `false` (#6449): `writer status` already reported that source `database_only`, and activation now agrees, listing it under `database_only_sources` and leaving it unbound. Page writes to it stay database-only (`disabled_by_config`), and turning `sync.write_through` back on does not claim it automatically on a PGLite brain (activation records the listed sources in `persistence.database_only_sources`; deactivation clears it): the next write refuses `owner_unavailable` with `detail: unbound_source` and the `gbrain sources writer claim` to run (or publishes database-only under `persistence.unbound_write=database_only`), the same as on Postgres. With `sync.write_through` on, the activation refusal and the `owner_unavailable` that `gbrain sync` gives such a source now name the claim (preview with `--dry-run`) instead of a generic inspection hint.' },
// Fix wave 15 G2 (GBRA-79, #5808); provisional merge-slot stamp.
{ since: '0.60.176.0', text: 'On a managed canonical worktree, `gbrain sources writer git-durability <source> --enable` (and `--pat-file`) now rewrites the durability block between the gbrain markers in `AGENTS.md`/`RESOLVER.md` to a managed variant (#5808). The block `sources harden` wrote before activation told agents to run the commit-and-push helper after every write and to pull --rebase before writing, both of which route around the persistence owner; the managed variant says page writes go through gbrain, files that are not pages are committed with plain git and ride the owner\'s next push, and the checkout is never pulled, rebased or reset. The rewrite is idempotent, changes nothing outside the markers and is not committed: the file is left for the operator to commit. The preview (`--dry-run`) lists it as `agents`.' },
+ // Fix wave 15 G2 (GBRA-79, #5913); provisional merge-slot stamp.
+ { since: '0.60.176.0', text: 'A slug-bound OAuth client (a `memory-writer` or `coding-agent` grant with `--bound-slug-prefixes`) can now call `remember` (#5913). The operation was fenced to the one slug it writes (the caller\'s entity, or `memory/unattributed`) but not on the allow-list of fenced write operations, so dispatch denied it before the fence ran and a bound grant could not remember anything. A save against an entity under the prefixes commits; one against an entity outside them, or with no entity, is refused `scope_denied` by the slug fence with nothing saved; `replaces` naming a fact outside the prefixes answers exactly like an id that does not exist. `forget` and `forget_fact` stay denied for bound clients: a withdrawal reaches pages the fenced slug does not name. New bound grants list `remember`; an existing grant keeps its operation snapshot until `gbrain auth rescope` (doctor `grant_new_ops_available` names it).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index b4adc3d0dc..700ff873de 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -9,6 +9,7 @@ import { interleaveFusion } from '../search/fusion-lists.ts';
import { readSupersessionThreshold } from './supersession-threshold.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
import { pageNotVisibleError } from '../persistence/page-visibility.ts';
+import { slugUnderBoundPrefixes } from '../ops/context.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
@@ -121,7 +122,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
* duplicate. `lock` takes the target row lock inside the publishing transaction.
*/
export async function decideReplacement(engine: BrainEngine, sourceId: string, input: SingleFactIntent, targetId: number,
- opts: { pageSlug: string; remote: boolean; lock?: boolean; excludePrivate?: boolean }): Promise<FactDecision> {
+ opts: { pageSlug: string; remote: boolean; lock?: boolean; excludePrivate?: boolean; slugPrefixes?: string[] | null }): Promise<FactDecision> {
const notFound = () => verbError('not_found', `No fact with id "${targetId}" to replace.`,
'Pass the fact_id of an active fact from recall (facts[].fact_id) about the same entity, or omit replaces to save a new fact.');
const [target] = await engine.executeRaw<FactCandidate & { withdrawn: boolean }>(`SELECT f.*,
@@ -131,6 +132,8 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i
FROM facts f WHERE f.id=$1 AND f.source_id=$2${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('f')}` : ''}${opts.lock ? ' FOR UPDATE OF f' : ''}`, [targetId, sourceId]);
if (!target || (opts.remote && target.visibility !== 'world')) throw notFound();
if (target.visibility !== input.visibility) throw notFound();
+ // #5913 [R2]: a slug-bound writer learns nothing about a fact outside its prefixes; the answer is the missing-id one.
+ if (opts.slugPrefixes && [target.entity_slug, target.source_markdown_slug].some(slug => slug && !slugUnderBoundPrefixes(opts.slugPrefixes!, slug))) throw notFound();
const candidate: FactCandidate = { ...target, id: Number(target.id) };
if (target.withdrawn) {
throw verbError('invalid_params', `target_withdrawn: fact #${targetId} was forgotten, so it cannot be replaced.`,
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index 240d337989..1aa9ad8624 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -476,6 +476,14 @@ export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set([
'get_write_request', 'list_write_requests', 'cancel_write_request',
'takes_add', 'takes_update', 'takes_resolve', 'takes_supersede', 'takes_remove',
'put_skill', 'delete_skill',
+ // #5913: remember fences the one slug it writes (the caller's entity, or
+ // memory/unattributed) in planRememberTarget (persistence/memory-mutations.ts)
+ // before admission, so an inferred or unattributed target outside the
+ // prefixes is refused, and `replaces` is confined to the same entity and
+ // page (facts/single-prepare.ts decideReplacement). forget/forget_fact stay
+ // off the list: a withdrawal's write set (withdrawal-discovery.ts) reaches
+ // pages the fenced slug does not name, so they wait for a confined closure.
+ 'remember',
]);
/**
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 0a25221007..32b4df4274 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -170,7 +170,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
if (p.replaces !== undefined && p.replaces !== null) {
// Fail fast on an invalid target; the coordinator re-checks it under the row lock before publishing.
await decideReplacement(ctx.engine, sourceId, factIntent, Number(p.replaces),
- { pageSlug: slug, remote: ctx.remote !== false, excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) });
+ { pageSlug: slug, remote: ctx.remote !== false, excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote), slugPrefixes: authority.slugPrefixes });
}
await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent, { excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) });
const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index b223b08a8c..d5f19d5548 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -95,7 +95,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
// `replaces`: the caller names the fact this one replaces (checked; the cosine rule does not apply).
const replaces = p.replaces !== undefined && p.replaces !== null ? Number(p.replaces) : null;
const replace = (e: BrainEngine, target: number, lock: boolean) =>
- decideReplacement(e, row.source_id, input, target, { pageSlug: row.slug, remote: row.authority.remote === true, lock, excludePrivate });
+ decideReplacement(e, row.source_id, input, target, { pageSlug: row.slug, remote: row.authority.remote === true, lock, excludePrivate, slugPrefixes: row.authority.slugPrefixes });
const decide = async (e: BrainEngine, lock = false) => {
if (replaces !== null) return replace(e, replaces, lock);
// The same claim saved earlier without an entity is this fact unlinked: linking it supersedes that copy,
diff --git a/test/grant-prefix-remember-5913.test.ts b/test/grant-prefix-remember-5913.test.ts
new file mode 100644
index 0000000000..5163f5b7b5
--- /dev/null
+++ b/test/grant-prefix-remember-5913.test.ts
@@ -0,0 +1,116 @@
+/**
+ * #5913: `remember` was fenced inside the persistence layer (planRememberTarget
+ * fences the entity slug or `memory/unattributed` before admission) but never
+ * added to `CLIENT_FENCED_WRITE_OPS`, so the fail-closed dispatch gate denied
+ * it to every slug-bound client before the fence could run, and a bound
+ * `memory-writer` / `coding-agent` grant (which requires prefixes) could not
+ * remember anything. The op is allow-listed now; `forget`/`forget_fact` are
+ * not ([UC6]: a withdrawal's write set reaches pages the fenced slug does not
+ * name, so they wait for a confined closure).
+ *
+ * [R2] `replaces` is confined to the caller's entity and page, and a bound
+ * client learns nothing about a fact outside its prefixes through it: the
+ * refusal is byte-identical to the one for an id that does not exist.
+ */
+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 { CLIENT_FENCED_WRITE_OPS, opAllowedForBoundClient, operations, type AuthInfo } from '../src/core/operations.ts';
+import { resolveGrantProfile } from '../src/core/grants/profiles.ts';
+
+const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+const parsed = (result: { content: Array<{ text: string }> }): Record<string, any> => JSON.parse(result.content[0]!.text);
+const auth: AuthInfo = { token: 't', clientId: 'bound-example', principal: { kind: 'oauth_client', id: 'bound-example' },
+ scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes/'] } as AuthInfo;
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+describe('grant profiles and the bound-client allow-list (#5913)', () => {
+ test('a prefix-bound memory-writer or coding-agent grant lists remember and not forget/forget_fact', () => {
+ for (const profile of ['memory-writer', 'coding-agent'] as const) {
+ const grant = resolveGrantProfile({ profile, sourceId: 'default', boundSlugPrefixes: ['notes/'] });
+ expect(grant.allowedOperations).toContain('remember');
+ expect(grant.allowedOperations).not.toContain('forget');
+ expect(grant.allowedOperations).not.toContain('forget_fact');
+ expect(grant.allowedOperations).toContain('recall');
+ }
+ });
+
+ test('the dispatch predicate and the catalog filter agree: remember allowed, withdrawal denied, degraded fence denies everything', () => {
+ expect(CLIENT_FENCED_WRITE_OPS.has('remember')).toBe(true);
+ expect(CLIENT_FENCED_WRITE_OPS.has('forget')).toBe(false);
+ expect(CLIENT_FENCED_WRITE_OPS.has('forget_fact')).toBe(false);
+ const bound = { boundSlugPrefixes: ['notes/'] };
+ expect(opAllowedForBoundClient(bound, op('remember'))).toBe(true);
+ expect(opAllowedForBoundClient(bound, op('forget'))).toBe(false);
+ expect(opAllowedForBoundClient(bound, op('forget_fact'))).toBe(false);
+ expect(opAllowedForBoundClient({ ...bound, fenceProjectionDegraded: true }, op('remember'))).toBe(false);
+ expect(opAllowedForBoundClient({ boundSlugPrefixes: [] }, op('remember'))).toBe(true);
+ });
+});
+
+describe('a notes/-bound client remembering through dispatch (#5913)', () => {
+ let engine: PGLiteEngine;
+ let outsideFactId: string;
+ const put = (slug: string, type: string) => dispatchToolCall(engine, 'put_page',
+ { slug, content: `---\ntype: ${type}\ntitle: ${slug}\n---\n# ${slug}\n\nBody.\n`, request_id: randomUUID() }, { ...STDIO });
+ const remember = (params: Record<string, unknown>, bound = true) =>
+ dispatchToolCall(engine, 'remember', { provenance: 'test', request_id: randomUUID(), ...params }, bound ? { ...STDIO, auth } : { ...STDIO }).then(parsed);
+ const facts = (slug: string) => engine.executeRaw<{ fact: string }>("SELECT fact FROM facts WHERE source_id='default' AND entity_slug=$1 AND expired_at IS NULL ORDER BY id", [slug]);
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.setConfig('schema_pack', 'gbrain-base');
+ await engine.setConfig('sync.write_through', 'false');
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,scope,source_id,bound_slug_prefixes)
+ VALUES ('bound-example','Synthetic bound client','read write','default',$1::text[])`, [['notes/']]);
+ expect(parsed(await put('notes/project-x', 'note')).state).toBe('committed');
+ expect(parsed(await put('people/someone-example', 'person')).state).toBe('committed');
+ const outside = await remember({ fact: 'Someone prefers tea over coffee.', entity: 'people/someone-example' }, false);
+ expect(outside.status).toBe('inserted');
+ outsideFactId = String(outside.id);
+ }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ test('remember inside the prefix commits; outside it and unattributed are refused by the slug fence with nothing saved', async () => {
+ const inside = await remember({ fact: 'Project X ships on Friday.', entity: 'notes/project-x' });
+ expect(inside.error).toBeUndefined();
+ expect(inside).toMatchObject({ status: 'inserted', entity_slug: 'notes/project-x' });
+ expect((await facts('notes/project-x')).map(row => row.fact)).toEqual(['Project X ships on Friday.']);
+
+ const outside = await remember({ fact: 'Someone likes hiking.', entity: 'people/someone-example' });
+ expect(outside.error).toBe('scope_denied');
+ expect(outside.message).toContain("remember: slug 'people/someone-example' is not under any of client bound-example's bound_slug_prefixes (notes/)");
+ expect((await facts('people/someone-example')).map(row => row.fact)).toEqual(['Someone prefers tea over coffee.']);
+
+ const unattributed = await remember({ fact: 'A stray thought.' });
+ expect(unattributed.error).toBe('scope_denied');
+ expect(unattributed.message).toContain("slug 'memory/unattributed' is not under");
+ expect(await engine.executeRaw("SELECT id FROM facts WHERE source_id='default' AND entity_slug IS NULL")).toEqual([]);
+ });
+
+ test('[R2] replaces naming a fact outside the prefixes answers exactly like a missing id, and the fact stays active', async () => {
+ const missing = await remember({ fact: 'Someone prefers coffee over tea.', entity: 'notes/project-x', replaces: '999999' });
+ expect(missing.error).toBe('not_found');
+ const probed = await remember({ fact: 'Someone prefers coffee over tea.', entity: 'notes/project-x', replaces: outsideFactId });
+ const envelope = ({ error, code, message, suggestion }: Record<string, unknown>) =>
+ ({ error, code, message: String(message).replace(/"\d+"/, '"<id>"'), suggestion });
+ expect(envelope(probed)).toEqual(envelope(missing));
+ expect(JSON.stringify(probed)).not.toContain('people/someone-example');
+ expect((await facts('people/someone-example')).map(row => row.fact)).toEqual(['Someone prefers tea over coffee.']);
+ expect((await facts('notes/project-x')).map(row => row.fact)).toEqual(['Project X ships on Friday.']);
+ // An unbound caller keeps the explanatory mismatch.
+ const unbound = await remember({ fact: 'Someone prefers coffee over tea.', entity: 'notes/project-x', replaces: outsideFactId }, false);
+ expect(unbound.error).toBe('invalid_params');
+ expect(unbound.message).toContain('replaces_entity_mismatch');
+ });
+
+ test('forget and forget_fact stay denied at dispatch for the bound client', async () => {
+ for (const [name, params] of [['forget', { id: '2' }], ['forget_fact', { id: 2 }]] as const) {
+ const denied = parsed(await dispatchToolCall(engine, name, { ...params, request_id: randomUUID() }, { ...STDIO, auth }));
+ expect(denied.error).toBe('permission_denied');
+ expect(denied.message).toContain(`${name} is not available to slug-bound clients`);
+ }
+ expect((await facts('notes/project-x')).map(row => row.fact)).toEqual(['Project X ships on Friday.']);
+ });
+});