From 315b00277f818de49b85c6029476ffa5d29ac78d Mon Sep 17 00:00:00 2001 From: Kris Zyp Date: Mon, 16 Nov 2026 13:33:57 -0700 Subject: [PATCH 1/9] Let a principal act for another: Delegation rows for edit and shared private scope A Delegation row (keyed by the delegate's principal id, actsFor the principal it acts for) lets a person's agents revise, withdraw, confirm, link and list candidates for the person's memories, and read and write user:. A delegate still reads only through labels; ownership-based reads are not shared. Co-Authored-By: Claude Opus 5.5 Dispatch-Task: agent-memory-55-delegation --- integrationTests/delegation.test.ts | 161 +++++++++++++ schema/memory.graphql | 8 + src/events.ts | 62 ++--- src/lifecycle.ts | 53 +++-- src/mcp.ts | 3 +- src/principal.ts | 44 ++-- src/scopes.ts | 91 +++++++- src/search.ts | 17 +- src/supersession.ts | 4 +- test/delegation.test.js | 347 ++++++++++++++++++++++++++++ test/helpers/harper-stub.mjs | 15 +- test/principal.test.js | 61 +++++ test/scopes.test.js | 83 +++++++ 13 files changed, 861 insertions(+), 88 deletions(-) create mode 100644 integrationTests/delegation.test.ts create mode 100644 test/delegation.test.js diff --git a/integrationTests/delegation.test.ts b/integrationTests/delegation.test.ts new file mode 100644 index 0000000..b4c09da --- /dev/null +++ b/integrationTests/delegation.test.ts @@ -0,0 +1,161 @@ +// Needs `npm run install:fixtures` first: the fixture app loads the packed plugin from its own node_modules. +import { suite, test, before, after } from 'node:test'; +import { deepStrictEqual, ok, strictEqual } from 'node:assert/strict'; +import { join, dirname } from 'node:path'; +import { createRequire } from 'node:module'; +import { setupHarperWithFixture, teardownHarper, type ContextWithHarper } from '@harperfast/integration-testing'; + +const require = createRequire(import.meta.url); +const fixturePath = join(import.meta.dirname, 'fixtures', 'memory-app'); +const PASSWORD = 'Delegation-test-1!'; + +// kris is the person; agent-a acts for kris with global-only grants; carol is someone else. +suite('@harperfast/agent-memory delegation over HTTP', (ctx: ContextWithHarper) => { + const basic = (username: string, password: string) => + 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64'); + + async function operation(body: object) { + const response = await fetch(ctx.harper.operationsAPIURL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: basic(ctx.harper.admin.username, ctx.harper.admin.password), + }, + body: JSON.stringify(body), + }); + const text = await response.text(); + ok(response.ok, `${JSON.stringify(body)} → ${response.status} ${text}`); + return JSON.parse(text); + } + + async function call(user: string, method: string, path: string, body?: unknown, revision?: number) { + const response = await fetch(`${ctx.harper.httpURL}/Memory/${path}`, { + method, + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + Authorization: basic(user, PASSWORD), + ...(revision !== undefined && { 'If-Match': `"${revision}"` }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const text = await response.text(); + let parsed: any; + try { + parsed = JSON.parse(text); + } catch { + parsed = text; + } + return { status: response.status, body: parsed }; + } + + const memId = (tag: string) => `mem-dlg-${tag}`.padEnd(16, '_'); + const delegate = (id: string, actsFor: string) => + operation({ operation: 'upsert', database: 'memory', table: 'Delegation', records: [{ id, actsFor }] }); + const revoke = (id: string) => operation({ operation: 'delete', database: 'memory', table: 'Delegation', ids: [id] }); + + before(async () => { + await setupHarperWithFixture(ctx, fixturePath, { + harperBinPath: + process.env.HARPER_INTEGRATION_TEST_INSTALL_SCRIPT ?? + join(dirname(require.resolve('harper')), 'bin', 'harper.js'), + config: { + threads: { count: 1 }, + logging: { stdStreams: true }, + authentication: { authorizeLocal: false }, + }, + }); + await operation({ operation: 'add_role', role: 'member', permission: { super_user: false } }); + for (const username of ['kris', 'agent-a', 'carol']) { + await operation({ operation: 'add_user', username, password: PASSWORD, role: 'member', active: true }); + } + await operation({ + operation: 'upsert', + database: 'memory', + table: 'ScopeGrant', + records: [ + { id: 'role:member', read: ['global'], write: ['global'] }, + { id: 'user:kris', read: ['customer:*'], write: ['customer:*'] }, + ], + }); + await delegate('agent-a', 'kris'); + const deadline = Date.now() + 60_000; + let ready = await call('kris', 'GET', '?q=warmup'); + while (ready.status === 503 && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 250)); + ready = await call('kris', 'GET', '?q=warmup'); + } + strictEqual(ready.status, 200, JSON.stringify(ready.body)); + }); + + after(async () => { + await teardownHarper(ctx); + }); + + test("a delegate revises the principal's memory as the principal, until the row is revoked", async () => { + const id = memId('revise'); + strictEqual( + (await call('kris', 'PUT', id, { title: 'imported', content: 'stale conclusion', visibility: 'shared' })).status, + 201, + ); + const revised = await call('agent-a', 'PUT', id, { content: 'corrected conclusion' }, 1); + strictEqual(revised.status, 200, JSON.stringify(revised.body)); + const memory = (await call('kris', 'GET', id)).body.memory; + strictEqual(memory.ownerId, 'kris'); + strictEqual(memory.content, 'corrected conclusion'); + strictEqual(memory.lastEditor.principalId, 'agent-a'); + + const refused = await call('carol', 'PUT', id, { content: 'carol edit' }, 2); + strictEqual(refused.status, 403); + strictEqual(refused.body.code, 'not_memory_owner'); + ok(refused.body.error.includes(`supersedes: ["${id}"]`), refused.body.error); + + await revoke('agent-a'); + try { + const afterRevoke = await call('agent-a', 'PUT', id, { content: 'after revoke' }, 2); + strictEqual(afterRevoke.status, 403, JSON.stringify(afterRevoke.body)); + strictEqual(afterRevoke.body.code, 'not_memory_owner'); + } finally { + await delegate('agent-a', 'kris'); + } + }); + + test('user: is shared with the delegate and 404 to anyone else', async () => { + const byAgent = memId('agent-note'); + const created = await call('agent-a', 'PUT', byAgent, { title: 'agent note', content: 'private to the person' }); + strictEqual(created.status, 201, JSON.stringify(created.body)); + const stored = (await call('kris', 'GET', byAgent)).body.memory; + deepStrictEqual(stored.scopes, ['user:kris']); + strictEqual(stored.ownerId, 'kris'); + strictEqual(stored.author.principalId, 'agent-a'); + + const byKris = memId('kris-note'); + strictEqual((await call('kris', 'PUT', byKris, { title: 'kris note', content: 'kris private' })).status, 201); + strictEqual((await call('agent-a', 'GET', byKris)).status, 200); + strictEqual((await call('agent-a', 'PUT', byKris, { content: 'agent edit' }, 1)).status, 200); + + for (const id of [byAgent, byKris]) { + strictEqual((await call('carol', 'GET', id)).status, 404); + strictEqual((await call('carol', 'PUT', id, { content: 'x' }, 1)).status, 409); + } + const carolSees = (await call('carol', 'GET', '?limit=50')).body.memories.map((memory: any) => memory.id); + ok(!carolSees.includes(byAgent) && !carolSees.includes(byKris)); + const agentSees = (await call('agent-a', 'GET', '?limit=50')).body.memories.map((memory: any) => memory.id); + ok(agentSees.includes(byAgent) && agentSees.includes(byKris)); + }); + + test("a global-only delegate is denied the principal's customer memory", async () => { + const id = memId('customer'); + strictEqual( + (await call('kris', 'PUT', id, { title: 'acme incident', content: 'acme detail', scopes: ['customer:acme'] })) + .status, + 201, + ); + strictEqual((await call('agent-a', 'GET', id)).status, 404); + strictEqual((await call('agent-a', 'PUT', id, { content: 'x' }, 1)).status, 409); + strictEqual((await call('agent-a', 'DELETE', id, undefined, 1)).status, 404); + strictEqual((await call('agent-a', 'POST', `${id}/confirm`, {})).status, 404); + const agentSees = (await call('agent-a', 'GET', '?scope=customer:acme')).body.memories; + deepStrictEqual(agentSees, []); + }); +}); diff --git a/schema/memory.graphql b/schema/memory.graphql index 22e7903..f837d7b 100644 --- a/schema/memory.graphql +++ b/schema/memory.graphql @@ -31,6 +31,7 @@ type Memory @table(database: "memory", audit: true) { validUntil: Date withdrawnAt: Date withdrawnReason: String + withdrawnBy: String # The plugin installs its own embedder for every model; it embeds with the model recorded on the row. embedding: [Float] @embed(source: "content", model: "default") embeddingModel: String @indexed @@ -54,6 +55,13 @@ type ScopeGrant @table(database: "memory", audit: true) { updatedAt: Date @updatedTime } +# Keyed by the delegate's principal id: that principal acts for `actsFor` (DESIGN.md Identity). +type Delegation @table(database: "memory", audit: true) { + id: ID @primaryKey + actsFor: String + updatedAt: Date @updatedTime +} + type MemoryWatch @table(database: "memory", audit: true) { id: ID @primaryKey principalId: String @indexed diff --git a/src/events.ts b/src/events.ts index 06c4788..a78ae15 100644 --- a/src/events.ts +++ b/src/events.ts @@ -10,7 +10,7 @@ import { } from './lifecycle.ts'; import { hasCustomPrincipalResolver, resolvePrincipal } from './principal.ts'; import { forReader } from './provenance.ts'; -import { canRead, type Principal } from './scopes.ts'; +import { canRead, inOwnView, type Principal } from './scopes.ts'; const EVENT_KINDS = ['created', 'revised', 'superseded', 'withdrawn', 'restored', 'flagged'] as const; type MemoryEventKind = (typeof EVENT_KINDS)[number]; @@ -232,13 +232,18 @@ interface CachedPrincipal { const principalCache = new Map(); const inflightPrincipals = new Map>(); +// Bumped on every invalidation, so a resolution that started before a grant or delegation change is not cached. +let principalCacheGeneration = 0; let nextListenerCacheId = 0; -function scopeGrantTable(): any { - return (databases as any).memory?.ScopeGrant; +// The tables a principal is resolved from: a change to either invalidates the cache. +function authTables(): any[] { + const memory = (databases as any).memory; + return [memory?.ScopeGrant, memory?.Delegation]; } function clearPrincipalCache(): void { + principalCacheGeneration++; principalCache.clear(); inflightPrincipals.clear(); } @@ -267,14 +272,17 @@ async function resolveSubscriberPrincipal( } const existing = inflightPrincipals.get(key); if (existing) return existing; - const promise = resolvePrincipal(authContext).then( + const generation = principalCacheGeneration; + const promise: Promise = resolvePrincipal(authContext).then( (resolved) => { - inflightPrincipals.delete(key); - principalCache.set(key, { principal: resolved, expiresAtMs: Date.now() + PRINCIPAL_CACHE_TTL_MS }); + if (inflightPrincipals.get(key) === promise) inflightPrincipals.delete(key); + if (generation === principalCacheGeneration) { + principalCache.set(key, { principal: resolved, expiresAtMs: Date.now() + PRINCIPAL_CACHE_TTL_MS }); + } return resolved; }, (error) => { - inflightPrincipals.delete(key); + if (inflightPrincipals.get(key) === promise) inflightPrincipals.delete(key); throw error; }, ); @@ -465,7 +473,7 @@ const tableListeners = new Set(); const itemListeners = new Map>(); let hubSub: UpstreamSub | undefined; let watchHubSub: UpstreamSub | undefined; -let grantHubSub: UpstreamSub | undefined; +let authHubSubs: UpstreamSub[] = []; let hubOpening: Promise | undefined; function closeUpstreamSub(sub: UpstreamSub | undefined): void { @@ -478,10 +486,10 @@ function closeUpstreamSub(sub: UpstreamSub | undefined): void { function resetHubState(): void { const activeMem = hubSub; const activeWatch = watchHubSub; - const activeGrant = grantHubSub; + const activeAuth = authHubSubs; hubSub = undefined; watchHubSub = undefined; - grantHubSub = undefined; + authHubSubs = []; watchesByPrincipal.clear(); seededWatchPrincipals.clear(); seedingWatchPrincipals.clear(); @@ -489,7 +497,7 @@ function resetHubState(): void { clearPrincipalCache(); closeUpstreamSub(activeMem); closeUpstreamSub(activeWatch); - closeUpstreamSub(activeGrant); + for (const sub of activeAuth) closeUpstreamSub(sub); } function teardownActiveHub(): void { @@ -522,29 +530,29 @@ async function ensureHubSubscription(): Promise { opening = (async () => { let rawSub: UpstreamSub | undefined; let rawWatchSub: UpstreamSub | undefined; - let rawGrantSub: UpstreamSub | undefined; + const rawAuthSubs: UpstreamSub[] = []; try { await null; const Memory = memoryTable(); const MemoryWatch = memoryWatchTable(); - const ScopeGrant = scopeGrantTable(); const memSub: UpstreamSub = await Memory.subscribe({ omitCurrent: true, includeSuperseded: true }, {}); rawSub = memSub; rawWatchSub = typeof MemoryWatch?.subscribe === 'function' ? await MemoryWatch.subscribe({ omitCurrent: true }, {}) : undefined; - rawGrantSub = - typeof ScopeGrant?.subscribe === 'function' ? await ScopeGrant.subscribe({ omitCurrent: true }, {}) : undefined; + for (const table of authTables()) { + if (typeof table?.subscribe === 'function') rawAuthSubs.push(await table.subscribe({ omitCurrent: true }, {})); + } if (tableListeners.size === 0 && itemListeners.size === 0) { closeUpstreamSub(rawSub); closeUpstreamSub(rawWatchSub); - closeUpstreamSub(rawGrantSub); + for (const sub of rawAuthSubs) closeUpstreamSub(sub); return; } hubSub = memSub; watchHubSub = rawWatchSub; - grantHubSub = rawGrantSub; + authHubSubs = rawAuthSubs; if (rawWatchSub) { const watchSub = rawWatchSub; @@ -564,18 +572,17 @@ async function ensureHubSubscription(): Promise { })(); } - if (rawGrantSub) { - const grantSub = rawGrantSub; + for (const authSub of rawAuthSubs) { void (async () => { try { - for await (const _ of grantSub) { - if (grantHubSub !== grantSub) break; + for await (const _ of authSub) { + if (!authHubSubs.includes(authSub)) break; clearPrincipalCache(); } } catch (error) { - if (grantHubSub === grantSub) normalizeError(error, 'subscribe'); + if (authHubSubs.includes(authSub)) normalizeError(error, 'subscribe'); } finally { - if (grantHubSub === grantSub) { + if (authHubSubs.includes(authSub)) { teardownActiveHub(); } } @@ -603,7 +610,7 @@ async function ensureHubSubscription(): Promise { } catch (error) { closeUpstreamSub(rawSub); closeUpstreamSub(rawWatchSub); - closeUpstreamSub(rawGrantSub); + for (const sub of rawAuthSubs) closeUpstreamSub(sub); throw error; } finally { if (hubOpening === opening) { @@ -759,7 +766,10 @@ export async function subscribeMemoryEvents( const kind = eventRecord?.lastEventKind; if (!id || !isEventKind(kind)) return undefined; const maybeOwnFlagged = - isFlagEvent(kind, eventRecord) && (!eventRecord?.ownerId || eventRecord.ownerId === principal.id); + isFlagEvent(kind, eventRecord) && + (!eventRecord?.ownerId || + inOwnView(eventRecord, principal) || + (principal.actsFor !== null && !Array.isArray(eventRecord.scopes))); if (maybeOwnFlagged) return { maybeOwnFlagged: true, watchConfirmed: false }; if (!hasActiveWatch(principal.id, id)) return undefined; return { maybeOwnFlagged: false, watchConfirmed: true }; @@ -779,7 +789,7 @@ export async function subscribeMemoryEvents( if (!deliverable) return undefined; const { event, record, currentPrincipal, dedupToken } = deliverable; - if (isFlagEvent(event.kind, record) && record.ownerId === currentPrincipal.id) { + if (isFlagEvent(event.kind, record) && inOwnView(record, currentPrincipal)) { if ( event.kind === 'flagged' || isNewContentFlag(event.kind, record) || diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 43d5dfd..65918a1 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -4,9 +4,11 @@ import { checkedText, matchCustomerContent } from './patterns.ts'; import { activeDependentIds, CLEARED_REVIEW, flagDependents, forReader, reviewFlagFor } from './provenance.ts'; import { CLEARED_CONTENT_FLAG, contentFlagFields, decideContentFlag, scheduleModelCheck } from './quarantine.ts'; import { + actsAsOwner, assertWritable, canRead, canWrite, + createScopesAndOwner, GLOBAL_SCOPE, isCustomerScope, isSuperset, @@ -314,6 +316,7 @@ export function toMemoryView(record: any): MemoryView { validUntil: iso(record.validUntil), withdrawnAt: iso(record.withdrawnAt), withdrawnReason: record.withdrawnReason ?? null, + withdrawnBy: record.withdrawnBy ?? null, createdAt: iso(record.createdAt), updatedAt: iso(record.updatedAt), }; @@ -592,17 +595,14 @@ function mayReviewWithdraw(existing: any, principal: Principal): boolean { return Boolean(existing.contentFlag) && reviewsCustomerContent(principal) && canRead(existing, principal); } -function plannedScopes( - payload: Record, - principal: Principal, - ownerId: string, - current?: string[], -): string[] | undefined { +/** The scopes a create (no `existing`) or a revise would write, or undefined when the write would be refused. */ +function plannedScopes(payload: Record, principal: Principal, existing?: any): string[] | undefined { try { - const scopes = - current && payload.scopes == null && payload.visibility == null - ? current - : normalizeScopes(payload.scopes, payload.visibility, ownerId); + const scopes = !existing + ? createScopesAndOwner(payload.scopes, payload.visibility, principal).scopes + : existing.scopes && payload.scopes == null && payload.visibility == null + ? existing.scopes + : normalizeScopes(payload.scopes, payload.visibility, existing.ownerId); assertWritable(scopes, principal); return scopes; } catch (error) { @@ -664,7 +664,7 @@ export async function putMemory(id: unknown, input: unknown, principal: Principa const citedReadable = cited.every((record) => record && canRead(record, principal)); const createScopes = !preExisting && ifMatch === undefined && parsedTitle !== undefined && parsedContent !== undefined && citedReadable - ? plannedScopes(payload, principal, principal.id) + ? plannedScopes(payload, principal) : undefined; const refused = (target: any) => supersedeRefusal(target, createScopes!, principal) !== undefined; const explicitTargets = createScopes @@ -677,10 +677,10 @@ export async function putMemory(id: unknown, input: unknown, principal: Principa matchesIfMatch(ifMatch, preExisting.revision) && (ifNoneMatch === undefined || !matchesIfNoneMatch(ifNoneMatch, preExisting.revision)) && payload.supersedes === undefined && - (preExisting.ownerId === principal.id || principal.superUser) && + (actsAsOwner(preExisting, principal) || principal.superUser) && preExisting.status === STATUS_ACTIVE && citedReadable - ? plannedScopes(payload, principal, preExisting.ownerId, preExisting.scopes) + ? plannedScopes(payload, principal, preExisting) : undefined; const mayRevise = revisedScopes !== undefined; const writesContent = @@ -775,14 +775,19 @@ export async function putMemory(id: unknown, input: unknown, principal: Principa const existing = await Memory.get(id, txn); const now = new Date(); if (existing) { + const owner = actsAsOwner(existing, principal); // A customer review (super_user's included) changes scopes only, so it leaves the owner's review flag alone. - const reviewing = existing.ownerId !== principal.id && isReviewRescope(existing, payload, principal); - if (existing.ownerId !== principal.id && !principal.superUser) { + const reviewing = !owner && isReviewRescope(existing, payload, principal); + if (!owner && !principal.superUser) { if (!canRead(existing, principal)) { throw memoryError('Memory id is not available', 409, 'id_unavailable'); } if (!isReviewRescope(existing, payload, principal)) { - throw memoryError('Only the owner can modify this memory', 403, 'not_memory_owner'); + throw memoryError( + `Only the owner, or a principal acting for it, can revise this memory. To correct it, create a merged replacement with supersedes: ["${id}"] and scopes that include all of its scopes.`, + 403, + 'not_memory_owner', + ); } } if (ifNoneMatch !== undefined && matchesIfNoneMatch(ifNoneMatch, existing.revision)) { @@ -906,7 +911,7 @@ export async function putMemory(id: unknown, input: unknown, principal: Principa } const title = boundedText(payload.title, 'title', settings.titleChars, true)!; const content = boundedText(payload.content, 'content', settings.contentChars, true)!; - const scopes = normalizeScopes(payload.scopes, payload.visibility, principal.id); + const { scopes, ownerId } = createScopesAndOwner(payload.scopes, payload.visibility, principal); assertWritable(scopes, principal); const tags = parsedTags ?? []; const evidence = parsedEvidence ?? []; @@ -965,7 +970,7 @@ export async function putMemory(id: unknown, input: unknown, principal: Principa embedding: planned.vector, tags, scopes, - ownerId: principal.id, + ownerId, status: STATUS_ACTIVE, revision: 1, lastEventKind: 'created', @@ -984,6 +989,7 @@ export async function putMemory(id: unknown, input: unknown, principal: Principa validUntil, withdrawnAt: null, withdrawnReason: null, + withdrawnBy: null, embeddingModel: settings.embeddingModel, }, txn, @@ -1247,7 +1253,7 @@ export async function withdrawMemory( ifMatch !== undefined && matchesIfMatch(ifMatch, planned.revision) && planned.status !== STATUS_WITHDRAWN && - (planned.ownerId === principal.id || principal.superUser || mayReviewWithdraw(planned, principal)); + (actsAsOwner(planned, principal) || principal.superUser || mayReviewWithdraw(planned, principal)); const plan = mayWithdraw ? [id, ...(planned.supersedes ?? []), ...(await activeDependentIds(Memory, [id], requestContext))] : [id]; @@ -1260,7 +1266,7 @@ export async function withdrawMemory( if (!existing) throw notFound(); // A caller that cannot read the memory gets the same 404 as a missing one, so a write attempt does not // confirm another principal's memory exists. One that can read it gets an informative 403. - if (existing.ownerId !== principal.id && !principal.superUser && !mayReviewWithdraw(existing, principal)) { + if (!actsAsOwner(existing, principal) && !principal.superUser && !mayReviewWithdraw(existing, principal)) { if (!canRead(existing, principal)) throw notFound(); throw memoryError('Only the owner can modify this memory', 403, 'not_memory_owner'); } @@ -1284,6 +1290,7 @@ export async function withdrawMemory( status: STATUS_WITHDRAWN, withdrawnAt: now, withdrawnReason: reason ?? null, + withdrawnBy: principal.id, lastEventKind: 'withdrawn', revision: existing.revision + 1, }, @@ -1361,7 +1368,7 @@ export async function linkSupersedes(id: unknown, input: unknown, principal: Pri planned && plannedNewIds.length > 0 && planned.status !== STATUS_WITHDRAWN && - (planned.ownerId === principal.id || principal.superUser) && + (actsAsOwner(planned, principal) || principal.superUser) && canWrite(planned.scopes ?? [], principal) && ifMatch !== undefined && matchesIfMatch(ifMatch, planned.revision) && @@ -1387,7 +1394,7 @@ export async function linkSupersedes(id: unknown, input: unknown, principal: Pri async (txn, locks) => { const existing = await Memory.get(id, txn); if (!existing) throw notFound(); - if (existing.ownerId !== principal.id && !principal.superUser) { + if (!actsAsOwner(existing, principal) && !principal.superUser) { if (!canRead(existing, principal)) throw notFound(); throw memoryError('Only the owner can modify this memory', 403, 'not_memory_owner'); } @@ -1477,7 +1484,7 @@ export async function confirmMemory( return withLockPlan(requestContext, [id], async (txn) => { const existing = await Memory.get(id, txn); if (!existing) throw notFound(); - if (existing.ownerId !== principal.id && !principal.superUser) { + if (!actsAsOwner(existing, principal) && !principal.superUser) { if (!canRead(existing, principal)) throw notFound(); throw memoryError('Only the owner can modify this memory', 403, 'not_memory_owner'); } diff --git a/src/mcp.ts b/src/mcp.ts index 4c6ef27..ef2be84 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -122,7 +122,8 @@ export const MEMORY_MCP_TOOLS = [ { name: 'revise', method: 'mcpRevise', - description: 'Revise an existing owned memory at a specific revision.', + description: + "Revise an existing memory you own, or one owned by the principal you act for, at a specific revision. To correct anyone else's memory, call remember with a merged replacement and supersedes: [id], with scopes that include all of its scopes.", inputSchema: { type: 'object', additionalProperties: false, diff --git a/src/principal.ts b/src/principal.ts index db647d7..00fac4b 100644 --- a/src/principal.ts +++ b/src/principal.ts @@ -8,12 +8,13 @@ export interface PrincipalResolution { grants?: GrantPatterns; superUser?: boolean; source?: string; + actsFor?: string; } /** - * Maps a request context to a principal. `next()` is the default resolution (the Harper user and its - * ScopeGrant rows), so a resolver can handle its own credentials and defer everything else. Returning - * undefined means unauthenticated. + * Maps a request context to a principal. `next()` is the default resolution (the Harper user, its ScopeGrant + * rows and its Delegation row), so a resolver can handle its own credentials and defer everything else. + * Returning undefined means unauthenticated. */ export type PrincipalResolver = ( context: any, @@ -33,6 +34,10 @@ function grantRows(): any { return (databases as any).memory.ScopeGrant; } +function delegationRows(): any { + return (databases as any).memory.Delegation; +} + async function resolveHarperUser(context: any): Promise { const user = context?.user; if (typeof user?.username !== 'string') return undefined; @@ -41,9 +46,10 @@ async function resolveHarperUser(context: any): Promise(); -const MAX_WARNED_PATTERNS = 1000; +// Grants are compiled on every request; warn once per value rather than once per request. +const warnedValues = new Set(); +const MAX_WARNED_VALUES = 1000; -function warnRejectedPattern(pattern: unknown): void { - const key = JSON.stringify(pattern); - if (warnedPatterns.has(key) || warnedPatterns.size >= MAX_WARNED_PATTERNS) return; - warnedPatterns.add(key); - logger.warn?.(`[agent-memory] ignoring invalid scope grant pattern ${key}`); +function warnRejected(value: unknown, kind: 'pattern' | 'actsFor'): void { + const text = JSON.stringify(value); + const key = `${kind}:${text}`; + if (warnedValues.has(key) || warnedValues.size >= MAX_WARNED_VALUES) return; + warnedValues.add(key); + logger.warn?.( + kind === 'pattern' + ? `[agent-memory] ignoring invalid scope grant pattern ${text}` + : `[agent-memory] ignoring invalid delegation actsFor ${text}`, + ); } /** - * The caller behind a request context: the custom resolver's answer, else the Harper user and its `ScopeGrant` - * rows. Rejects with a 401 `principal_required` MemoryError when there is no caller; a failed grant read or a - * throwing resolver rejects with its own error. + * The caller behind a request context: the custom resolver's answer, else the Harper user, its `ScopeGrant` rows + * and its `Delegation` row. Rejects with a 401 `principal_required` MemoryError when there is no caller; a failed + * grant or delegation read, or a throwing resolver, rejects with its own error. */ export async function resolvePrincipal(context: any): Promise { const resolver = domain().resolver; @@ -76,5 +88,5 @@ export async function resolvePrincipal(context: any): Promise { ? await resolver(context, () => resolveHarperUser(context)) : await resolveHarperUser(context); if (!resolution) throw memoryError('Authenticated principal required', 401, 'principal_required'); - return createPrincipal(resolution, warnRejectedPattern); + return createPrincipal(resolution, warnRejected); } diff --git a/src/scopes.ts b/src/scopes.ts index e3d69b5..d56428a 100644 --- a/src/scopes.ts +++ b/src/scopes.ts @@ -27,6 +27,7 @@ export interface PrincipalInput { superUser?: boolean; source?: string; grants?: GrantPatterns; + actsFor?: unknown; } export interface ScopeMatcher { @@ -35,15 +36,16 @@ export interface ScopeMatcher { } /** - * `read` and `write` are the effective grant patterns: `user:` first, then exact labels, then namespace - * wildcards (`customer:*`). A pattern that grants nothing (invalid, in the `user` namespace, past + * `read` and `write` are the effective grant patterns: `user:` (and `user:`) first, then exact labels, + * then namespace wildcards (`customer:*`). A pattern that grants nothing (invalid, in the `user` namespace, past * MAX_GRANT_PATTERNS, or inside a granted wildcard) is not listed. A super_user's lists do not enumerate its - * access; `superUser` does. + * access; `superUser` does. `actsFor` is the principal this one acts for (a Delegation), or null. */ export interface Principal { readonly id: string; readonly superUser: boolean; readonly source: string; + readonly actsFor: string | null; readonly read: readonly string[]; readonly write: readonly string[]; } @@ -69,6 +71,12 @@ export function isScopeLabel(label: unknown): label is string { ); } +function isPrincipalId(id: unknown): id is string { + return ( + typeof id === 'string' && id.length > 0 && id.length <= PRINCIPAL_ID_MAX_CHARS && !PRINCIPAL_ID_FORBIDDEN.test(id) + ); +} + export function requirePrincipalId(id: unknown): string { if (typeof id !== 'string' || id.length === 0) { throw memoryError('Authenticated principal required', 401, 'principal_required'); @@ -83,20 +91,24 @@ export function requirePrincipalId(id: unknown): string { } /** - * Compile grant patterns into a matcher. `user:` is always included. A pattern that is neither an exact - * label nor `:*` is reported in `rejected` and grants nothing; patterns past MAX_GRANT_PATTERNS too. - * So is any pattern in the `user` namespace: `user:` means the owner only, and a grant such as `user:*` - * would quietly open every private memory. Reading everything is what super_user is for. + * Compile grant patterns into a matcher. `user:` is always included, and `user:` for a delegate; + * neither counts toward MAX_GRANT_PATTERNS. A pattern that is neither an exact label nor `:*` is + * reported in `rejected` and grants nothing; patterns past MAX_GRANT_PATTERNS too. So is any pattern in the + * `user` namespace: `user:` means the owner only, and a grant such as `user:*` would quietly open every + * private memory. Reading everything is what super_user is for. */ export function compileMatcher( patterns: readonly unknown[] | undefined, principalId: string, + actsFor?: string | null, ): { matcher: ScopeMatcher; rejected: unknown[] } { const exact = new Set([userScope(principalId)]); + if (actsFor) exact.add(userScope(actsFor)); + const implicit = exact.size; const namespaces = new Set(); const rejected: unknown[] = []; for (const pattern of patterns ?? []) { - if (exact.size + namespaces.size >= MAX_GRANT_PATTERNS + 1) { + if (exact.size + namespaces.size >= MAX_GRANT_PATTERNS + implicit) { rejected.push(pattern); continue; } @@ -157,15 +169,28 @@ export function matches(patterns: readonly string[], label: string): boolean { return covers((patterns as CompiledList)[MATCHER]!, label); } -export function createPrincipal(input: PrincipalInput, onRejectedPattern?: (pattern: unknown) => void): Principal { +/** + * `onRejected` hears each grant pattern and each `actsFor` that grants nothing. An `actsFor` naming the principal + * itself, or one that is not a valid principal id, is ignored: `:` would let it forge a label (`user:a:b`). + */ +export function createPrincipal( + input: PrincipalInput, + onRejected?: (value: unknown, kind: 'pattern' | 'actsFor') => void, +): Principal { const id = requirePrincipalId(input.id); - const read = compileMatcher(input.grants?.read, id); - const write = compileMatcher(input.grants?.write, id); - if (onRejectedPattern) for (const pattern of [...read.rejected, ...write.rejected]) onRejectedPattern(pattern); + let actsFor: string | null = null; + if (input.actsFor !== undefined && input.actsFor !== null) { + if (isPrincipalId(input.actsFor) && input.actsFor !== id) actsFor = input.actsFor; + else onRejected?.(input.actsFor, 'actsFor'); + } + const read = compileMatcher(input.grants?.read, id, actsFor); + const write = compileMatcher(input.grants?.write, id, actsFor); + if (onRejected) for (const pattern of [...read.rejected, ...write.rejected]) onRejected(pattern, 'pattern'); const principal = { id, superUser: input.superUser === true, source: input.source || 'harper', + actsFor, read: patternList(read.matcher), write: patternList(write.matcher), }; @@ -211,6 +236,32 @@ export function canRead(record: ScopedRecord, principal: Principal): boolean { return canReadLabels(principal, record.scopes); } +/** + * Rule 3's edit gate, short of super_user: the owner, or a principal acting for the owner that can read the memory. + * A delegate reads only through labels (its grants plus `user:`), so delegation never opens a memory its + * own grants do not. + */ +export function actsAsOwner(record: ScopedRecord, principal: Principal): boolean { + return ( + record.ownerId === principal.id || + (principal.actsFor !== null && record.ownerId === principal.actsFor && canRead(record, principal)) + ); +} + +/** The memories shown as the caller's own (bootstrap, own-flag events): owned, or in its principal's private scope. */ +export function inOwnView(record: ScopedRecord, principal: Principal): boolean { + return ( + record.ownerId === principal.id || + (principal.actsFor !== null && (record.scopes ?? []).includes(userScope(principal.actsFor))) + ); +} + +export function ownViewCondition(principal: Principal): Condition { + const owned: Condition = { attribute: 'ownerId', comparator: 'equals', value: principal.id }; + if (principal.actsFor === null) return owned; + return anyOf([owned, { attribute: 'scopes', comparator: 'equals', value: userScope(principal.actsFor) }]); +} + export function canWrite(scopes: readonly string[], principal: Principal): boolean { const { write } = matchersOf(principal); return principal.superUser || scopes.every((label) => covers(write, label)); @@ -231,6 +282,22 @@ export function isSuperset(next: readonly string[], previous: readonly string[]) return previous.every((label) => next.includes(label)); } +/** + * A create's scopes and owner. A delegate's private shorthand lands in its principal's scope, and a create carrying + * exactly that label belongs to the principal, so the principal and its other delegates can edit it. Any other + * create belongs to its writer: a mixed create stays editable, and readable through content flags, by the writer. + */ +export function createScopesAndOwner( + scopes: unknown, + visibility: unknown, + principal: Principal, +): { scopes: string[]; ownerId: string } { + const { actsFor } = principal; + const resolved = normalizeScopes(scopes, visibility, actsFor ?? principal.id); + const privateToPrincipal = actsFor !== null && resolved.length === 1 && resolved[0] === userScope(actsFor); + return { scopes: resolved, ownerId: privateToPrincipal ? actsFor : principal.id }; +} + /** * The scopes a write produces: explicit `scopes` wins over `visibility`; neither means private. Labels are * deduplicated and sorted so a retry with the same set in another order produces an identical array. diff --git a/src/search.ts b/src/search.ts index c2fd787..5a0a092 100644 --- a/src/search.ts +++ b/src/search.ts @@ -15,7 +15,15 @@ import { type MemoryView, } from './lifecycle.ts'; import { forReader } from './provenance.ts'; -import { anyOf, canRead, isScopeLabel, readableConditions, type Condition, type Principal } from './scopes.ts'; +import { + anyOf, + canRead, + isScopeLabel, + ownViewCondition, + readableConditions, + type Condition, + type Principal, +} from './scopes.ts'; import { getSettings } from './settings.ts'; const RRF_K = 60; @@ -63,6 +71,7 @@ export const VIEW_FIELDS = [ 'validUntil', 'withdrawnAt', 'withdrawnReason', + 'withdrawnBy', 'createdAt', 'updatedAt', ]; @@ -551,6 +560,8 @@ export async function bootstrapMemories(params: BootstrapParams, principal: Prin const active = { attribute: 'status', comparator: 'equals', value: STATUS_ACTIVE }; const unexpired = unexpiredCondition(new Date()); const readable = readableConditions(principal); + // A delegate's own view adds its principal's private scope, which it reads through labels, quarantine included. + const own = principal.actsFor === null ? [ownViewCondition(principal)] : [ownViewCondition(principal), ...readable]; const recentFirst = { attribute: 'updatedAt', descending: true }; // One lookup per flag source across every section. const access = new Map>(); @@ -599,7 +610,7 @@ export async function bootstrapMemories(params: BootstrapParams, principal: Prin conditions: [ active, unexpired, - { attribute: 'ownerId', comparator: 'equals', value: principal.id }, + ...own, { attribute: 'needsReviewSince', comparator: 'greater_than', value: new Date(0) }, ], sort: { attribute: 'needsReviewSince', descending: true }, @@ -638,7 +649,7 @@ export async function bootstrapMemories(params: BootstrapParams, principal: Prin collect( Memory.search( { - conditions: [active, unexpired, { attribute: 'ownerId', comparator: 'equals', value: principal.id }], + conditions: [active, unexpired, ...own], sort: recentFirst, select: VIEW_FIELDS, limit: BOOTSTRAP_RECENT_LIMIT, diff --git a/src/supersession.ts b/src/supersession.ts index 07adae9..8868e39 100644 --- a/src/supersession.ts +++ b/src/supersession.ts @@ -1,7 +1,7 @@ import { logger, models } from 'harper'; import { memoryError, notFound } from './errors.ts'; import { isMemoryId, memoryTable, STATUS_ACTIVE, STATUS_WITHDRAWN } from './lifecycle.ts'; -import { anyOf, canRead, readableConditions, type Principal } from './scopes.ts'; +import { actsAsOwner, anyOf, canRead, readableConditions, type Principal } from './scopes.ts'; import { DEFAULT_EMBEDDING_MODEL, getSettings } from './settings.ts'; import { assertReadable, @@ -149,7 +149,7 @@ export async function findCandidates( export async function memoryCandidates(id: string, principal: Principal, context: object): Promise { const record = isMemoryId(id) ? await memoryTable().get(id, context) : undefined; if (!record) throw notFound(); - if (record.ownerId !== principal.id && !principal.superUser) { + if (!actsAsOwner(record, principal) && !principal.superUser) { if (!canRead(record, principal)) throw notFound(); throw memoryError('Only the owner can list candidates for this memory', 403, 'not_memory_owner'); } diff --git a/test/delegation.test.js b/test/delegation.test.js new file mode 100644 index 0000000..09fd675 --- /dev/null +++ b/test/delegation.test.js @@ -0,0 +1,347 @@ +import { beforeEach, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { __test, databases } from 'harper'; +import { + MemoryActionResource, + MemoryBootstrapResource, + MemoryEventsResource, + MemoryItemResource, + MemoryMcpResource, + MemoryResource, +} from '../dist/resource.js'; +import { applySettings, parseSettings } from '../dist/settings.js'; + +// kris is the person; agent-a and agent-b are kris's agents (global only); carol is someone else. +const kris = { username: 'kris' }; +const agentA = { username: 'agent-a' }; +const agentB = { username: 'agent-b' }; +const cleared = { username: 'agent-c' }; +const carol = { username: 'carol' }; +const superUser = { username: 'root', role: { role: 'super_user', permission: { super_user: true } } }; + +const target = (query = '', params = {}) => Object.assign(new URLSearchParams(query), params); +const ctx = (user, revision) => ({ user, ...(revision !== undefined && { headers: { 'if-match': `"${revision}"` } }) }); +const parse = async (response) => ({ status: response.status, body: await response.json() }); +const stored = (id) => __test.stores.get('Memory').get(id); + +const grant = (id, read, write) => databases.memory.ScopeGrant.put({ id, read, write }); +const delegate = (id, actsFor) => databases.memory.Delegation.put({ id, actsFor }); +const revoke = (id) => databases.memory.Delegation.delete(id); + +const put = async (user, id, body, revision) => + parse(await MemoryItemResource.put(target('', { id }), body, ctx(user, revision))); +const get = async (user, id) => parse(await MemoryItemResource.get(target('', { id }), ctx(user))); +const withdraw = async (user, id, revision) => + parse(await MemoryItemResource.delete(target('', { id }), ctx(user, revision))); +const act = async (user, id, action, body = {}, revision) => + parse(await MemoryActionResource.post(target('', { id, action }), body, ctx(user, revision))); +const candidates = async (user, id) => + parse(await MemoryActionResource.get(target('', { id, action: 'candidates' }), ctx(user))); +const search = async (user, query = '') => parse(await MemoryResource.get(target(query, { rest: '' }), ctx(user))); +const bootstrap = async (user) => + parse(await MemoryBootstrapResource.get(target('budget=100000', { rest: '' }), ctx(user))); +const note = (title, extra = {}) => ({ title, content: `${title} body`, ...extra }); +const idOf = (tag) => `mem-dlg-${tag}`.padEnd(16, '_'); + +function collectEvents(stream) { + const received = []; + const done = (async () => { + for await (const event of stream) received.push(event); + })(); + return { + received, + async settle(ms = 30) { + await new Promise((resolve) => setTimeout(resolve, ms)); + }, + async close() { + stream.end(); + await done; + }, + }; +} + +beforeEach(async () => { + __test.reset(); + applySettings(parseSettings({ mcp: true })); + await grant('user:kris', ['global', 'customer:*'], ['global', 'customer:*']); + await grant('user:agent-a', ['global'], ['global']); + await grant('user:agent-b', ['global'], ['global']); + await grant('user:agent-c', ['global', 'customer:*'], ['global', 'customer:*']); + await grant('user:carol', ['global'], ['global']); + await delegate('agent-a', 'kris'); + await delegate('agent-b', 'kris'); + await delegate('agent-c', 'kris'); +}); + +describe('delegated edit', () => { + it("revises, confirms and withdraws the principal's memory as the principal would, recording the delegate", async () => { + const id = idOf('edit'); + assert.equal((await put(kris, id, note('imported finding', { visibility: 'shared' }))).status, 201); + + const revised = await put(agentA, id, { content: 'corrected by agent-a' }, 1); + assert.equal(revised.status, 200, JSON.stringify(revised.body)); + assert.equal(stored(id).ownerId, 'kris'); + assert.equal(stored(id).content, 'corrected by agent-a'); + assert.equal(stored(id).lastEditor.principalId, 'agent-a'); + + const confirmed = await act(agentB, id, 'confirm', {}, 2); + assert.equal(confirmed.status, 200, JSON.stringify(confirmed.body)); + assert.equal(stored(id).confirmed.by, 'agent-b'); + assert.equal(stored(id).lastEditor.principalId, 'agent-a'); + + const withdrawn = await withdraw(agentA, id, 3); + assert.equal(withdrawn.status, 200, JSON.stringify(withdrawn.body)); + assert.equal(withdrawn.body.memory.withdrawnBy, 'agent-a'); + assert.equal(stored(id).status, 'withdrawn'); + assert.equal(stored(id).ownerId, 'kris'); + assert.equal(stored(id).withdrawnBy, 'agent-a'); + assert.equal(stored(id).lastEditor.principalId, 'agent-a'); + // Withdrawn memories stay readable by their owner only: a delegate reads through labels. + assert.equal((await get(kris, id)).status, 200); + assert.equal((await get(agentA, id)).status, 404); + }); + + it("links and lists candidates for the principal's memories", async () => { + const older = idOf('older'); + const newer = idOf('newer'); + await put(kris, older, note('older', { visibility: 'shared' })); + await put(kris, newer, note('newer', { visibility: 'shared' })); + assert.equal((await candidates(agentA, newer)).status, 200); + const linked = await act(agentA, newer, 'supersedes', { ids: [older] }, 1); + assert.equal(linked.status, 200, JSON.stringify(linked.body)); + assert.equal(stored(older).supersededBy, newer); + assert.equal(stored(newer).ownerId, 'kris'); + }); + + it('refuses a principal without the row as before, and a revoked row from the next request', async () => { + const id = idOf('revoke'); + await put(kris, id, note('shared note', { visibility: 'shared' })); + assert.equal((await put(carol, id, { content: 'carol' }, 1)).status, 403); + assert.equal((await withdraw(carol, id, 1)).status, 403); + assert.equal((await act(carol, id, 'confirm')).status, 403); + assert.equal((await candidates(carol, id)).status, 403); + + assert.equal((await put(agentA, id, { content: 'before revoke' }, 1)).status, 200); + await revoke('agent-a'); + const refused = await put(agentA, id, { content: 'after revoke' }, 2); + assert.equal(refused.status, 403); + assert.equal(refused.body.code, 'not_memory_owner'); + assert.equal((await withdraw(agentA, id, 2)).status, 403); + assert.equal(stored(id).content, 'before revoke'); + }); + + it('does not reach a principal two delegations away', async () => { + await delegate('kris', 'boss'); + const id = idOf('chain'); + await put(superUser, id, note('boss note', { scopes: ['user:boss'] })); + await databases.memory.Memory.patch(id, { ownerId: 'boss' }); + assert.equal((await get(kris, id)).status, 200); + assert.equal((await get(agentA, id)).status, 404); + assert.equal((await put(agentA, id, { content: 'x' }, 1)).status, 409); + }); +}); + +describe("the principal's private scope", () => { + it("lands a delegate's private write in user:, owned by the principal and editable by its delegates", async () => { + const implicit = idOf('implicit'); + const explicit = idOf('explicit'); + assert.equal((await put(agentA, implicit, note('agent note'))).status, 201); + assert.equal((await put(agentA, explicit, note('agent private', { visibility: 'private' }))).status, 201); + for (const id of [implicit, explicit]) { + assert.deepEqual(stored(id).scopes, ['user:kris']); + assert.equal(stored(id).ownerId, 'kris'); + assert.equal(stored(id).author.principalId, 'agent-a'); + } + // An identical retry by the writer is still a retry. + assert.equal((await put(agentA, implicit, note('agent note'))).status, 200); + + assert.equal((await get(agentB, implicit)).status, 200); + assert.equal((await get(kris, implicit)).status, 200); + assert.equal((await get(carol, implicit)).status, 404); + assert.equal((await put(carol, implicit, { content: 'carol' }, 1)).status, 409); + assert.equal((await withdraw(carol, implicit, 1)).status, 404); + + assert.equal((await put(agentB, implicit, { content: 'agent-b edit' }, 1)).status, 200); + assert.equal((await put(kris, implicit, { content: 'kris edit' }, 2)).status, 200); + // A private shorthand on the principal's memory keeps resolving against the owner. + assert.equal((await put(agentB, explicit, { visibility: 'private', title: 'renamed' }, 1)).status, 200); + assert.deepEqual(stored(explicit).scopes, ['user:kris']); + + const ids = (response) => response.body.memories.map((memory) => memory.id).sort(); + assert.deepEqual(ids(await search(agentB)), [explicit, implicit].sort()); + assert.deepEqual(ids(await search(kris)), [explicit, implicit].sort()); + assert.deepEqual(ids(await search(carol)), []); + }); + + it("keeps a delegate's shared, mixed and own-private creates its own", async () => { + const shared = idOf('shared'); + const mixed = idOf('mixed'); + const own = idOf('own'); + assert.equal((await put(agentA, shared, note('shared', { visibility: 'shared' }))).status, 201); + assert.equal((await put(agentA, mixed, note('mixed', { scopes: ['user:kris', 'global'] }))).status, 201); + assert.equal((await put(agentA, own, note('own', { scopes: ['user:agent-a'] }))).status, 201); + assert.equal(stored(shared).ownerId, 'agent-a'); + assert.equal(stored(mixed).ownerId, 'agent-a'); + assert.deepEqual(stored(own).scopes, ['user:agent-a']); + assert.equal(stored(own).ownerId, 'agent-a'); + assert.equal((await get(agentB, own)).status, 404); + assert.equal((await put(agentB, mixed, { content: 'agent-b' }, 1)).status, 403); + }); + + it('loses user: with the row', async () => { + const id = idOf('private-revoke'); + await put(agentB, id, note('family note')); + assert.equal((await get(agentA, id)).status, 200); + await revoke('agent-a'); + assert.equal((await get(agentA, id)).status, 404); + assert.equal( + (await put(agentA, idOf('after'), note('x', { scopes: ['user:kris'] }))).body.code, + 'scope_not_writable', + ); + }); +}); + +describe('labels stay gated by the delegate’s own grants', () => { + it("denies a global-only delegate the principal's customer memory everywhere", async () => { + const id = idOf('customer'); + await put(kris, id, note('acme incident', { scopes: ['customer:acme'] })); + await put(kris, idOf('replacement'), note('replacement', { scopes: ['customer:acme'] })); + assert.equal((await get(agentA, id)).status, 404); + assert.equal((await put(agentA, id, { content: 'x' }, 1)).status, 409); + assert.equal((await withdraw(agentA, id, 1)).status, 404); + assert.equal((await act(agentA, id, 'confirm')).status, 404); + assert.equal((await candidates(agentA, id)).status, 404); + assert.equal((await act(agentA, idOf('replacement'), 'supersedes', { ids: [id] }, 1)).status, 404); + assert.deepEqual((await search(agentA)).body.memories, []); + assert.equal((await get(cleared, id)).status, 200); + assert.equal((await put(cleared, id, { content: 'cleared edit' }, 1)).status, 200); + }); + + it('hides a content-flagged memory of the principal from an uncleared delegate', async () => { + applySettings( + parseSettings({ + mcp: true, + customerContentCheck: { patterns: { hosts: [{ label: 'acme-db', host: 'db.acme.test' }] } }, + }), + ); + const id = idOf('flagged'); + await put(kris, id, note('outage on db.acme.test', { visibility: 'shared' })); + assert.ok(stored(id).contentFlag); + assert.equal((await get(agentA, id)).status, 404); + assert.equal((await put(agentA, id, { content: 'scrubbed' }, 1)).status, 409); + assert.equal((await get(cleared, id)).status, 200); + }); +}); + +describe('refusal guidance', () => { + it('names the supersede route on the revise 403, over HTTP and MCP', async () => { + const id = idOf('guidance'); + await put(kris, id, note('kris note', { visibility: 'shared' })); + const refused = await put(carol, id, { content: 'carol edit' }, 1); + assert.equal(refused.status, 403); + assert.match(refused.body.error, new RegExp(`supersedes: \\["${id}"\\]`)); + + const resource = new MemoryMcpResource(); + await assert.rejects( + () => resource.mcpRevise({ id, revision: 1, content: 'carol edit' }, { user: carol }), + (error) => error.statusCode === 403 && error.code === 'not_memory_owner' && error.message.includes(id), + ); + const revise = MemoryMcpResource.mcpTools.find((tool) => tool.name === 'revise'); + assert.match(revise.description, /supersedes/); + assert.deepEqual(await resource.mcpRevise({ id, revision: 1, content: 'agent edit' }, { user: agentA }), { + id, + revision: 2, + created: false, + candidates: [], + scopes: ['global'], + status: 'active', + contentFlag: null, + needsReview: null, + }); + }); +}); + +describe("a delegate's own view", () => { + it("bootstraps the principal's private notes beside the delegate's own, not the principal's shared corpus", async () => { + await put(kris, idOf('corpus'), note('imported shared', { visibility: 'shared' })); + await put(agentB, idOf('family'), note('family private note')); + await put(agentA, idOf('mine'), note('agent-a shared', { visibility: 'shared' })); + const recent = (await bootstrap(agentA)).body.memories + .filter((memory) => memory.section === 'recent') + .map((memory) => memory.id) + .sort(); + assert.deepEqual(recent, [idOf('family'), idOf('mine')].sort()); + const carolRecent = (await bootstrap(carol)).body.memories.filter((memory) => memory.section === 'recent'); + assert.deepEqual(carolRecent, []); + }); + + it("lists the principal's flagged private notes for review and delivers their flag events", async () => { + const source = idOf('source'); + const citer = idOf('citer'); + await put(kris, source, note('source', { visibility: 'shared' })); + await put(agentB, citer, note('private conclusion', { evidence: [{ kind: 'memory', ref: source }] })); + const events = collectEvents(await MemoryEventsResource.connect(target(''), null, ctx(agentA))); + await withdraw(kris, source, 1); + await events.settle(); + await events.close(); + assert.deepEqual(events.received, [{ id: citer, kind: 'flagged', revision: 2 }]); + const review = (await bootstrap(agentA)).body.memories.filter((memory) => memory.section === 'needsReview'); + assert.deepEqual( + review.map((memory) => memory.id), + [citer], + ); + }); + + it('stops live events for user: once the row is revoked', async () => { + const id = idOf('live'); + const events = collectEvents(await MemoryResource.subscribe(target('', { rest: '' }), ctx(agentA))); + await put(kris, id, note('kris private')); + await events.settle(); + await revoke('agent-a'); + await events.settle(); + await put(kris, id, { content: 'kris private v2' }, 1); + await events.settle(); + await events.close(); + assert.deepEqual(events.received, [{ id, kind: 'created', revision: 1 }]); + }); +}); + +describe('subscriber principal cache', () => { + it('does not cache a resolution that started before a grant change', async () => { + await grant('user:carol', ['global', 'team:eng'], ['global']); + await grant('user:kris', ['global', 'team:eng'], ['global', 'team:eng']); + const ScopeGrant = databases.memory.ScopeGrant; + const originalGet = ScopeGrant.get; + let release; + const gate = new Promise((resolve) => (release = resolve)); + let armed = false; + let held = false; + ScopeGrant.get = async function (id, context) { + const row = await originalGet.call(this, id, context); + if (armed && id === 'user:carol' && !held) { + held = true; + await gate; + } + return row; + }; + try { + const id = idOf('fence'); + const events = collectEvents(await MemoryResource.subscribe(target('', { rest: '' }), ctx(carol))); + armed = true; + await put(kris, id, note('team note', { scopes: ['team:eng'] })); + await events.settle(); + assert.ok(held, 'delivery should be resolving carol'); + await grant('user:carol', ['global'], ['global']); + await events.settle(); + release(); + await events.settle(); + await put(kris, id, { content: 'team note v2' }, 1); + await events.settle(); + await events.close(); + assert.ok(!events.received.some((event) => event.revision === 2), JSON.stringify(events.received)); + } finally { + ScopeGrant.get = originalGet; + release(); + } + }); +}); diff --git a/test/helpers/harper-stub.mjs b/test/helpers/harper-stub.mjs index 9738a7d..4d09982 100644 --- a/test/helpers/harper-stub.mjs +++ b/test/helpers/harper-stub.mjs @@ -103,17 +103,19 @@ class StubTable { #rows(context) { return context?.transaction?.rows.get(this.name) ?? stores.get(this.name); } - #stageWrite(record, context) { + #stageWrite(record, context, type = 'put') { + const event = { id: record.id, type, value: type === 'delete' ? undefined : structuredClone(record) }; if (context?.transaction) { - context.transaction.writes.get(this.name).push({ id: record.id, value: structuredClone(record) }); + context.transaction.writes.get(this.name).push(event); } else { - this.#emitWrite({ id: record.id, value: structuredClone(record) }); + this.#emitWrite(event); } } #emitWrite(event) { for (const sub of subscribers.get(this.name)) { if (sub.id !== undefined && sub.id !== event.id) continue; - sub.push({ id: event.id, type: 'put', value: Object.freeze(structuredClone(event.value)) }); + const value = event.value === undefined ? undefined : Object.freeze(structuredClone(event.value)); + sub.push({ id: event.id, type: event.type ?? 'put', value }); } } emitCommittedWrites(writes) { @@ -160,7 +162,9 @@ class StubTable { this.#stageWrite(next, context); } async delete(id, context) { - return this.#rows(context).delete(id); + const deleted = this.#rows(context).delete(id); + if (deleted) this.#stageWrite({ id }, context, 'delete'); + return deleted; } async subscribe(options = {}) { const buffer = []; @@ -241,6 +245,7 @@ export const databases = { MemoryPin: new StubTable('MemoryPin'), MemoryWatch: new StubTable('MemoryWatch'), ScopeGrant: new StubTable('ScopeGrant'), + Delegation: new StubTable('Delegation'), }, }; export const tables = {}; diff --git a/test/principal.test.js b/test/principal.test.js index 15d3769..083db38 100644 --- a/test/principal.test.js +++ b/test/principal.test.js @@ -27,6 +27,7 @@ describe('resolvePrincipal', () => { id: 'alice', superUser: false, source: 'harper', + actsFor: null, read: ['user:alice', 'team:a', 'global', 'customer:*'], write: ['user:alice', 'team:a', 'global'], }); @@ -80,6 +81,7 @@ describe('resolvePrincipal', () => { id: 'reflex-svc', superUser: false, source: 'api-key', + actsFor: null, read: ['user:reflex-svc', 'global', 'team:*'], write: ['user:reflex-svc'], }); @@ -143,6 +145,65 @@ describe('resolvePrincipal', () => { }); }); +describe('delegation', () => { + const delegate = (id, actsFor) => databases.memory.Delegation.put({ id, actsFor }); + + it('reads the Delegation row on every call, so a revoked delegation is gone from the next principal', async () => { + await grant('user:agent-a', ['global'], ['global']); + await delegate('agent-a', 'kris'); + const acting = await resolvePrincipal(member('agent-a')); + assert.equal(acting.actsFor, 'kris'); + assert.deepEqual(acting.read, ['user:agent-a', 'user:kris', 'global']); + assert.deepEqual(acting.write, ['user:agent-a', 'user:kris', 'global']); + await databases.memory.Delegation.delete('agent-a'); + const revoked = await resolvePrincipal(member('agent-a')); + assert.equal(revoked.actsFor, null); + assert.deepEqual(revoked.read, ['user:agent-a', 'global']); + }); + + it('ignores a malformed row and a row for super_user', async () => { + await delegate('agent-a', 'not:valid'); + assert.equal((await resolvePrincipal(member('agent-a'))).actsFor, null); + await delegate('agent-a', 7); + assert.equal((await resolvePrincipal(member('agent-a'))).actsFor, null); + await delegate('root', 'kris'); + assert.equal((await resolvePrincipal(superUser)).actsFor, null); + }); + + it("takes a custom resolver's actsFor, and the row's through next()", async () => { + await delegate('agent-a', 'kris'); + setPrincipalResolver((context, next) => + context.headers?.['x-api-key'] ? { id: 'svc-agent', actsFor: 'kris', source: 'api-key' } : next(), + ); + assert.equal((await resolvePrincipal({ headers: { 'x-api-key': 'k' } })).actsFor, 'kris'); + assert.equal((await resolvePrincipal(member('agent-a'))).actsFor, 'kris'); + }); + + it('reads the row in a context of its own and rejects with the original error when the read fails', async () => { + const Delegation = databases.memory.Delegation; + const originalGet = Delegation.get; + const contexts = []; + Delegation.get = function (id, context) { + contexts.push(context); + return originalGet.call(this, id, context); + }; + const caller = { ...member('agent-a'), authorize: true }; + try { + await resolvePrincipal(caller); + assert.equal(contexts.length, 1); + assert.equal(contexts[0].authorize, false); + assert.equal(caller.authorize, true); + const outage = new Error('storage unavailable'); + Delegation.get = async () => { + throw outage; + }; + await assert.rejects(resolvePrincipal(member('agent-a')), (error) => error === outage); + } finally { + Delegation.get = originalGet; + } + }); +}); + describe('canReadLabels', () => { async function principalWith(read) { await grant('user:pat', read); diff --git a/test/scopes.test.js b/test/scopes.test.js index ddd456d..0ee080d 100644 --- a/test/scopes.test.js +++ b/test/scopes.test.js @@ -1,10 +1,13 @@ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { + actsAsOwner, assertWritable, canRead, compileMatcher, createPrincipal, + createScopesAndOwner, + inOwnView, isSuperset, matches, MAX_GRANT_PATTERNS, @@ -283,3 +286,83 @@ describe('the customer-content quarantine', () => { assert.equal(reviewsCustomerContent(principal('root', [], [], true)), true); }); }); + +describe('delegation', () => { + const agent = (read = ['global'], write = ['global']) => + createPrincipal({ id: 'agent-a', actsFor: 'kris', grants: { read, write } }); + + it("adds the principal's private label to both matchers, outside the pattern cap", () => { + const delegate = agent(); + assert.equal(delegate.actsFor, 'kris'); + assert.deepEqual(delegate.read, ['user:agent-a', 'user:kris', 'global']); + assert.deepEqual(delegate.write, ['user:agent-a', 'user:kris', 'global']); + assert.ok(!matches(delegate.read, 'user:bob')); + + const many = Array.from({ length: MAX_GRANT_PATTERNS + 5 }, (_, i) => `team:t${i}`); + const capped = compileMatcher(many, 'agent-a', 'kris'); + assert.equal(capped.matcher.exact.size, MAX_GRANT_PATTERNS + 2); + assert.equal(capped.rejected.length, 5); + }); + + it('ignores an actsFor that is not a valid principal id, or names the principal itself', () => { + for (const actsFor of [42, '', 'a:b', 'two words', 'team*', 'agent-a', 'x'.repeat(123), { id: 'kris' }]) { + const reported = []; + const delegate = createPrincipal({ id: 'agent-a', actsFor }, (value, kind) => reported.push([value, kind])); + assert.equal(delegate.actsFor, null, JSON.stringify(actsFor)); + assert.deepEqual(delegate.read, ['user:agent-a']); + assert.deepEqual(reported, [[actsFor, 'actsFor']]); + } + assert.equal(createPrincipal({ id: 'agent-a', actsFor: null }).actsFor, null); + }); + + it("searches the principal's private label exactly, and never by the principal's ownership", () => { + const [labels] = readableConditions(agent()); + assert.deepEqual(labels.conditions, [ + { attribute: 'ownerId', comparator: 'equals', value: 'agent-a' }, + { attribute: 'scopes', comparator: 'equals', value: 'user:agent-a' }, + { attribute: 'scopes', comparator: 'equals', value: 'user:kris' }, + { attribute: 'scopes', comparator: 'equals', value: 'global' }, + ]); + }); + + it('edits as the owner only what it can read through its labels', () => { + const delegate = agent(); + const owned = { ownerId: 'kris', status: 'active' }; + assert.ok(actsAsOwner({ ...owned, scopes: ['global'] }, delegate)); + assert.ok(actsAsOwner({ ...owned, scopes: ['user:kris'] }, delegate)); + assert.ok(actsAsOwner({ ownerId: 'agent-a', scopes: ['customer:x'], status: 'active' }, delegate)); + assert.ok(!actsAsOwner({ ...owned, scopes: ['customer:x'] }, delegate)); + assert.ok(!actsAsOwner({ ...owned, scopes: ['global'], status: 'withdrawn' }, delegate)); + assert.ok(!actsAsOwner({ ...owned, scopes: ['global'], contentFlag: { kind: 'x' } }, delegate)); + assert.ok(!actsAsOwner({ ownerId: 'bob', scopes: ['global'], status: 'active' }, delegate)); + assert.ok(!actsAsOwner({ ...owned, scopes: ['global'] }, principal('carol', ['global']))); + }); + + it("puts a delegate's private create in its principal's scope, owned by the principal only when exactly private", () => { + const delegate = agent(); + assert.deepEqual(createScopesAndOwner(undefined, undefined, delegate), { scopes: ['user:kris'], ownerId: 'kris' }); + assert.deepEqual(createScopesAndOwner(undefined, 'private', delegate), { scopes: ['user:kris'], ownerId: 'kris' }); + assert.deepEqual(createScopesAndOwner(['user:kris'], undefined, delegate), { + scopes: ['user:kris'], + ownerId: 'kris', + }); + assert.equal(createScopesAndOwner(['user:kris', 'global'], undefined, delegate).ownerId, 'agent-a'); + assert.equal(createScopesAndOwner(undefined, 'shared', delegate).ownerId, 'agent-a'); + assert.deepEqual(createScopesAndOwner(['user:agent-a'], undefined, delegate), { + scopes: ['user:agent-a'], + ownerId: 'agent-a', + }); + assert.deepEqual(createScopesAndOwner(undefined, undefined, principal('carol')), { + scopes: ['user:carol'], + ownerId: 'carol', + }); + }); + + it("counts the principal's private scope as the delegate's own view", () => { + const delegate = agent(); + assert.ok(inOwnView({ ownerId: 'agent-a', scopes: ['global'] }, delegate)); + assert.ok(inOwnView({ ownerId: 'kris', scopes: ['user:kris'] }, delegate)); + assert.ok(!inOwnView({ ownerId: 'kris', scopes: ['global'] }, delegate)); + assert.ok(!inOwnView({ ownerId: 'kris', scopes: ['user:kris'] }, principal('carol'))); + }); +}); From f505fd0a566b387aea136893155641d04dcb2a3e Mon Sep 17 00:00:00 2001 From: Kris Zyp Date: Mon, 16 Nov 2026 13:36:15 -0700 Subject: [PATCH 2/9] Document delegation in DESIGN.md, README, deploy notes and changelog Co-Authored-By: Claude Opus 5.5 Dispatch-Task: agent-memory-55-delegation --- CHANGELOG.md | 16 ++++++++ DESIGN.md | 71 ++++++++++++++++++++++++------------ README.md | 12 ++++-- deploy/engineering/README.md | 4 ++ 4 files changed, 77 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fde803..94add06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ All notable changes to `@harperfast/agent-memory` are documented here. The forma ### Fixed +- Live updates: a principal resolution that started before a `ScopeGrant` change is no longer cached after it, so a + revoked grant stops event delivery on the next event instead of up to 5 s later. + - Claude Code plugin: session start injects every entry the server packed, in the server's order, within `AGENT_MEMORY_BOOTSTRAP_BUDGET`, for entries whose metadata is within its framing estimate. It sends that estimate as `entryOverhead` and `sectionItemOverhead`, so the server packs only what fits; before, about 40% of the entries were dropped at the default budget, because @@ -20,6 +23,19 @@ All notable changes to `@harperfast/agent-memory` are documented here. The forma ### Added +- Delegation ([#55](https://github.com/HarperFast/agent-memory/issues/55)): a `Delegation` row + `{ id: , actsFor: }` lets a person's agent users act for the person. A delegate may revise, + withdraw, confirm, link and list candidates for the principal's memories (`ownerId` stays the principal; `lastEditor`, + `confirmed.by` and the new `withdrawnBy` name the delegate) and reads and writes `user:`: its private + writes land there, owned by the principal, so the principal and every other delegate can edit them. A delegate + still reads only through labels, so it never reaches a memory its own grants do not. The row is read on every + request, and deleting it revokes the delegation on the next one. `resolvePrincipal` returns `actsFor`, and a custom + principal resolver may return it. +- A delegate's bootstrap `recent` and `needsReview` sections, and its `/MemoryEvents` flag notices, include memories in + its principal's private scope. +- The `403 not_memory_owner` from a revise (HTTP and the MCP `revise` tool) names the route left: a merged replacement + with `supersedes: [id]`. +- `withdrawnBy`: the principal that withdrew a memory. - `GET /Memory/bootstrap?entryOverhead=§ionItemOverhead=`: characters a client adds around each memory and each contributed section item it renders (`0..10000`, default `0`; `sectionItemOverhead` defaults to `entryOverhead`). Each packed entry is charged title + content + its overhead, so a client that frames entries can ask for its exact diff --git a/DESIGN.md b/DESIGN.md index ec51541..601894f 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -39,6 +39,7 @@ allowlists, idempotent `PUT` create/revise with `If-Match` revision precondition | Supersession backfill: candidates for an existing memory, links between existing memories, created-order cursor | implemented (`src/lifecycle.ts`) | | Package exports reaching the plugin from another app (Extension points, Across apps) | implemented (`src/runtime.ts`) | | `scanMemories`, `getMemories`, bootstrap sections and search annotators for derived plugins (Extension points) | implemented (`src/extensions.ts`) | +| Delegation: one principal acting for another (Identity, Scopes and grants) | implemented (`src/scopes.ts`) | ## Data model @@ -64,6 +65,7 @@ database). caps and flag from one settings snapshot (`EmbeddingSettings`); the table embedder truncates only a row recorded under the configured `embeddingModel`. - `ScopeGrant` — read/write scope patterns held by a Harper role or user. +- `Delegation` — the principal a delegate acts for (Identity), keyed by the delegate's principal id. - `MemoryPin` — a principal's pinned memories (`:`), loaded first at session bootstrap. - `MemoryWatch` — a principal's time-bounded interest in specific memories (live updates). @@ -73,7 +75,7 @@ See `schema/memory.graphql`. The table is not `@export`ed: every read and write Server-owned fields: `ownerId`, `status`, `revision`, `author`, `lastEditor`, `supersededBy`, `autoSupersedes`, `evidenceMemoryIds`, `needsReview`, `needsReviewSince`, `confirmed`, `contentFlag`, -`contentFlagged`, `scopeConfirmed`, `createdAt`, `embeddingModel`, `lastEventKind`. `createdAt` is set by the lifecycle rather than `@createdTime`, because Harper's +`contentFlagged`, `scopeConfirmed`, `withdrawnBy`, `createdAt`, `embeddingModel`, `lastEventKind`. `createdAt` is set by the lifecycle rather than `@createdTime`, because Harper's `@createdTime` overwrites a supplied value on insert and import must preserve it. `updatedAt` stays `@updatedTime`. `needsReviewSince` mirrors `needsReview.since` because Harper does not index object values; `lastEventKind` records the lifecycle event kind (`created`, `revised`, `superseded`, `withdrawn`, @@ -110,6 +112,16 @@ source? }`, or `undefined` for unauthenticated. `next()` is the default Harper-u Principal ids must not contain whitespace, `:` or `*`, and are capped at 122 characters, so that `user:` fits a 128-character scope label. +**Delegation.** A person often reaches the plugin through several principals: their own user (owning history +imported for them) and one agent user per machine. A `Delegation` row `{ id: , actsFor: }` +lets the delegate act for the principal: edit the principal's memories and share its private scope (Scopes and +grants). Keyed by the delegate, so a principal acts for at most one other and its private writes have one +destination; only the caller's own row is read, so it is not transitive. The default resolution reads it with the +grants on every request, so deleting it takes effect on the next request; a custom resolver returns `actsFor` +itself. An `actsFor` naming the principal itself, or not a valid principal id, grants nothing and is logged. +Delegation never merges the two principals: `author`, `lastEditor`, `confirmed.by` and `withdrawnBy` name the +delegate, and the delegate keeps its own grants and `user:`. + Memory ids are client-chosen (`^[A-Za-z0-9_-]{16,64}$`; clients normally generate a UUID) and share one table-wide namespace across all owners rather than per-owner id namespaces. Because `PUT /Memory/` creates when the id is absent, a `PUT` to an existing id that the caller cannot read answers `409 @@ -134,12 +146,13 @@ caller's readable set. To restrict content, use one specific label (`customer:ac Grants are `ScopeGrant` rows keyed `role:` or `user:`, with `read` and `write` pattern lists. A pattern is an exact label or a namespace wildcard (`customer:*`); a wildcard never -covers the bare `global`. Every principal implicitly reads and writes `user:`, and no grant -reaches into the `user` namespace: `user:` means the owner only, so a pattern such as `user:*` or -`user:bob` is ignored rather than quietly opening private memories (reading everything is what -`super_user` is for). `super_user` reads and writes everything. Grant rows are read on every request, -so revoking one takes effect on the next request. An invalid pattern grants nothing and is logged; at -most 256 patterns per principal count, which bounds the condition every search carries. +covers the bare `global`. Every principal implicitly reads and writes `user:`, a delegate also +`user:`, and no grant reaches into the `user` namespace: `user:` means the owner and its +delegates only, so a pattern such as `user:*` or `user:bob` is ignored rather than quietly opening private +memories (reading everything is what `super_user` is for). `super_user` reads and writes everything. Grant rows +are read on every request, so revoking one takes effect on the next request. An invalid pattern grants nothing +and is logged; at most 256 patterns per principal count (the implicit `user:` labels do not), which bounds the +condition every search carries. Rules: @@ -154,10 +167,16 @@ Rules: 2. **Write scopes**: creating or revising with scopes `S` requires every label of `S` to be writable by the caller — the resulting scopes, so revising a memory that stays `global` needs `global` write. `visibility: "private" | "shared"` is shorthand for `[user:]` / `[global]`; explicit - `scopes` wins when both are given. Withdrawal is exempt. -3. **Edit**: only the owner (or `super_user`) revises or withdraws, apart from the customer-content review - (rule 4). Read access never grants edit; a - reader that is not the owner gets 403 (`not_memory_owner`), and a non-reader gets 404 on `DELETE` + `scopes` wins when both are given. Withdrawal is exempt. A delegate's private create goes to + `[user:]`, and a create whose scopes are exactly that is owned by the principal, so the principal and + its other delegates can edit it; any other create is owned by its writer (`createScopesAndOwner`), which keeps an + uncleared writer able to read, and so fix, its own content-flagged write. +3. **Edit**: only the owner, a principal acting for the owner, or `super_user` revises, withdraws, confirms, + links or lists candidates, apart from the customer-content review (rule 4). A delegate must still read the + memory through its labels (`actsAsOwner`): delegation never adds the owner's other labels or the owner's + ownership-based reads (withdrawn, content-flagged), so a delegate that cannot read gets what a stranger gets. + Read access never grants edit; a reader that is not the owner gets 403 (`not_memory_owner`; on a revise it + names the route left, a merged replacement with `supersedes: [id]`), and a non-reader gets 404 on `DELETE` or 409 `id_unavailable` on `PUT`. 4. **Supersede, review flags and customer-content review**: see below. They are the only writes that touch another principal's memory: a supersede changes only status fields (`status`, `supersededBy`, `revision`), @@ -166,8 +185,8 @@ Rules: confirm-scope changes only the content flag, `scopeConfirmed` and `revision`. 5. **Search pushes the readable set into the query**, applied before the limit in every lane, never as a post-filter on a top-k. The set compiles to conditions (`src/scopes.ts` `readableConditions`): - an `or` of `ownerId = self`, `scopes =