Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes (memory_write preflight refuses a forgotten claim before saving any fact; an attested write is granted by the public operation, so a memory-only grant writes)
garrytana878a952543e
diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex 0e40defc08..f277372ea7 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -238,6 +238,15 @@ const memory_write: Operation = {throw e;}}+ const { assertFactNotWithdrawn } = await import('../facts/single-prepare.ts');+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);+ for (const [index, item] of parsed.entries()) {+ const intent = { fact: item.fact as string, kind: (item.kind ?? 'fact') as never, visibility: 'private' as const, entity_slug: null, page_slug: memberPageSlug(actor.member) };+ try { await assertFactNotWithdrawn(ctx.engine, ctx.sourceId ?? 'default', intent, { excludePrivate }); } catch (e) {+ if (e instanceof OperationError) e.message = `facts[${index}]: ${e.message} Nothing was saved.`;+ throw e;+ }+ }if (ctx.dryRun) return { dry_run: true, action: 'memory_write', facts: items.length };const saved: Array<{ request_id: string; fact_id?: string; pending?: true }> = [];for (const [index, item] of items.entries()) {diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex b7e128b073..25a04081cf 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -145,7 +145,9 @@ export async function slugDisclosable(engine: SqlEngine, a: WriteAuthority, slugexport async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operation: string, slug: string, lock = false): Promise<void> {if (a.version !== 1 || !a.principal || !a.sourceId || !a.sourceIncarnation) deny('Missing durable write authority.');assertSkillWriteScopes(a.scopes, operation, a.remote);- if (!hasScope(a.scopes, a.delegated ? 'agent' : 'write') || !operationAllowed(a.operations, operation) || !prefixAllowed(a.slugPrefixes, slug)) deny('The operation exceeds its original accepted grant.');+ // GST-359: an attested write is granted by the public operation the person's system called (memory_write runs remember).+ const granted = a.actingFor && !Array.isArray(a.actingFor) && a.attestedOp ? a.attestedOp : operation;+ if (!hasScope(a.scopes, a.delegated ? 'agent' : 'write') || !operationAllowed(a.operations, granted) || !prefixAllowed(a.slugPrefixes, slug)) deny('The operation exceeds its original accepted grant.');if ((a.delegated || a.restrictedNamespace) && (!a.delegatedPrefixes?.length || !matchesSlugAllowList(slug, a.delegatedPrefixes))) deny('The target exceeds the accepted delegated namespace.');if (a.actingFor && !Array.isArray(a.actingFor)) {const actor = parseStoredActor(a.actingFor);@@ -164,7 +166,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaif (a.delegated) {if (!strings(row.bound_tools) || !row.bound_tools.some(t => t.replace(/^(?:brain_|mcp__gbrain__)/, '') === operation)) deny('The delegated tool was removed from the current grant.');if (!matchesSlugAllowList(slug, liveDelegation(row, a.delegatedJobId))) deny('The delegated namespace was narrowed.');- } else if (!operationAllowed(row.allowed_operations, operation) ||+ } else if (!operationAllowed(row.allowed_operations, granted) ||(row.bound_slug_prefixes != null && (!strings(row.bound_slug_prefixes) || !prefixAllowed(row.bound_slug_prefixes, slug)))) deny('The current operation or slug grant excludes this write.');return;}@@ -175,7 +177,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaif (grant.permissionsMalformed) deny('The current legacy grant is malformed.');assertSkillWriteScopes(normalizeTokenScopes(row.scopes) ?? [], operation, a.remote);const liveOperations = grant.allowedOperations;- if (!operationAllowed(liveOperations, operation) || skillWrite(operation) && !liveOperations?.includes(operation)) deny('The current legacy operation grant excludes this write.');+ if (!operationAllowed(liveOperations, granted) || skillWrite(operation) && !liveOperations?.includes(operation)) deny('The current legacy operation grant excludes this write.');if (!hasScope(grant.scopes, 'write') || authSourcesFromGrant(grant).sourceId !== a.sourceId) deny('The current token no longer permits this source write.');return;}diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.tsindex 5da32e586a..61556abdb5 100644--- a/test/qm-memory-tools.test.ts+++ b/test/qm-memory-tools.test.ts@@ -418,6 +418,19 @@ for (const kind of testBackends()) {expect(line).toMatch(/^- Harbor rules keep the ledger canaryfence \(\d{4}-\d{2}-\d{2}; fact\)$/);}, 60_000);+ test('a QM client whose operation grant names only the memory tools writes and reads back its receipts', async () => {+ const c = await provider().registerClientManual('d-pinned-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm' });+ await engine.executeRaw('UPDATE oauth_clients SET allowed_operations = $2::text[] WHERE client_id = $1', [c.clientId, ['get_write_request', 'memory_recall', 'memory_write']]);+ tokens.pinned = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;+ const pinned: Who = { token: 'pinned', actor: ALICE_ID };+ const out = await write(pinned, [{ fact: 'Alice prefers the north dock canarypinned', provenance: 'turn 30' }]);+ expect({ isError: out.isError, status: out.structured?.status }).toEqual({ isError: false, status: 'committed' });+ const receipt = await call(pinned, 'get_write_request', { request_id: out.structured!.request_id });+ expect(receipt.isError).toBe(false);+ expect((await recall(pinned, 'north dock')).text).toContain('canarypinned');+ }, 60_000);+test('forget and forget_fact withdraw the person\'s own member-page fact there alone, never another member\'s or a world fact', async () => {const claim = 'Shared standup moved to Thursdays canaryforget';const a = await write(alice, [{ fact: claim, provenance: 'turn 11' }]);@@ -444,6 +457,12 @@ for (const kind of testBackends()) {const again = await write(alice, [{ fact: claim, provenance: 'turn 12' }]);expect(again.isError).toBe(true);expect(again.text).toContain('fact_withdrawn');+ const batchKey = randomUUID();+ const mixed = await write(alice, [{ fact: 'Alice books the harbor room canarymixedfirst', provenance: 'turn 12' }, { fact: claim, provenance: 'turn 12' }], batchKey);+ expect({ isError: mixed.isError, code: mixed.json.code }).toEqual({ isError: true, code: 'invalid_params' });+ expect(await factRows('canarymixedfirst')).toHaveLength(0);+ const fixedBatch = await write(alice, [{ fact: 'Alice books the harbor room canarymixedfirst', provenance: 'turn 12' }], batchKey);+ expect(fixedBatch.structured?.status).toBe('committed');const carolCopy = await write(carol, [{ fact: claim, provenance: 'turn 12' }]);expect(carolCopy.structured!.status).toBe('committed');const second = await write(alice, [{ fact: 'Alice drafts the harbor memo canaryforgetfact', provenance: 'turn 13' }]);