Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
QM wave review fixes: agent jobs and all_sources honor the scope read, proposals keep their credential and revision
garrytanf998aaebfaf3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e2ba9df0e4..50419cc804 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ identifiers and attribution are available in the pre-removal Git revision| Area | Before | Now ||---|---|---|| Direct page writes from QM | an attested call could run `add_timeline_entry`, `add_link`, `put_page` and `edit_page` | refused (`actor_not_attested`, reason `op_not_attested`); `--attest-ops` refuses a list that names one, and a queued attested write of one fails when it publishes |-| Reads that name sources | only `memory_recall` read named sources as their audience | `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` and `query` do too: restricted pages and member pages read as missing, `__all__`/`all_sources` beside a named source is refused |+| Reads that name sources | only `memory_recall` read named sources as their audience | `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` and `query` do too: restricted pages and member pages read as missing, and `__all__` or `all_sources` is refused; an agent job submitted for the person reads the same way, and `context_pack` naming sources is refused on a client that reads them as the scope || How a client reads named sources | always as the audience | `gbrain auth rescope --attest-read person\|scope\|none`; `scope` also refuses any call that names no person; `gbrain doctor` warns (`attest_read_shared_scope`) when a person client reads a source a scope client reads || A person's own DM sources | every attested caller with the grant read every DM source in it | `gbrain access member source add\|remove\|list` binds a source to its member; an attested call reads its grant minus other members' personal sources, and a scope read reads no personal source at all || QM contract | v1 and v2 | v3 (`docs/contracts/qm-memory-provider/v3.json`) adds the person's own-DM tools with frozen result shapes, `structuredContent` on attested personal reads (re-measured against the result cap), an `arm` (`own`/`ranked`) on each `memory_recall` fact, and an opt-in `memory_recall` `query_keep` (`head`/`tail`) that adds `query_truncated`; v1 and v2 are byte-identical |@@ -30,10 +30,10 @@ identifiers and attribution are available in the pre-removal Git revision### Itemized changes- `src/core/access/actor-model.ts`: the four page writes join `ACTOR_DEFERRED_OPS`; `docs/contracts/qm-memory-provider/v2.json` lists them in `deferred_ops` (a published-contract amendment).-- `src/core/access/scope-read.ts` (new), `src/mcp/dispatch.ts`: `SCOPE_READ_ACCESS`, `SCOPE_READ_OPS`, `attestedReadMode`; `attest_read` on `access_tokens` and `oauth_clients` (migration v297).+- `src/core/access/scope-read.ts` (new), `src/mcp/dispatch.ts`: `SCOPE_READ_ACCESS`, `SCOPE_READ_OPS`, `attestedReadMode`, also applied to agent job tool calls (`src/core/minions/tools/brain-allowlist.ts`); `attest_read` on `access_tokens` and `oauth_clients` (migration v297).- `src/core/access/member-sources.ts` (new): `access_member_sources` (migration v298) and `attestedReadScope`, also applied to agent jobs submitted for an attested actor.- `src/core/ops/qm-memory.ts`, `scripts/build-qm-memory-contract.ts`: contract v3, `qmMemoryToolResult` for personal tools, recall arms, `query_keep`, and `boundRecallChars` trimming `facts_groups` and `entity_unspecified` to the facts it delivers.-- `src/core/persistence/memory-proposals.ts` (new), `src/commands/memory-proposals.ts` (new): `memory_proposals` (migration v299), owner review, TTL and retention; a proposed link re-checks its target when it publishes.+- `src/core/persistence/memory-proposals.ts` (new), `src/commands/memory-proposals.ts` (new): `memory_proposals` (migration v299), owner review, TTL and retention; a proposal's request id is scoped to its credential and member, and a proposed link re-checks its target and the approved page revision when it publishes.- `src/core/access/members.ts`, `src/core/access/actor.ts`, `src/commands/access.ts`, `src/commands/serve-http-access.ts`, `src/commands/mcp-admin.ts`: member email (migration v300), `linkMemberByEmail`, and the owner HTTP routes with an `access_admin` request-log row per applied change.- Inventories: `access_member_sources`, `memory_proposals` and the email column join the deletion and graduation inventories.- Docs: `docs/guides/qm.md` (reads that name sources, each person's own sources, proposed writes), `docs/mcp/ADMIN.md`, `docs/architecture/key-files/access.md`.diff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex 6733c5b521..1263362756 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -60,9 +60,11 @@ An attested call to `get_page`, `entity`, `whois`, `get_backlinks`, `get_timelinor `source_ids` reads those sources as their audience, never as the person: theperson's restricted pages and their member page read as missing, a source outsidethe grant is refused, and `__all__` or `all_sources` is refused (`invalid_params`).-`volunteer_context` refuses `stats: true` there. List the ops a client needs with-`--attest-ops`. `context_pack` is not a scope read yet, so keep it off a client that-serves shared turns.+`volunteer_context` refuses `stats: true` there. An agent job submitted for the+person reads the same way. List the ops a client needs with `--attest-ops`.+`context_pack` is not a scope read yet: on a client that reads named sources as the+scope it is refused (`invalid_params`) when it names `source_id`, `source_ids`,+`all_sources` or `entity_refs`, so keep it off a client that serves shared turns.Set how each client reads named sources with `--attest-read`:@@ -114,7 +116,7 @@ the person it serves. Nothing is written until the brain owner says yes. Grant i`link_type?`, `context?`, `valid_from?` and `valid_until?`. A field of the other kind isrefused (`invalid_params`, reason `proposal_kind_field`). The person must be able to read thetarget (and a link's `to` page). The answer is `{status: "awaiting_owner", request_id, kind,- target, expires_at}`; the same key from the same person returns that proposal's current+ target, expires_at}`; the same key from the same person and client returns that proposal's currentstatus, and the same key with other fields is `idempotency_conflict`.- `get_write_request {request_id}` reads the proposal: `awaiting_owner`, then `approved`(with the write's own receipt), `denied` (with the owner's reason), `expired`, `cancelled`,diff --git a/src/core/access/scope-read.ts b/src/core/access/scope-read.tsindex 0d5eeb5ac2..a339aad616 100644--- a/src/core/access/scope-read.ts+++ b/src/core/access/scope-read.ts@@ -17,7 +17,7 @@ export const SCOPE_READ_ACCESS: Partial<CallerAccess> = {hidePrivate: true, applyRemoteReadPolicy: false, restricted: true, remotePolicy: { privacyRelaxed: false, restricted: true },};-/** GST-1158 E1: the reads an attested call that names sources runs as the scope. context_pack stays out until it is confined to the named sources. */+/** GST-1158 E1: the reads an attested call that names sources runs as the scope. context_pack stays out until it is confined to the named sources, so it is refused when it names sources on a scope credential. */export const SCOPE_READ_OPS: ReadonlySet<string> = new Set(['memory_recall', 'get_page', 'entity', 'whois', 'get_backlinks', 'get_timeline', 'find_experts', 'volunteer_context', 'query',]);@@ -37,7 +37,7 @@ export function withReadMode<T>(mode: ReadMode | null, fn: () => T): T {function namesSources(params: Record<string, unknown> | undefined): boolean {const id = params?.source_id;const ids = params?.source_ids;- return (id !== undefined && id !== null && id !== '')+ return params?.all_sources === true || (id !== undefined && id !== null && id !== '')|| (Array.isArray(ids) ? ids.length > 0 : typeof ids === 'string' ? ids.trim() !== '' : ids !== undefined && ids !== null);}@@ -46,6 +46,7 @@ function namesSources(params: Record<string, unknown> | undefined): boolean {* sources, else null. A scope read that asks for every source (`__all__`, `all_sources`) is refused with invalid_params.*/export function attestedReadMode(op: string, params: Record<string, unknown> | undefined, attestRead: ReadMode | null | undefined): ReadMode | null {+ if (op === 'context_pack' && attestRead !== 'person' && (namesSources(params) || (Array.isArray(params?.entity_refs) && params.entity_refs.length > 0))) throw contextPackScopeRefused();if (!SCOPE_READ_OPS.has(op) || !namesSources(params)) return null;if (attestRead === 'person') return 'person';const ids = params?.source_ids;@@ -53,6 +54,12 @@ export function attestedReadMode(op: string, params: Record<string, unknown> | ureturn 'scope';}+function contextPackScopeRefused(): OperationError {+ return opError('invalid_params', 'context_pack: a call that names sources would read them as the person, and this credential reads named sources as their audience, so it is refused. Nothing was read.',+ 'Leave source_id, source_ids, all_sources and entity_refs out to read as the person, or call query, get_page or entity with source_id for the scope.',+ { why: 'context_pack is not yet confined to the named sources, so it cannot run as a scope read.' });+}+function scopeAllSourcesRefused(op: string): OperationError {return opError('invalid_params', `${op}: a call that names sources reads them as their audience, so '${ALL_SOURCES}' and all_sources are refused. Nothing was read.`,'Name the sources to read in source_id or source_ids, or leave them out to read as the person.',diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex 2e91275c6b..454fa9ae4d 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -35,8 +35,9 @@ import { putPageRejection, rethrowWithCurrentRevision } from './put-page-result.import { BRAIN_TOOL_ALLOWLIST } from './brain-tool-allowlist.ts';import { stagePutPage } from './staged-put-page.ts';import { withCallerAccess } from '../../search/private-visibility.ts';-import { remoteCallerAccess } from '../../access/caller.ts';-import { attestedCallerAccess, storedActorIdentity } from '../../access/actor.ts';+import { folderAccessFor, remoteCallerAccess } from '../../access/caller.ts';+import { attestedCallerAccess, attestRightOf, storedActorIdentity } from '../../access/actor.ts';+import { attestedReadMode, SCOPE_READ_ACCESS, withReadMode } from '../../access/scope-read.ts';import { attestedReadScope } from '../../access/member-sources.ts';import type { AudiencePrincipal } from '../../access/audience.ts';import { currentSubmissionAuthority } from '../submission-authority.ts';@@ -321,9 +322,14 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {// GST-359 C1: a job submitted for an attested actor reads as that member only while actorCoverage still covers it.const agent = submitted?.kind === 'remote_agent' ? submitted : undefined;const actor = agent?.grant.actor;+ // GST-1158 E1: and a job tool call that names sources reads them as the scope, exactly as the same call through MCP dispatch.const output = agent && actor- ? await withCallerAccess(await attestedCallerAccess(ctx.engine, actor, await storedActorIdentity(ctx.engine, agent.principal, actor, op.name)),- async () => run(await attestedReadScope(ctx.engine, opCtx, actor.member, false)))+ ? await (async () => {+ const identity = await storedActorIdentity(ctx.engine, agent.principal, actor, op.name);+ const readMode = attestedReadMode(op.name, params, (await attestRightOf(ctx.engine, { principal: agent.principal }))?.read);+ const access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(ctx.engine, [])).folderCoverage } : await attestedCallerAccess(ctx.engine, actor, identity);+ return withCallerAccess(access, () => withReadMode(readMode, async () => run(await attestedReadScope(ctx.engine, opCtx, actor.member, readMode === 'scope'))));+ })(): opCtx.auth? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, [], undefined, actingFor), run): await run();diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex 6f2baef187..fb24a99967 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -388,7 +388,7 @@ const memory_propose: Operation = {const { requestPrincipalForContext, pageMutationSource } = await import('../persistence/page-mutations.ts');const digest = proposalDigest(sent);const principal = await requestPrincipalForContext(ctx);- const requestId = proposalRequestId(actor.member, p.idempotency_key);+ const requestId = proposalRequestId(principal, actor.member, p.idempotency_key);const replay = (row: { payload_digest: string; state: string; request_id: string; kind: string; slug: string; expires_at: string }) => {if (row.payload_digest !== digest) {throw opError('idempotency_conflict', 'This idempotency_key was used for a different proposal; send a new key.',diff --git a/src/core/persistence/manual-links.ts b/src/core/persistence/manual-links.tsindex 35ae2de480..e1adc04947 100644--- a/src/core/persistence/manual-links.ts+++ b/src/core/persistence/manual-links.ts@@ -46,6 +46,11 @@ export async function prepareManualLinkMutation(engine: BrainEngine, row: WriteRthrow opError('page_not_found', `The link target ${to} was removed or is no longer readable by the person this link was proposed for.`,`Request ${row.request_id} for ${row.slug} in source ${row.source_id} changed nothing; a new proposal is needed if the link is still wanted.`);}+ // A proposed link carries the revision the owner approved against; a page that moved since then is a conflict, never a silent upsert.+ if (row.authority?.attestedOp === 'memory_propose' && typeof p.expected_revision === 'string' && stored.revision !== p.expected_revision) {+ throw opError('revision_conflict', `${row.slug} changed after the proposal was approved, so the proposed link was not written.`,+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} changed nothing; a new proposal is needed if the link is still wanted.`);+ }const linkType = optional(p.link_type), linkSource = optional(p.link_source);const validFrom = optional(p.valid_from), validUntil = optional(p.valid_until);let body: string;diff --git a/src/core/persistence/memory-proposals.ts b/src/core/persistence/memory-proposals.tsindex 7b54c3a85e..0991313bfc 100644--- a/src/core/persistence/memory-proposals.ts+++ b/src/core/persistence/memory-proposals.ts@@ -69,9 +69,9 @@ function normalize(row: Record<string, unknown>): MemoryProposal {decided_at: iso(row.decided_at), created_at: iso(row.created_at)!, updated_at: iso(row.updated_at)!, expires_at: iso(row.expires_at)! } as MemoryProposal;}-/** The request id of a proposal: uuidv5 of the key under the member's own proposal namespace, so a key never crosses members or collides with a memory_write. */-export function proposalRequestId(member: string, idempotencyKey: string): string {- return uuidV5(uuidV5(QM_PROPOSE_REQUEST_NAMESPACE, `member:${member}`), idempotencyKey);+/** The request id of a proposal: uuidv5 of the key under the credential's and member's own proposal namespace, so a key never crosses credentials or members, or collides with a memory_write. */+export function proposalRequestId(principal: Principal, member: string, idempotencyKey: string): string {+ return uuidV5(uuidV5(QM_PROPOSE_REQUEST_NAMESPACE, `${principalKey(principal)}:member:${member}`), idempotencyKey);}/** Replay identity: only the fields the caller sent. */@@ -88,7 +88,7 @@ export async function getProposal(engine: SqlEngine, principal: Principal, requeconst proposalNotFound = (requestId: string) => opError('not_found', `No memory proposal has request id ${requestId}.`,'List the proposals awaiting a decision with gbrain memory-proposals list, and pass one of their request ids.');-/** The proposal an owner names by request id. Two credentials could only share one by colliding uuidv5 namespaces; that is refused, never guessed. */+/** The proposal an owner names by request id. The namespace holds the credential, so two credentials share one only by a uuidv5 collision; that is refused, never guessed. */export async function ownerProposal(engine: SqlEngine, requestId: string): Promise<MemoryProposal> {if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(requestId)) throw proposalNotFound(requestId);const rows = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM memory_proposals WHERE request_id=$1::uuid LIMIT 2', [requestId]);@@ -260,7 +260,7 @@ async function prepareApproval(ctx: OperationContext, row: MemoryProposal): Promtry {const { preparePageAdmission } = await import('./page-mutations.ts');const params: Record<string, unknown> = { ...row.payload, request_id: row.request_id,- ...(row.kind === 'timeline' && row.expected_revision ? { expected_revision: row.expected_revision } : {}) };+ ...(row.expected_revision ? { expected_revision: row.expected_revision } : {}) };const prepared = await preparePageAdmission(lane, { operation: row.operation, params });return prepared.prior ? { prior: prepared.prior } : { admission: prepared.admission! };} catch (error) { return refusal(error); }diff --git a/test/qm-memory-propose.test.ts b/test/qm-memory-propose.test.tsindex a27a02f615..ec8fcad769 100644--- a/test/qm-memory-propose.test.ts+++ b/test/qm-memory-propose.test.ts@@ -132,7 +132,7 @@ for (const kind of testBackends()) {const held = await timeline(alice, 'Acme signed the harbor lease canaryapprove', {}, key);expect(held.isError).toBe(false);const id = held.structured!.request_id as string;- expect(id).toBe(proposalRequestId('alice-example', key));+ expect(id).toBe(proposalRequestId({ kind: 'oauth_client', id: qmClient }, 'alice-example', key));expect(held.structured).toMatchObject({ status: 'awaiting_owner', request_id: id, kind: 'timeline', target: ACME, expires_at: expect.any(String) });expect(await timelineRows('canaryapprove')).toHaveLength(0);expect(await journalRows(id)).toHaveLength(0);@@ -158,17 +158,66 @@ for (const kind of testBackends()) {expect((await proposalRow(id))!.decided_by).toBe('cli:test');}, 90_000);- test('the request id is uuidv5 of the member and key, apart from memory_write ids and other members', async () => {+ test('the request id is uuidv5 of the credential, member and key, apart from memory_write ids and other members', async () => {const key = 'same-key-' + randomUUID();const a = await timeline(alice, 'Key derivation canarykeyid a', {}, key);const b = await timeline(bob, 'Key derivation canarykeyid a', {}, key);- expect(a.structured!.request_id).toBe(proposalRequestId('alice-example', key));- expect(b.structured!.request_id).toBe(proposalRequestId('bob-example', key));+ const qm = { kind: 'oauth_client', id: qmClient } as const;+ expect(a.structured!.request_id).toBe(proposalRequestId(qm, 'alice-example', key));+ expect(b.structured!.request_id).toBe(proposalRequestId(qm, 'bob-example', key));expect(a.structured!.request_id).not.toBe(b.structured!.request_id);const { memoryWriteRequestId } = await import('../src/core/ops/qm-memory.ts');expect(await memoryWriteRequestId('alice-example', key, 0)).not.toBe(a.structured!.request_id);}, 60_000);+ test('two credentials proposing for one member with one key get two request ids, and the owner decides each', async () => {+ const c = await provider().registerClientManual('p-qm2-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: ATTEST_OPS });+ tokens.qm2 = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;+ const key = 'shared-key-' + randomUUID();+ const a = (await timeline(alice, 'Two credentials canarytwocreds one', {}, key)).structured!.request_id as string;+ const b = (await timeline({ token: 'qm2', actor: ALICE_ID }, 'Two credentials canarytwocreds two', {}, key)).structured!.request_id as string;+ expect(a).not.toBe(b);+ expect(b).toBe(proposalRequestId({ kind: 'oauth_client', id: c.clientId }, 'alice-example', key));+ expect(await approve(a)).toMatchObject({ status: 'approved', write_request: { state: 'committed' } });+ expect(await denyMemoryProposal(owner(), b, 'Duplicate', { decidedBy: 'cli:test' })).toMatchObject({ status: 'denied' });+ expect((await timelineRows('canarytwocreds')).map(r => r.summary)).toEqual(['Two credentials canarytwocreds one']);+ }, 90_000);++ test('link deny, expiry and cancel close the proposal and write no link and no journal row', async () => {+ const links = async () => engine.executeRaw('SELECT 1 FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id WHERE f.slug = $1 AND t.slug = $2 AND f.source_id = $3 AND l.context LIKE $4',+ [GLOBEX, INITECH, SRC, '%canarylinkclose%']);+ const link = async () => (await propose(alice, { kind: 'link', target: GLOBEX, to: INITECH, context: 'canarylinkclose' })).structured!.request_id as string;+ const denied = await link();+ expect(await denyMemoryProposal(owner(), denied, 'no', { decidedBy: 'cli:test' })).toMatchObject({ status: 'denied' });+ const expired = await link();+ await engine.executeRaw("UPDATE memory_proposals SET expires_at = now() - interval '1 minute' WHERE request_id = $1::uuid", [expired]);+ await runMemoryProposalUpkeep(engine);+ const cancelled = await link();+ expect((await call(alice, 'cancel_write_request', { request_id: cancelled })).json).toMatchObject({ state: 'cancelled' });+ for (const [id, state] of [[denied, 'denied'], [expired, 'expired'], [cancelled, 'cancelled']] as const) {+ expect((await proposalRow(id))!.state).toBe(state);+ expect(await journalRows(id)).toHaveLength(0);+ }+ expect(await links()).toHaveLength(0);+ }, 90_000);++ test('link approval carries the proposal revision to publication: a page moved after the yes is a conflict, never a silent upsert', async () => {+ const id = (await propose(alice, { kind: 'link', target: ACME, to: INITECH, context: 'canarylinkpin' })).structured!.request_id as string;+ const held = (await proposalRow(id))!;+ expect(typeof held.expected_revision).toBe('string');+ const from = (await engine.getPage(ACME, { sourceId: SRC }))!;+ const row = { request_id: id, operation: 'add_link', source_id: SRC, slug: ACME, page_id: from.id,+ intent: { to: INITECH, link_type: '', link_source: 'qm-proposal', context: 'canarylinkpin', expected_revision: 'not-the-revision' }, authority: { ...held.authority, attestedOp: 'memory_propose' } };+ const { prepareManualLinkMutation } = await import('../src/core/persistence/manual-links.ts');+ await expect(prepareManualLinkMutation(engine, row as never, { engine: engine.kind } as never)).rejects.toMatchObject({ code: 'revision_conflict' });+ const current = await prepareManualLinkMutation(engine, { ...row, intent: { ...row.intent, expected_revision: held.expected_revision } } as never, { engine: engine.kind } as never)+ .then(() => 'prepared', (e: { code?: string }) => e.code);+ expect(current).not.toBe('revision_conflict');+ expect(await approve(id)).toMatchObject({ status: 'approved', write_request: { state: 'committed' } });+ expect((await journalRows(id))[0]!.intent).toMatchObject({ expected_revision: held.expected_revision });+ }, 90_000);+test('deny: the receipt says denied with the reason, the page is unchanged, approve afterwards is proposal_closed', async () => {const held = await timeline(alice, 'Acme moved offices canarydeny');const id = held.structured!.request_id as string;diff --git a/test/qm-personal-sources.test.ts b/test/qm-personal-sources.test.tsindex e402e73de0..cdd29b9533 100644--- a/test/qm-personal-sources.test.ts+++ b/test/qm-personal-sources.test.ts@@ -228,9 +228,9 @@ for (const kind of testBackends()) {expect((await call('wide', 'get_page', { slug: PAGE_B, source_id: DM_B }, null)).text).toContain('canarydmbobpage');}, 120_000);- test('an agent job submitted for an attested person reads the same way: its own personal source, never another member\'s', async () => {+ test('an agent job submitted for an attested person on a person-read credential reads the same way: its own personal source, never another member\'s', async () => {const { clientId } = await provider().registerClientManual('personal-agent-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);- await bindCredential(engine, { kind: 'client', id: clientId }, { attestActor: 'qm', attestOps: ['get_page', 'query'] });+ await bindCredential(engine, { kind: 'client', id: clientId }, { attestActor: 'qm', attestOps: ['get_page', 'query'], attestRead: 'person' });await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', bound_tools = ARRAY['get_page','query'], bound_source_id = source_id, federated_read = $2::text[], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 1 WHERE client_id = $1", [clientId, [SRC, DM_A, DM_B]]);const actor = { system: 'qm', external_id: ALICE_ID, member: 'alice-example' };const agentAuth = { token: 'x', clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC, DM_A, DM_B], principal: { kind: 'oauth_client', id: clientId } } as unknown as AuthInfo;diff --git a/test/qm-scope-read.test.ts b/test/qm-scope-read.test.tsindex d5fa7d7961..e654813e9b 100644--- a/test/qm-scope-read.test.ts+++ b/test/qm-scope-read.test.ts@@ -32,7 +32,11 @@ import { addMember, bindCredential } from '../src/core/access/members.ts';import { attestRightOf, linkMember } from '../src/core/access/actor.ts';import { takeBindingFlags, bindingLine } from '../src/commands/auth-binding.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import type { AuthInfo } from '../src/core/ops/contract.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { attestedCallerAccess } from '../src/core/access/actor.ts';+import { withCallerAccess } from '../src/core/search/private-visibility.ts';+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';+import { prepareRemoteAgent, withSubmissionAuthority, type RemoteAgentAuthority } from '../src/core/minions/submission-authority.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -210,7 +214,49 @@ for (const kind of testBackends()) {hidden(out);await refused(call(client, 'get_backlinks', { slug: ACME, source_id: OTHER }), 'permission_denied');await refused(call(client, 'get_backlinks', { slug: ACME, source_id: SRC, all_sources: true }), 'invalid_params');+ await refused(call(client, 'get_backlinks', { slug: ACME, all_sources: true }), 'invalid_params');}+ expect((await call('person', 'get_backlinks', { slug: ACME, all_sources: true })).text).toContain('zephyr-restricted-example');+ }, 120_000);++ test('context_pack that names sources is refused on a scope credential, never read as the person; unnamed and person credentials are unchanged', async () => {+ const c = await provider().registerClientManual('scope-ctx-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);+ await provider().rescopeClient(c.clientId, { federatedRead: [SRC, ROOM] });+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: [...SCOPE_OPS, 'context_pack'] });+ clients.ctx = { id: c.clientId, secret: c.clientSecret ?? '', token: (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token };+ for (const params of [{ source_id: SRC }, { all_sources: true }, { entity_refs: [{ source_id: SRC, slug: RESTRICTED }] }]) {+ const out = await refused(call('ctx', 'context_pack', { counterparty: 'Zephyr Restricted Example', ...params }), 'invalid_params');+ expect(out.all).toContain('context_pack: a call that names sources');+ }+ expect((await call('ctx', 'context_pack', { counterparty: 'Zephyr Restricted Example' })).all).not.toContain('context_pack: a call that names sources');+ }, 120_000);++ test('an agent job submitted for the person reads named sources as the scope too, exactly like the direct call', async () => {+ const job = async (read?: 'person') => {+ const c = await provider().registerClientManual('scope-agent-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: ['get_page', 'query'], ...(read ? { attestRead: read } : {}) });+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', bound_tools = ARRAY['get_page','query'], bound_source_id = source_id, federated_read = $2::text[], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 1 WHERE client_id = $1", [c.clientId, [SRC, ROOM]]);+ const actor = { system: 'qm', external_id: ALICE_ID, member: 'alice-example' };+ const agentAuth = { token: 'x', clientId: c.clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC, ROOM], principal: { kind: 'oauth_client', id: c.clientId } } as unknown as AuthInfo;+ const submitted = await withCallerAccess(await attestedCallerAccess(engine, actor, ['member:alice-example']),+ () => prepareRemoteAgent({ engine, auth: agentAuth, remote: true } as unknown as OperationContext, { source_id: SRC, allowed_tools: ['get_page', 'query'], allowed_slug_prefixes: [] }));+ const tools = buildBrainTools({ subagentId: 13, engine, config: { engine: 'pglite' } as never, sourceId: SRC,+ delegatedAuth: { clientId: c.clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC, ROOM] } });+ const authority: RemoteAgentAuthority = { ...submitted, payloadHash: '0'.repeat(64) };+ return async (tool: string, input: Record<string, unknown>) => {+ try { return JSON.stringify(await withSubmissionAuthority(authority, () => tools.find(t => t.name === tool)!.execute(input, { engine, jobId: 1, remote: true } as never))); }+ catch (e) { return 'ERR ' + String((e as Error).message); }+ };+ };+ const scoped = await job();+ expect(await scoped('brain_get_page', { slug: RESTRICTED })).toContain('canaryrestrictedbody');+ expect(await scoped('brain_get_page', { slug: RESTRICTED, source_id: SRC })).not.toContain('canaryrestrictedbody');+ expect(await scoped('brain_get_page', { slug: MEMBER_PAGE, source_id: SRC })).not.toContain('Memory of alice-example');+ const found = await scoped('brain_query', { query: 'harbor ledger tariffs', limit: 20, source_ids: [SRC] });+ expect(found).toContain('canaryworldacme');+ for (const c of CANARIES) expect(found).not.toContain(c);+ expect(await scoped('brain_get_page', { slug: RESTRICTED, all_sources: true })).not.toContain('canaryrestrictedbody');+ expect(await (await job('person'))('brain_get_page', { slug: RESTRICTED, source_id: SRC })).toContain('canaryrestrictedbody');}, 120_000);test('get_timeline narrows to source_id/source_ids inside the grant and, named, reads as the scope', async () => {