Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
QM scope writes: grant guards import attest-sources lazily (snapshot closure), default-only grants skip the scope query, shorter source_id description (GST-1113)
garrytand29c62a25813
diff --git a/docs/contracts/qm-memory-provider/v2.json b/docs/contracts/qm-memory-provider/v2.jsonindex 4d72a1bc87..8a176ba97e 100644--- a/docs/contracts/qm-memory-provider/v2.json+++ b/docs/contracts/qm-memory-provider/v2.json@@ -126,7 +126,7 @@},"source_id": {"type": "string",- "description": "Save on this scope source's shared page (memory/scope), read by everyone who reads that source; it must be one of the credential's scope sources. Omit to save for the person alone."+ "description": "One of this credential's scope sources: save on its shared memory/scope page."}},"required": [diff --git a/src/core/access/attest-sources.ts b/src/core/access/attest-sources.tsindex c937db2c32..933de5017a 100644--- a/src/core/access/attest-sources.ts+++ b/src/core/access/attest-sources.ts@@ -104,7 +104,8 @@ async function credentialSources(sql: SqlQuery): Promise<CredentialSources[]> {/*** Refuses a grant whose read sources name a marked scope source this credential does not list. `self` is the credential- * being written (null for one not inserted yet), whose stored attest_sources are honoured.+ * being written (null for one not inserted yet), whose stored attest_sources are honoured. `default` is never a scope+ * source (applyAttestSources refuses it), so a default-only grant reads nothing.*/export async function assertScopeSourceGrant(db: Db, self: CredentialRef | null, reads: readonly string[], opts: { privatePages?: boolean } = {}): Promise<void> {const sql = sqlOf(db);@@ -112,8 +113,9 @@ export async function assertScopeSourceGrant(db: Db, self: CredentialRef | null,throw new GrantError('invalid_grant', 'This credential lists scope sources (--attest-sources), so it cannot hold the private-pages grant; nothing changed. '+ 'A scope credential reads only shared memory: use a separate credential for private pages.');}- if (!reads.length) return;- const marked = await markedScopeSources(sql, reads, true);+ const candidates = reads.filter(s => s !== 'default');+ if (!candidates.length) return;+ const marked = await markedScopeSources(sql, candidates, true);if (!marked.size) return;const own = self ? (await credentialSources(sql)).find(c => same(c.ref, self))?.attest ?? [] : [];const reserved = [...marked].filter(s => !own.includes(s)).sort();diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.tsindex 37f02e79ba..c980503a8b 100644--- a/src/core/grants/legacy-token.ts+++ b/src/core/grants/legacy-token.ts@@ -37,7 +37,6 @@ import {tokenGrantFromPermissions, validatePrincipalGrant, TOKEN_GRANT_COLUMNS, type LegacyGrantAxis, type PrincipalGrant, type PrivatePagesGrant,} from './model.ts';import { parsePrivatePagesFlag } from './cli.ts';-import { assertScopeSourceGrant, sourcesOf } from '../access/attest-sources.ts';export type { LegacyGrantAxis } from './model.ts';@@ -199,6 +198,7 @@ function schemaError(error: unknown): unknown {/** Write the unified columns and the `permissions` mirror in one UPDATE; returns the new revision. */async function writeTokenGrant(tx: BrainEngine, row: Record<string, unknown>, grant: TokenGrantAxes, scopes?: string[]): Promise<number> {+ const { assertScopeSourceGrant, sourcesOf } = await import('../access/attest-sources.ts');const before = sourcesOf(grantFromTokenRow(row).sources).reads;await assertScopeSourceGrant(tx, { kind: 'token', id: String(row.id) }, sourcesOf(grant.sources).reads.filter(s => !before.includes(s)));const [written] = await executeRawJsonb<{ grant_revision: number }>(@@ -307,7 +307,7 @@ async function rescopeInTransaction(tx: BrainEngine, args: RescopeTokenArgs): Prconst write = !args.dryRun && (edits || Boolean(args.adopt));const revision = write ? await writeTokenGrant(tx, row, next, args.scopes) : current.revision;if (write && privatePages !== current.privatePages) {- await assertScopeSourceGrant(tx, { kind: 'token', id }, [], { privatePages: privatePages === 'granted_sources' });+ await (await import('../access/attest-sources.ts')).assertScopeSourceGrant(tx, { kind: 'token', id }, [], { privatePages: privatePages === 'granted_sources' });await tx.executeRaw('UPDATE access_tokens SET private_pages = $2 WHERE id = $1::uuid', [id, privatePages]);}return {diff --git a/src/core/grants/service.ts b/src/core/grants/service.tsindex 53fc5f4654..8b423696b8 100644--- a/src/core/grants/service.ts+++ b/src/core/grants/service.ts@@ -2,7 +2,6 @@ import type { BrainEngine } from '../engine.ts';import { sqlQueryForEngine, type SqlQuery } from '../sql-query.ts';import { GrantError, grantFromRow, normalizeGrantBrain, validateClientGrant, type ClientGrant, type GrantPatch, type GrantValidationContext } from './model.ts';import { catalogProvenance, grantCatalog, type CatalogProvenance } from './profiles.ts';-import { assertScopeSourceGrant, clientGrantReads } from '../access/attest-sources.ts';export type GrantDatabase = BrainEngine | SqlQuery;const query = (db: GrantDatabase): SqlQuery => typeof db === 'function' ? db : sqlQueryForEngine(db);@@ -78,6 +77,7 @@ export async function readClientCatalogProvenance(db: GrantDatabase, clientId: s/** Called after validation. Never exposes the credential in the audit document. */export async function insertClientGrant(sql: SqlQuery, grant: ClientGrant, metadata: GrantClientMetadata, actor = 'operator'): Promise<void> {+ const { assertScopeSourceGrant, clientGrantReads } = await import('../access/attest-sources.ts');await assertScopeSourceGrant(sql, null, clientGrantReads(grant));await sql`WITH created AS (@@ -192,6 +192,7 @@ export async function recordFirstConsentInTransaction(db: GrantDatabase, clientI/** One UPDATE+audit statement: SQL-only provider callers get atomicity too. */export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: ClientGrant, actor: string, action: string): Promise<void> {+ const { assertScopeSourceGrant, clientGrantReads } = await import('../access/attest-sources.ts');const widened = clientGrantReads(after).filter(s => !clientGrantReads(before).includes(s));await assertScopeSourceGrant(sql, { kind: 'client', id: before.clientId }, widened, { privatePages: after.privatePages === 'granted_sources' && before.privatePages !== 'granted_sources' });const result = await sql`diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 65b119c75f..5d27818d79 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -6256,7 +6256,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"source_id": {"type": "string",- "description": "Save on this scope source's shared page (memory/scope), read by everyone who reads that source; it must be one of the credential's scope sources. Omit to save for the person alone."+ "description": "One of this credential's scope sources: save on its shared memory/scope page."}},"scope": "write",diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex 9fdcd59f31..c08a2bb48a 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -244,7 +244,7 @@ const memory_write: Operation = {},idempotency_key: { type: 'string', required: true, description: '1-128 visible ASCII characters; the same key replays this write.' },[ACTOR_ARGUMENT]: actorParam,- source_id: { type: 'string', description: `Save on this scope source's shared page (${SCOPE_PAGE_SLUG}), read by everyone who reads that source; it must be one of the credential's scope sources. Omit to save for the person alone.` },+ source_id: { type: 'string', description: `One of this credential's scope sources: save on its shared ${SCOPE_PAGE_SLUG} page.` },},scope: 'write',annotations: { title: 'memory_write (QM memory write)', idempotentHint: true },diff --git a/src/core/snapshot-schema-inputs.ts b/src/core/snapshot-schema-inputs.tsindex 6fce71bd82..ad1756e814 100644--- a/src/core/snapshot-schema-inputs.ts+++ b/src/core/snapshot-schema-inputs.ts@@ -41,6 +41,7 @@ export const SNAPSHOT_SCHEMA_LEAVES: readonly string[] = [/** Dynamic imports inside the closure that never run during schema init or migrations. */export const SNAPSHOT_DYNAMIC_IMPORTS_NOT_HASHED: Readonly<Record<string, string>> = {'operations.ts': 'verbs.ts request-time verb handlers',+ 'access/attest-sources.ts': 'grants/service.ts, grants/legacy-token.ts and token-mint.ts check grant writes against QM scope sources at request time (GST-1113)','ops/context.ts': 'verbs.ts request-time verb handlers (synthesize source scope, #7147)','ops/facts.ts': 'verbs.ts request-time verb handlers (remember TTL parsing, #7147)','ai/gateway.ts': 'search/projection-statistics.ts embed-drain refresh reads the configured embedding model at request time (#7083)',diff --git a/src/core/token-mint.ts b/src/core/token-mint.tsindex 23e98c806c..c5e891f322 100644--- a/src/core/token-mint.ts+++ b/src/core/token-mint.ts@@ -20,7 +20,6 @@ import type { BrainEngine } from './engine.ts';import { ALLOWED_SCOPES_LIST, assertAllowedScopes } from './scope.ts';import type { SqlQuery } from './sql-query.ts';import { opError } from './ops/contract.ts';-import { assertScopeSourceGrant, sourcesOf } from './access/attest-sources.ts';import { generateToken, hashToken, isUndefinedColumnError } from './utils.ts';import { permissionsMirror, tokenGrantColumnValues, tokenGrantFromPermissions, TOKEN_GRANT_COLUMNS, type GrantSources, type PrincipalGrant } from './grants/model.ts';@@ -104,6 +103,7 @@ export async function insertUnifiedToken(engine: BrainEngine, opts: {grant: Pick<PrincipalGrant, 'sources' | 'allowedOperations' | 'takesHolders'>;}): Promise<Array<{ id: string }>> {const scopes = opts.scopes === undefined ? null : `{${opts.scopes.join(',')}}`;+ const { assertScopeSourceGrant, sourcesOf } = await import('./access/attest-sources.ts');await assertScopeSourceGrant(engine, null, sourcesOf(opts.grant.sources).reads);try {return await engine.executeRaw<{ id: string }>(diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 3f18526025..ab8e032971 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 269780,- "stdoutSha256": "cda3d9e0ad1f81977a5a7dfacb8b786702ba2be1f5c278ab7d4ba09e36c6e09d",+ "stdoutBytes": 269677,+ "stdoutSha256": "4ce1f054ec59831dd8a3da42f2a45dca03771480f6ef3e03a649a31660e206a5","toolNames": ["remember","entity",@@ -7220,7 +7220,7 @@"type": "string"},"source_id": {- "description": "Save on this scope source's shared page (memory/scope), read by everyone who reads that source; it must be one of the credential's scope sources. Omit to save for the person alone.",+ "description": "One of this credential's scope sources: save on its shared memory/scope page.","type": "string"}},