diff --git a/docs/design.md b/docs/design.md index c81fce4..0657d77 100644 --- a/docs/design.md +++ b/docs/design.md @@ -88,6 +88,7 @@ Notes: - **Primary record + typed referencing records**, the same shape atproto itself uses (post + replies + likes). The goal author edits their own goal record (atproto records are owner-mutable, so goal closure is just an owner edit); everyone else contributes requests, artifacts, reviews, messages that reference it. Materialization is a deterministic fold over typed records, not op replay. - **Records are immutable by convention**; goal closure and claim lease renewal are the sanctioned exceptions. atproto owners *can* rewrite records in place, so materializers keep the earliest repo revision they observe, independent of arrival order, and flag other CID changes on the same record as edit annotations — a review's pinned strongref stays meaningful even if the PDS now serves different bytes. +- **A project's `autoReview` map is mutated via standalone `com.disnetdev.radial.setAutoReview` records** (admin-authored, `{project, type, enabled}`), folded latest-wins per type over the project record's own field — never by editing the project record, which is strongref-pinned and would drop the edit (the fold keeps its earliest CID). Same primary-record-plus-standalone-edit divergence as archiving a goal via a standalone `archiveGoal` record rather than an owner edit. - **Large bodies overflow to blobs.** atproto records have size ceilings; an artifact `body` that exceeds them is stored as a blob, with the record carrying a summary and the blob ref. - **Artifact types are data, not lexicon.** `plan` and `implementation` ship as built-ins; a space admin adds `security-review` or `architecture-diagram` by writing a registry record with a brief template and expected output shape. New capabilities are configuration, and the UI grows a button, not a schema. - **Scope is a property of the type.** Registry types declare where their deliverables live: `goal` (the default — plans, implementations) or `project` — **system artifacts** (architecture docs, ADRs) that outlive any one goal and collect in the UI's System section (§8). A request's goal-or-project reference matches its type's scope; `basedOn` carries cross-links between scopes. diff --git a/packages/core/src/generated/records.ts b/packages/core/src/generated/records.ts index bdbe61a..d62467f 100644 --- a/packages/core/src/generated/records.ts +++ b/packages/core/src/generated/records.ts @@ -28,6 +28,7 @@ export const COLLECTIONS = { removeMember: "com.disnetdev.radial.removeMember", retractRequest: "com.disnetdev.radial.retractRequest", review: "com.disnetdev.radial.review", + setAutoReview: "com.disnetdev.radial.setAutoReview", space: "com.disnetdev.radial.space", } as const @@ -187,6 +188,14 @@ export interface ReviewRecord { createdAt: string } +export interface SetAutoReviewRecord { + $type: "com.disnetdev.radial.setAutoReview" + project: StrongRef + type: string + enabled: boolean + createdAt: string +} + export interface SpaceRecord { $type: "com.disnetdev.radial.space" name: string @@ -210,6 +219,7 @@ export interface RecordByCollection { [COLLECTIONS.removeMember]: RemoveMemberRecord [COLLECTIONS.retractRequest]: RetractRequestRecord [COLLECTIONS.review]: ReviewRecord + [COLLECTIONS.setAutoReview]: SetAutoReviewRecord [COLLECTIONS.space]: SpaceRecord } @@ -1033,6 +1043,42 @@ export const lexiconSchemas = [ } } }, + { + "lexicon": 1, + "id": "com.disnetdev.radial.setAutoReview", + "defs": { + "main": { + "type": "record", + "key": "tid", + "record": { + "type": "object", + "required": [ + "project", + "type", + "enabled", + "createdAt" + ], + "properties": { + "project": { + "type": "ref", + "ref": "com.atproto.repo.strongRef" + }, + "type": { + "type": "string", + "maxLength": 100 + }, + "enabled": { + "type": "boolean" + }, + "createdAt": { + "type": "string", + "format": "datetime" + } + } + } + } + } + }, { "lexicon": 1, "id": "com.disnetdev.radial.space", diff --git a/packages/core/src/materializer.ts b/packages/core/src/materializer.ts index 5d2bae0..bdafa9f 100644 --- a/packages/core/src/materializer.ts +++ b/packages/core/src/materializer.ts @@ -15,6 +15,7 @@ import { type RemoveMemberRecord, type RetractRequestRecord, type ReviewRecord, + type SetAutoReviewRecord, type SpaceRecord, type StrongRef, } from './generated/records.js' @@ -77,6 +78,12 @@ export interface GoalView extends TargetView { export interface ProjectView extends TargetView { currentSystemArtifacts: Array> + // Per-artifact-type auto-review defaults for this project. The base is the project record's own + // `autoReview` field; standalone trusted `setAutoReview` records (admin-authored, latest-wins per + // type) overlay it — the same primary-record-plus-standalone-edit divergence as goal archiving via + // `archiveGoal`, chosen because rewriting the project record would drop the edit (store keeps the + // earliest CID) and break every strongref pinning the project by uri#cid. + autoReview: Record } export interface MaterializedIndex { @@ -542,6 +549,27 @@ export function materialize(store: RecordStore, options: MaterializeOptions): Ma [...archiveByGoal].filter(([, archive]) => archive.value.archived === true).map(([uri]) => uri), ) + // A project's per-type auto-review default is overlaid by standalone `setAutoReview` records so + // the setting can change without rewriting the (strongref-pinned) project record. Unlike + // `archiveGoal`, this is admin-only (like the artifactType registry): only an admin governs which + // types auto-review. Matched by exact project uri#cid — projects resolve strictly, so an edit that + // mints a new project cid simply orphans stale overlays. "Latest" per (project.uri, type) is by + // (createdAt, uri). Non-admin records fall through to the unassociated/ignored diagnostic below. + const autoReviewByProject = new Map>>() + const associatedAutoReviewUris: string[] = [] + for (const record of trust.records) { + if (record.collection !== COLLECTIONS.setAutoReview || record.authorRole !== 'admin') continue + const setting = record.value as SetAutoReviewRecord + if (!projectByRef.has(refKey(setting.project))) continue + associatedAutoReviewUris.push(record.uri) + const byType = autoReviewByProject.get(setting.project.uri) ?? new Map() + const current = byType.get(setting.type) + if (!current || compareRecord(current, record) < 0) { + byType.set(setting.type, record as IndexedRecord) + } + autoReviewByProject.set(setting.project.uri, byType) + } + const reviews = trust.records.filter( (record): record is IndexedRecord => record.collection === COLLECTIONS.review && @@ -617,9 +645,18 @@ export function materialize(store: RecordStore, options: MaterializeOptions): Ma .map((project) => { const view = buildView(makeInput(project)) const currentUris = new Set(view.artifactChains.map((chain) => chain.current)) + const base = + project.value.autoReview && typeof project.value.autoReview === 'object' + ? (project.value.autoReview as Record) + : {} + const overlay: Record = {} + for (const [type, record] of autoReviewByProject.get(project.uri) ?? []) { + overlay[type] = record.value.enabled + } return { ...view, currentSystemArtifacts: view.artifacts.filter((artifact) => currentUris.has(artifact.uri)), + autoReview: { ...base, ...overlay }, } }) .sort((a, b) => a.target.uri.localeCompare(b.target.uri)) @@ -638,6 +675,7 @@ export function materialize(store: RecordStore, options: MaterializeOptions): Ma ...messages.map((record) => record.uri), ...associatedRetractUris, ...associatedArchiveUris, + ...associatedAutoReviewUris, ]) const membershipCollections: string[] = [COLLECTIONS.addMember, COLLECTIONS.removeMember] const unassociated = trust.records diff --git a/packages/core/test/fixtures/invalid-records.json b/packages/core/test/fixtures/invalid-records.json index 7717217..5d9c4d8 100644 --- a/packages/core/test/fixtures/invalid-records.json +++ b/packages/core/test/fixtures/invalid-records.json @@ -9,6 +9,7 @@ "com.disnetdev.radial.claim": {"$type":"com.disnetdev.radial.claim","request":{"uri":"at://x","cid":"x"},"expiresAt":"bad","createdAt":"bad"}, "com.disnetdev.radial.retractRequest": {"$type":"com.disnetdev.radial.retractRequest","request":{"uri":"nope","cid":""},"createdAt":"bad"}, "com.disnetdev.radial.archiveGoal": {"$type":"com.disnetdev.radial.archiveGoal","goal":{"uri":"nope","cid":""},"archived":"yes","createdAt":"bad"}, + "com.disnetdev.radial.setAutoReview": {"$type":"com.disnetdev.radial.setAutoReview","project":{"uri":"nope","cid":""},"type":"plan","enabled":"yes","createdAt":"bad"}, "com.disnetdev.radial.artifact": {"$type":"com.disnetdev.radial.artifact","request":{"uri":"at://x","cid":"x"},"type":"plan","body":"x","links":{},"createdAt":"bad"}, "com.disnetdev.radial.review": {"$type":"com.disnetdev.radial.review","subject":{"uri":"at://x","cid":"x"},"verdict":"maybe","findings":[],"createdAt":"bad"}, "com.disnetdev.radial.checkrun": {"$type":"com.disnetdev.radial.checkrun","artifact":{"uri":"at://x","cid":"x"},"commit":"x","results":[],"createdAt":"bad"}, diff --git a/packages/core/test/fixtures/valid-records.json b/packages/core/test/fixtures/valid-records.json index 79da267..74d763b 100644 --- a/packages/core/test/fixtures/valid-records.json +++ b/packages/core/test/fixtures/valid-records.json @@ -72,6 +72,13 @@ "archived": true, "createdAt": "2026-01-01T00:00:07Z" }, + "com.disnetdev.radial.setAutoReview": { + "$type": "com.disnetdev.radial.setAutoReview", + "project": {"uri": "at://did:plc:human/com.disnetdev.radial.project/project", "cid": "cid-project"}, + "type": "plan", + "enabled": true, + "createdAt": "2026-01-01T00:00:07Z" + }, "com.disnetdev.radial.artifact": { "$type": "com.disnetdev.radial.artifact", "request": {"uri": "at://did:plc:human/com.disnetdev.radial.artifactRequest/request", "cid": "cid-request"}, diff --git a/packages/core/test/materializer.test.mjs b/packages/core/test/materializer.test.mjs index 4c52c31..8ac503c 100644 --- a/packages/core/test/materializer.test.mjs +++ b/packages/core/test/materializer.test.mjs @@ -417,6 +417,33 @@ describe('materializer golden scenario', () => { ) }) + it('overlays admin setAutoReview records (latest-per-type) onto the project autoReview base', () => { + const scenario = goldenScenario() + const index = build(scenario.records) + const project = index.projects.find((view) => view.target.uri === scenario.projectUri) + // Base from the project record (`{ implementation: false }`) merged with the latest admin + // overlay for `plan` (a later `enabled: true` supersedes the earlier `enabled: false`). + assert.deepEqual(project?.autoReview, { implementation: false, plan: true }) + // The non-admin member's setAutoReview never reaches the view and is flagged unresolved. + assert.equal( + index.ignored.some( + (entry) => + entry.uri === scenario.nonAdminAutoReviewUri && + entry.reason === 'record does not resolve into this space index', + ), + true, + ) + }) + + it('converges autoReview overlays across two independent materializers', () => { + const scenario = goldenScenario() + const a = build(scenario.records) + const b = build(shuffled(scenario.records, 4242)) + assert.deepEqual(a.projects, b.projects) + const project = a.projects.find((view) => view.target.uri === scenario.projectUri) + assert.equal(project?.autoReview.plan, true) + }) + it('is invariant under 200 deterministic random arrival permutations', () => { const scenario = goldenScenario() const expected = build(scenario.records) diff --git a/packages/core/test/scenario.ts b/packages/core/test/scenario.ts index 37f0c29..183c68c 100644 --- a/packages/core/test/scenario.ts +++ b/packages/core/test/scenario.ts @@ -49,6 +49,7 @@ export interface GoldenScenario { implGoalUri: string untrustedMergeUri: string danglingMergeUri: string + nonAdminAutoReviewUri: string } export function goldenScenario(): GoldenScenario { @@ -111,7 +112,8 @@ export function goldenScenario(): GoldenScenario { gitUrl: 'https://github.com/disnet/radial-ng.git', defaultBranch: 'main', checks: [{ name: 'test', command: 'pnpm test' }], - autoReview: {}, + // A base default on the project record itself; `setAutoReview` records overlay it per type. + autoReview: { implementation: false }, createdAt: '2026-01-01T00:01:00Z', }, 1, 'cid-project'), ) @@ -429,6 +431,38 @@ export function goldenScenario(): GoldenScenario { }, 19), ) + // Auto-review config via standalone `setAutoReview` records (design §4). Two admin (ROOT) records + // target (project, 'plan'): the earlier disables, the later enables — latest-wins must resolve to + // `true`, layered over the project record's own `{ implementation: false }` base. A third record, + // authored by a non-admin member (HUMAN), is admin-gated out and never touches the view. + add( + stored(ROOT, 'auto-plan-off', { + $type: COLLECTIONS.setAutoReview, + project: ref(project), + type: 'plan', + enabled: false, + createdAt: '2026-01-01T00:15:00Z', + }, 21), + ) + add( + stored(ROOT, 'auto-plan-on', { + $type: COLLECTIONS.setAutoReview, + project: ref(project), + type: 'plan', + enabled: true, + createdAt: '2026-01-01T00:15:01Z', + }, 22), + ) + const nonAdminAutoReview = add( + stored(HUMAN, 'auto-nonadmin', { + $type: COLLECTIONS.setAutoReview, + project: ref(project), + type: 'implementation', + enabled: true, + createdAt: '2026-01-01T00:15:02Z', + }, 23), + ) + const removedMembership = memberships.get(REMOVED) as StrongRef const ignoredAfterRemoval = add( stored(REMOVED, 'removed-message', { @@ -471,5 +505,6 @@ export function goldenScenario(): GoldenScenario { implGoalUri: implGoal.uri, untrustedMergeUri: untrustedMerge.uri, danglingMergeUri: danglingMerge.uri, + nonAdminAutoReviewUri: nonAdminAutoReview.uri, } } diff --git a/packages/lexicons/lexicons/com.disnetdev.radial.setAutoReview.json b/packages/lexicons/lexicons/com.disnetdev.radial.setAutoReview.json new file mode 100644 index 0000000..61b7902 --- /dev/null +++ b/packages/lexicons/lexicons/com.disnetdev.radial.setAutoReview.json @@ -0,0 +1,20 @@ +{ + "lexicon": 1, + "id": "com.disnetdev.radial.setAutoReview", + "defs": { + "main": { + "type": "record", + "key": "tid", + "record": { + "type": "object", + "required": ["project", "type", "enabled", "createdAt"], + "properties": { + "project": {"type": "ref", "ref": "com.atproto.repo.strongRef"}, + "type": {"type": "string", "maxLength": 100}, + "enabled": {"type": "boolean"}, + "createdAt": {"type": "string", "format": "datetime"} + } + } + } + } +} diff --git a/packages/sidecar/src/cli.ts b/packages/sidecar/src/cli.ts index 0287411..5553b3f 100644 --- a/packages/sidecar/src/cli.ts +++ b/packages/sidecar/src/cli.ts @@ -24,7 +24,12 @@ export const help = `radial — human CLI for Radial records radial space create --name NAME [--description TEXT] radial member add --space REF --actor HANDLE|DID --kind human|agent --role ROLE radial member remove --space REF --actor HANDLE|DID + radial type create --space REF --name NAME (--brief TEXT | --brief-file PATH) + --output-description TEXT [--format markdown|json] [--scope goal|project] + [--schema-file JSON] + radial type list --space REF radial project create --space REF --name NAME --git-url URL + radial project set-auto-review --project REF --type NAME --enabled true|false radial goal create --project REF --title TITLE (--body TEXT | --body-file PATH) radial request create (--goal REF | --project REF) --type TYPE [--assignee HANDLE|DID] [--subject REF] @@ -93,6 +98,39 @@ export async function main(args = argv.slice(2)): Promise { ) const transport = new FetchRepoTransport() const resolver = new StrongRefResolver(transport) + + // `type list` is a read command, not a record write, so it does not fit runCli's write-and-return + // contract; handled here like `auth login`. Materializes the space and prints its registry types. + if (args[0] === 'type' && args[1] === 'list') { + const spaceLocator = value(args, '--space') + if (!spaceLocator) throw new Error('type list requires --space') + const spaceUri = spaceLocator.split('#')[0] as string + const records = new MemoryRecordStore() + const ingestor = new SpaceIngestor( + spaceUri, + new RepoPoller(transport, records, new MemorySyncStateStore()), + records, + ) + const index = await ingestor.sync() + if (args.includes('--json')) { + console.log( + JSON.stringify( + index.artifactTypes.map((type) => ({ + name: type.value.name, + scope: type.value.scope, + brief: type.value.brief, + })), + ), + ) + } else { + for (const type of index.artifactTypes) { + const summary = type.value.brief.split('\n')[0]?.slice(0, 80) ?? '' + console.log(`${type.value.name}\t${type.value.scope}\t${summary}`) + } + } + return + } + const result = await runCli(args, { writer: client, resolver, @@ -114,6 +152,25 @@ export async function main(args = argv.slice(2)): Promise { } return target.membership }, + hasApprovingReview: async (subject, spaceUri) => { + const records = new MemoryRecordStore() + const ingestor = new SpaceIngestor( + spaceUri, + new RepoPoller(transport, records, new MemorySyncStateStore()), + records, + ) + const index = await ingestor.sync() + return [...index.goals, ...index.projects].some((view) => + view.reviews.some( + (review) => + review.value.verdict === 'approve' && + review.value.subject.uri === subject.uri && + review.value.subject.cid === subject.cid, + ), + ) + }, + // stderr, so it never corrupts `--json` stdout. + warn: (message) => console.error(message), }) if (args.includes('--json')) console.log(JSON.stringify({ ...result, ref: result.primary })) else console.log(`${result.primary.uri}#${result.primary.cid}`) diff --git a/packages/sidecar/src/commands.ts b/packages/sidecar/src/commands.ts index 131f514..f6f0d44 100644 --- a/packages/sidecar/src/commands.ts +++ b/packages/sidecar/src/commands.ts @@ -26,6 +26,13 @@ export interface CliDependencies { resolveMembership?: (spaceUri: string, did: string) => Promise /** Handle → DID. Records always store the DID, which outlives any handle pointing at it. */ resolveActor?: (identifier: string) => Promise + /** + * Whether the space has a trusted `approve` review pinning the given subject. Used only to warn on + * `request create --type implementation` off an unapproved plan — soft policy (§7), never a gate. + */ + hasApprovingReview?: (subject: StrongRef, spaceUri: string) => Promise + /** Emit a non-fatal warning. Wired to stderr so it never corrupts `--json` stdout. */ + warn?: (message: string) => void } export interface CommandResult { @@ -153,6 +160,48 @@ export async function runCli(args: string[], deps: CliDependencies): Promise { 'record does not resolve into this space index', ]) }) + + it('registers custom types, folds auto-review config, and warns on unapproved-plan implementations', async () => { + const aliceDid = 'did:plc:alice' + const bobDid = 'did:plc:bob' + const pdss = new Map([ + [aliceDid, new LocalPds(aliceDid)], + [bobDid, new LocalPds(bobDid)], + ]) + const fetcher = (input, init) => { + const service = new URL(input).origin + const pds = [...pdss.values()].find((candidate) => candidate.service === service) + if (!pds) throw new Error(`No local PDS for ${service}`) + return pds.fetch(input, init) + } + const transport = new FetchRepoTransport(async (did) => pdss.get(did).service, fetcher) + const resolver = new StrongRefResolver(transport) + const sessions = new Map() + for (const [did, pds] of pdss) { + sessions.set( + did, + new CredentialClient(await createSession(pds.service, pds.handle, 'password', fetcher), fetcher), + ) + } + const at = (did, minute) => ({ + writer: sessions.get(did), + resolver, + now: () => `2026-07-19T00:${String(minute).padStart(2, '0')}:00Z`, + readText: async () => { throw new Error('unexpected file read') }, + }) + // Mirrors cli.ts: a fresh materialization tells us whether a subject has a trusted approve verdict. + const hasApprovingReview = async (subject, spaceUri) => { + const store = new MemoryRecordStore() + const index = await new SpaceIngestor( + spaceUri, + new RepoPoller(transport, store, new MemorySyncStateStore()), + store, + ).sync() + return [...index.goals, ...index.projects].some((view) => + view.reviews.some( + (review) => + review.value.verdict === 'approve' && + review.value.subject.uri === subject.uri && + review.value.subject.cid === subject.cid, + ), + ) + } + + const space = await runCli( + ['space', 'create', '--name', 'Radial', '--description', 'config loop'], + at(aliceDid, 0), + ) + const stores = [new MemoryRecordStore(), new MemoryRecordStore()] + const ingestors = stores.map((store) => + new SpaceIngestor( + space.primary.uri, + new RepoPoller(transport, store, new MemorySyncStateStore(), { now: () => '2026-07-19T01:00:00Z' }), + store, + ), + ) + const sync = async () => { + const views = await Promise.all(ingestors.map((ingestor) => ingestor.sync())) + assert.deepEqual(views[0], views[1]) + return views + } + + // Feature 1: an admin (space root) registers a custom goal-scoped type; it surfaces in the index. + await runCli( + ['type', 'create', '--space', locator(space), '--name', 'security-review', + '--brief', 'Audit the change for vulnerabilities.', '--output-description', 'A security audit', '--scope', 'goal'], + at(aliceDid, 1), + ) + const [afterType] = await sync() + assert.equal(afterType.artifactTypes.some((type) => type.value.name === 'security-review'), true) + + // Bob authors the plan artifact below, so he must be an active member for it (and its review) to + // be trusted into the materialized view that hasApprovingReview consults. + await runCli( + ['member', 'add', '--space', locator(space), '--did', bobDid, '--kind', 'human', '--role', 'member'], + at(aliceDid, 10), + ) + await sync() + + const project = await runCli( + ['project', 'create', '--space', locator(space), '--name', 'radial', '--git-url', 'https://example.test/radial.git'], + at(aliceDid, 2), + ) + const goal = await runCli( + ['goal', 'create', '--project', locator(project), '--title', 'Ship it', '--body', 'Prove config'], + at(aliceDid, 3), + ) + + // Feature 2: standalone setAutoReview record; two independent materializers agree it took effect. + await runCli( + ['project', 'set-auto-review', '--project', locator(project), '--type', 'plan', '--enabled', 'true'], + at(aliceDid, 4), + ) + const views = await sync() + for (const view of views) { + const projectView = view.projects.find((candidate) => candidate.target.uri === project.primary.uri) + assert.equal(projectView.autoReview.plan, true) + } + + // Feature 3: an implementation request off a plan with no approving verdict warns but still writes. + const request = await runCli( + ['request', 'create', '--goal', locator(goal), '--type', 'plan', '--assignee', bobDid], + at(aliceDid, 5), + ) + const plan = await runCli( + ['artifact', 'post', '--request', locator(request), '--body', 'Plan version one'], + at(bobDid, 6), + ) + const unapproved = [] + const implOne = await runCli( + ['request', 'create', '--goal', locator(goal), '--type', 'implementation', '--based-on', locator(plan)], + { ...at(aliceDid, 7), hasApprovingReview, warn: (message) => unapproved.push(message) }, + ) + assert.match(implOne.primary.uri, /artifactRequest/) + assert.deepEqual(unapproved, [ + 'This plan has no approving review yet — reviews annotate, they don’t gate.', + ]) + + // After an approving review, the same request writes with no warning. + await runCli( + ['review', 'post', '--subject', locator(plan), '--verdict', 'approve'], + at(aliceDid, 8), + ) + const approved = [] + const implTwo = await runCli( + ['request', 'create', '--goal', locator(goal), '--type', 'implementation', '--based-on', locator(plan)], + { ...at(aliceDid, 9), hasApprovingReview, warn: (message) => approved.push(message) }, + ) + assert.match(implTwo.primary.uri, /artifactRequest/) + assert.deepEqual(approved, []) + }) }) -- knotmirror 0.0.1 From 1fd47bfc0dc3c38a0e217355cc844012716a07c3 Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 13:11:39 -0700 Subject: [PATCH 02/13] =?UTF-8?q?daemon:=20auto-review=20trigger=20(design?= =?UTF-8?q?=20=C2=A77)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When an artifact lands and its effective auto-review config is on, write a single terminal type:"review" artifactRequest under one of the daemon's agent identities with the artifact as subject. One hop, terminal — no dispatch. - New packages/daemon/src/auto-review.ts, shaped like merge-poll.ts: a pure selectAutoReviewCandidates gate plus a fire-and-forget AutoReviewTrigger pump. - Effective config read as request.autoReview ?? projectDefault[type] ?? false, where the project default flows through one projectAutoReviewConfig helper so the pending ProjectView.autoReview overlay flips in as a one-liner. - Dedup against live/fulfilled (not retracted) review requests, direct verdicts, the in-process alreadyWritten set, and a persisted per-space observed-subjects ledger (first snapshot seeds silently; downtime-landed artifacts still trigger). - Deterministic autoReviewRkey gives PDS-collision restart safety with matching adoption and mismatch-refusal, mirroring merge-poll. - Wired in cli.ts (near mergePoller, no forge dep), runtime.ts (after mergePoller), index.ts export, and shutdown drain. - New daemon/test/auto-review.test.mjs: 25 tests over selection, pump/dedup/ restart, real-materialize round-trip (goal + project), and terminality. Co-Authored-By: Claude Fable 5 --- packages/daemon/src/auto-review.ts | 359 ++++++++++++ packages/daemon/src/cli.ts | 13 + packages/daemon/src/index.ts | 1 + packages/daemon/src/node-shims.d.ts | 2 + packages/daemon/src/runtime.ts | 4 + packages/daemon/test/auto-review.test.mjs | 659 ++++++++++++++++++++++ 6 files changed, 1038 insertions(+) create mode 100644 packages/daemon/src/auto-review.ts create mode 100644 packages/daemon/test/auto-review.test.mjs diff --git a/packages/daemon/src/auto-review.ts b/packages/daemon/src/auto-review.ts new file mode 100644 index 0000000..38217b3 --- /dev/null +++ b/packages/daemon/src/auto-review.ts @@ -0,0 +1,359 @@ +import { createHash } from 'node:crypto' +import { existsSync, readFileSync } from 'node:fs' +import { mkdir, rename, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { XrpcError } from '@radial/atproto' +import { + COLLECTIONS, + type ArtifactRecord, + type ArtifactRequestRecord, + type GoalView, + type IndexedRecord, + type MaterializedIndex, + type ProjectView, + type StrongRef, +} from '@radial/core' +import type { ActorRegistry, LoadedActor } from './actors.js' +import { base32Encode } from './turn-socket.js' + +/** The one auto-review request type name the daemon emits (design §7). Matches a `review`-producing + * agent profile and the materializer's review-request path (materializer.ts:487-502). */ +const REVIEW_TYPE = 'review' + +/** Stable strongref key (uri#cid): the subject an auto-review request pins is an EXACT artifact + * version, so every dedup and the observed-subjects ledger key on uri#cid. */ +const refKey = (reference: { uri: string; cid: string }): string => `${reference.uri}#${reference.cid}` + +const sameRef = (left: StrongRef | undefined, right: StrongRef | undefined): boolean => + Boolean(left && right && left.uri === right.uri && left.cid === right.cid) + +/** + * Deterministic rkey for the auto-review request pinning an exact artifact version: `autoreview-` + * plus 24 base32 chars of sha256(subjectUri#subjectCid). Per-actor repos make this unique per + * daemon-actor, so a restart that re-derives the same rkey collides on the PDS (RecordAlreadyExists) + * instead of writing a second request — closing the restart-window double-write the in-memory + * `alreadyWritten` set alone cannot (it is lost on restart). Mirrors `mergeRkey` in merge-poll.ts. + */ +export function autoReviewRkey(subjectUri: string, subjectCid: string): string { + const digest = createHash('sha256').update(`${subjectUri}#${subjectCid}`).digest() + return `autoreview-${base32Encode(digest).slice(0, 24)}` +} + +/** + * The project's per-artifact-type auto-review defaults, read through THIS single helper on purpose. + * A concurrent issue is adding a computed `ProjectView.autoReview` overlay (standing `setAutoReview` + * records), and at merge the switch is a ONE-LINER here: prefer the overlay when present, e.g. + * `return ((projectView as { autoReview?: Record }).autoReview ?? onRecord)`. + * Today only the on-project-record default exists. + */ +export function projectAutoReviewConfig(projectView: ProjectView): Record { + const config = projectView.target.value.autoReview + return config && typeof config === 'object' ? (config as Record) : {} +} + +/** + * The review actor is deterministic: among the ELIGIBLE actors (each holds an active AGENT-kind + * membership grant in the space and produces `review` artifacts) pick the lowest DID. Returns + * undefined when no eligible actor exists (the caller skips with a once-per-space log). + */ +export function selectReviewActor(eligible: LoadedActor[]): LoadedActor | undefined { + return [...eligible].sort((a, b) => a.did.localeCompare(b.did))[0] +} + +export interface AutoReviewCandidate { + /** The exact artifact version to request a review of (its uri#cid is the review subject). */ + artifact: IndexedRecord + /** The actor whose repo the review request is written into (see `selectReviewActor`). */ + actor: LoadedActor +} + +/** + * Pure selection gate: which artifact versions should have an auto-review request written right now. + * Scans EVERY version in every goal's and project's artifacts (each prev-chained version is a + * distinct subject), skipping closed/archived goals. An artifact is a candidate iff: + * - its effective auto-review config is on: `request.autoReview ?? projectDefault[type] ?? false`, + * where `request` is the artifact's fulfilling request (its `request` backref; always resolvable, + * the materializer drops artifacts otherwise) and the project default is read through + * `projectAutoReviewConfig` (goal artifacts read their goal's project); + * - no LIVE-or-FULFILLED trusted `review` request already pins this exact version — a RETRACTED + * request does NOT count (it lingers in `view.requests` but is listed in `view.retracted`); + * - no trusted review VERDICT already pins this exact version (covers the UI's direct post-a-verdict + * path, which has no request); + * - it is not in the in-process `alreadyWritten` set; and + * - it is not in the observed-subjects `ledger` (i.e. it appeared since the last tick). + * When an artifact would be a candidate but no eligible review actor exists, `onSkip` is invoked + * (deduped to once per space by the caller). Ordered deterministically by subject uri. + */ +export function selectAutoReviewCandidates( + index: MaterializedIndex, + actors: ActorRegistry, + ledger: Set, + alreadyWritten: Set, + onSkip?: (reason: string) => void, +): AutoReviewCandidate[] { + const activeAgentDids = new Set( + index.members.filter((member) => member.active && member.kind === 'agent').map((member) => member.did), + ) + const eligible = actors.all.filter( + (actor) => activeAgentDids.has(actor.did) && actor.artifactTypes.includes(REVIEW_TYPE), + ) + const actor = selectReviewActor(eligible) + + // An artifact's `request` backref resolves against the fulfilling requests of ANY target (a + // project-scoped artifact's request lives under the project; a goal artifact's under the goal). + const requestByRef = new Map( + [...index.goals.flatMap((view) => view.requests), ...index.projects.flatMap((view) => view.requests)].map( + (request) => [refKey(request), request], + ), + ) + const projectViewByUri = new Map(index.projects.map((view) => [view.target.uri, view])) + + const candidates: AutoReviewCandidate[] = [] + const scan = (view: GoalView | ProjectView, projectConfig: Record): void => { + const retractedUris = new Set(view.retracted.map((request) => request.uri)) + for (const artifact of view.artifacts) { + const key = refKey(artifact) + if (ledger.has(key) || alreadyWritten.has(key)) continue + const request = requestByRef.get(refKey(artifact.value.request)) + if (!request) continue // defensive: the materializer guarantees this resolves. + const effective = request.value.autoReview ?? projectConfig[artifact.value.type] ?? false + if (!effective) continue + // (a) A live-or-fulfilled review request already pins this exact version. Retracted requests + // linger in `requests` but are excluded from `openRequests`; exclude them here identically. + const hasReviewRequest = view.requests.some( + (candidate) => + candidate.value.type === REVIEW_TYPE && + candidate.value.subject !== undefined && + refKey(candidate.value.subject) === key && + !retractedUris.has(candidate.uri), + ) + if (hasReviewRequest) continue + // (b) A trusted verdict already pins this exact version (direct post-a-verdict path, no request). + if (view.reviews.some((review) => refKey(review.value.subject) === key)) continue + if (!actor) { + onSkip?.('no loaded actor holds an active agent membership grant and produces review artifacts') + continue + } + candidates.push({ artifact, actor }) + } + } + + for (const goalView of index.goals) { + // Closed or archived goals are set aside: agents stop reviewing their artifacts. (Closure is the + // author's own `closed` edit; archival is any member's reversible `archiveGoal` record.) + if (goalView.archived || goalView.target.value.closed) continue + const projectView = projectViewByUri.get(goalView.target.value.project.uri) + scan(goalView, projectView ? projectAutoReviewConfig(projectView) : {}) + } + for (const projectView of index.projects) { + scan(projectView, projectAutoReviewConfig(projectView)) + } + + return candidates.sort((a, b) => a.artifact.uri.localeCompare(b.artifact.uri)) +} + +const allArtifactVersions = (index: MaterializedIndex): Array> => [ + ...index.goals.flatMap((view) => view.artifacts), + ...index.projects.flatMap((view) => view.artifacts), +] + +/** On-disk shape of a per-space observed-subjects ledger. Presence of the file means the space has + * been seeded (pre-existing artifacts recorded, never auto-reviewed). */ +interface LedgerFile { + space: string + subjects: string[] +} + +/** In-memory per-space observed-subjects ledger: the set of subject refKeys (uri#cid) ever seen, + * plus whether a persisted snapshot already existed (seeded). */ +class ObservedLedger { + readonly subjects = new Set() + seeded = false + constructor(readonly path: string) {} +} + +export interface AutoReviewTriggerDeps { + /** Daemon state directory; per-space ledgers live under `/auto-review/`. */ + stateDir: string + /** Injectable ISO-8601 clock for the written request's `createdAt`. */ + now?: () => string + log?: (message: string) => void +} + +/** + * Auto-review trigger (design §7), modeled on `MergePoller`: `pump` selects the artifact versions + * whose effective auto-review config is on and that landed since the last tick, and fires off exactly + * one `type: "review"` `artifactRequest` per subject (authored by one of the daemon's agent + * identities, with the artifact as `subject`). Fire-and-forget: `pump` never awaits a write, so it + * never blocks the ingestion loop. + * + * "Landed" is defined by a persisted per-space observed-subjects ledger, NOT a timestamp: every tick, + * AFTER selection, ALL currently-indexed artifact versions are recorded and persisted. The first-ever + * snapshot of a space seeds the ledger without triggering anything (pre-existing artifacts are never + * auto-reviewed); thereafter an artifact is a candidate only if it is not yet in the ledger — which + * also covers artifacts that landed during daemon downtime (never observed, so still reviewed on + * restart) and prevents a backfill storm when a project flips auto-review on. + * + * Double-write defense is two-layered, exactly like `MergePoller`: the in-memory `#alreadyWritten` + * set closes the within-process window before the request is ingested, and the DETERMINISTIC rkey + * (`autoReviewRkey`) makes a re-derived write after a restart collide on the PDS; a collision is + * ADOPTED as success only when the existing record matches (same subject, type, and goal/project + * target) — a mismatch is logged once and never retried. + */ +export class AutoReviewTrigger { + readonly #deps: AutoReviewTriggerDeps + readonly #ledgers = new Map() + readonly #alreadyWritten = new Set() + readonly #inFlight = new Map>() + /** Per-space persist tail: chained so overlapping ticks never race the tmp+rename. */ + readonly #persists = new Map>() + /** Skip/error reasons already logged, so a stable condition is reported once. */ + readonly #loggedSkips = new Set() + + constructor(deps: AutoReviewTriggerDeps) { + this.#deps = deps + } + + get inFlight(): number { + return this.#inFlight.size + } + + #now(): string { + return this.#deps.now?.() ?? new Date().toISOString() + } + + #logOnce(message: string): void { + if (this.#loggedSkips.has(message)) return + this.#loggedSkips.add(message) + this.#deps.log?.(message) + } + + #ledgerPathFor(spaceUri: string): string { + const hex = createHash('sha256').update(spaceUri).digest('hex').slice(0, 16) + return join(this.#deps.stateDir, 'auto-review', `${hex}.json`) + } + + /** Loads (once per process) the persisted ledger for a space; a present file means seeded. */ + #loadLedger(spaceUri: string): ObservedLedger { + const existing = this.#ledgers.get(spaceUri) + if (existing) return existing + const ledger = new ObservedLedger(this.#ledgerPathFor(spaceUri)) + if (existsSync(ledger.path)) { + try { + const parsed = JSON.parse(readFileSync(ledger.path, 'utf8')) as LedgerFile + if (Array.isArray(parsed.subjects)) for (const subject of parsed.subjects) ledger.subjects.add(subject) + ledger.seeded = true + } catch (error) { + // Corrupt ledger: treat as unseeded (re-seed silently) rather than crash the daemon. + this.#deps.log?.( + `auto-review: unreadable ledger ${ledger.path}; re-seeding: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + this.#ledgers.set(spaceUri, ledger) + return ledger + } + + /** Selects new auto-review candidates from `index` and fires their writes; returns immediately. */ + pump(index: MaterializedIndex, actors: ActorRegistry): void { + const spaceUri = index.space.uri + const ledger = this.#loadLedger(spaceUri) + + // Select against the ledger as it stood at the START of this tick. A first-ever snapshot + // (unseeded) triggers nothing: pre-existing artifacts are seeded below and never reviewed. + const candidates = ledger.seeded + ? selectAutoReviewCandidates(index, actors, ledger.subjects, this.#alreadyWritten, (reason) => + this.#logOnce(`not auto-reviewing: ${reason}`), + ) + : [] + + // AFTER selection, record every currently-indexed artifact version (all goals — including + // closed/archived — and all projects) so a later un-archive or auto-review flip never backfills. + for (const artifact of allArtifactVersions(index)) ledger.subjects.add(refKey(artifact)) + ledger.seeded = true + this.#persist(spaceUri, ledger) + + for (const candidate of candidates) { + const key = refKey(candidate.artifact) + if (this.#inFlight.has(key)) continue + const promise = this.#write(candidate).finally(() => this.#inFlight.delete(key)) + this.#inFlight.set(key, promise) + } + } + + #persist(spaceUri: string, ledger: ObservedLedger): void { + const snapshot: LedgerFile = { space: spaceUri, subjects: [...ledger.subjects].sort() } + const tail = (this.#persists.get(spaceUri) ?? Promise.resolve()) + .then(() => this.#writeLedgerFile(ledger.path, snapshot)) + .catch((error: unknown) => + this.#deps.log?.( + `auto-review: failed to persist ledger ${ledger.path}: ${error instanceof Error ? error.message : String(error)}`, + ), + ) + this.#persists.set(spaceUri, tail) + } + + async #writeLedgerFile(path: string, snapshot: LedgerFile): Promise { + await mkdir(dirname(path), { recursive: true }) + const tmp = `${path}.tmp` + await writeFile(tmp, JSON.stringify(snapshot)) + await rename(tmp, path) // atomic replace so a crash mid-write never leaves a torn ledger. + } + + async #write(candidate: AutoReviewCandidate): Promise { + const { artifact, actor } = candidate + const subject: StrongRef = { uri: artifact.uri, cid: artifact.cid } + const key = refKey(artifact) + // The review request's goal/project target is copied EXACTLY from the subject artifact's own ref + // — the materializer silently drops a review request whose target does not match its subject's + // (materializer.ts:487-502). + const record: ArtifactRequestRecord = { + $type: COLLECTIONS.artifactRequest, + ...(artifact.value.goal ? { goal: artifact.value.goal } : { project: artifact.value.project as StrongRef }), + type: REVIEW_TYPE, + subject, + basedOn: [subject], // provenance recorded-when-known: the subject is what this review is of. + assignee: actor.did, + createdAt: this.#now(), + } + const rkey = autoReviewRkey(subject.uri, subject.cid) + try { + let ref: StrongRef + try { + ref = await actor.client.create(COLLECTIONS.artifactRequest, record, { rkey }) + } catch (error) { + if (error instanceof XrpcError && error.status === 400 && error.error === 'RecordAlreadyExists') { + const existing = await actor.client.getOwnRecord(COLLECTIONS.artifactRequest, rkey) + if (!existing) throw error + const value = existing.value as ArtifactRequestRecord + const targetMatches = artifact.value.goal + ? sameRef(value.goal, artifact.value.goal) + : sameRef(value.project, artifact.value.project) + if (value.type !== REVIEW_TYPE || !sameRef(value.subject, subject) || !targetMatches) { + // A DIFFERENT record already occupies this deterministic rkey (should be impossible — the + // rkey is a pure function of the subject). Do NOT adopt, do NOT mark written, do NOT + // retry-loop; log once per subject. + this.#logOnce( + `auto-review: refusing to adopt mismatched record at ${rkey} for subject ${subject.uri}`, + ) + return + } + ref = { uri: existing.uri, cid: existing.cid } + } else { + throw error + } + } + this.#alreadyWritten.add(key) + this.#deps.log?.(`auto-review: requested review of ${subject.uri} as ${actor.did}: ${ref.uri}`) + } catch (error) { + this.#deps.log?.( + `auto-review: failed to write review request for ${subject.uri}: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + + /** Awaits every in-flight write and ledger persist (best-effort graceful shutdown). */ + async drain(): Promise { + await Promise.all([...this.#inFlight.values(), ...this.#persists.values()]) + } +} diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.ts index 51a5c18..43fbb61 100644 --- a/packages/daemon/src/cli.ts +++ b/packages/daemon/src/cli.ts @@ -8,6 +8,7 @@ import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { FileSessionStore, defaultDataDirectory } from '@radial/atproto' import { loadActors } from './actors.js' +import { AutoReviewTrigger } from './auto-review.js' import { CONFIG_FILENAME, buildDefaultConfig, @@ -346,6 +347,7 @@ async function runCommand(args: string[]): Promise { await mkdir(run.stateDir, { recursive: true }) await mkdir(join(run.stateDir, 'turns'), { recursive: true }) await mkdir(join(run.stateDir, 'checks'), { recursive: true }) + await mkdir(join(run.stateDir, 'auto-review'), { recursive: true }) const store = new FileSessionStore() const actors = await loadActors(config, store) @@ -452,6 +454,15 @@ async function runCommand(args: string[]): Promise { }) : undefined + // Auto-review trigger (design §7): writes a `type: "review"` request the moment an artifact whose + // effective auto-review config is on lands. No forge dependency — it runs whenever actors exist; + // its observed-subjects ledger lives under `/auto-review/`. + const autoReviewTrigger = new AutoReviewTrigger({ + stateDir: run.stateDir, + now: () => new Date().toISOString(), + log: (message) => console.log(message), + }) + const controller = new AbortController() const stop = (): void => controller.abort() process.on('SIGTERM', stop) @@ -463,6 +474,7 @@ async function runCommand(args: string[]): Promise { dispatcher, checkDispatcher, ...(mergePoller ? { mergePoller } : {}), + autoReviewTrigger, actors, intervalMs: interval, signal: controller.signal, @@ -478,6 +490,7 @@ async function runCommand(args: string[]): Promise { } await dispatcher.drain().catch(() => {}) await checkDispatcher.drain().catch(() => {}) + await autoReviewTrigger.drain().catch(() => {}) for (const { runtime } of spaces) runtime.close() ledger.close() checkLedger.close() diff --git a/packages/daemon/src/index.ts b/packages/daemon/src/index.ts index 8b25b5e..502312d 100644 --- a/packages/daemon/src/index.ts +++ b/packages/daemon/src/index.ts @@ -1,4 +1,5 @@ export * from './actors.js' +export * from './auto-review.js' export * from './bundle-writer.js' export * from './check-dispatch.js' export * from './check-ledger.js' diff --git a/packages/daemon/src/node-shims.d.ts b/packages/daemon/src/node-shims.d.ts index 3e6a905..7f1da1f 100644 --- a/packages/daemon/src/node-shims.d.ts +++ b/packages/daemon/src/node-shims.d.ts @@ -12,6 +12,8 @@ declare module 'node:readline/promises' { } declare module 'node:fs' { export function realpathSync(path: string): string + export function existsSync(path: string): boolean + export function readFileSync(path: string, encoding: string): string } declare module 'node:url' { export function pathToFileURL(path: string): URL diff --git a/packages/daemon/src/runtime.ts b/packages/daemon/src/runtime.ts index 8210f42..013c268 100644 --- a/packages/daemon/src/runtime.ts +++ b/packages/daemon/src/runtime.ts @@ -125,6 +125,9 @@ export interface RunDaemonOptions { /** Optional merge-observation poller (design §10); pumped with the same fresh index right after * the dispatcher, fire-and-forget. Omitted when no forge adapter is wired (e.g. no forge config). */ mergePoller?: { pump(index: MaterializedIndex, actors: ActorRegistry): void } + /** Optional auto-review trigger (design §7); pumped with the same fresh index right after the + * merge poller, fire-and-forget. Runs whenever agents exist (no forge dependency). */ + autoReviewTrigger?: { pump(index: MaterializedIndex, actors: ActorRegistry): void } actors: ActorRegistry intervalMs: number log?: (message: string) => void @@ -155,6 +158,7 @@ export async function runDaemon(options: RunDaemonOptions): Promise { options.dispatcher.pump(index, options.actors) options.checkDispatcher?.pump(index, options.actors) options.mergePoller?.pump(index, options.actors) + options.autoReviewTrigger?.pump(index, options.actors) } catch (error) { options.log?.(`sync failed for ${spaceUri}: ${error instanceof Error ? error.message : String(error)}`) } diff --git a/packages/daemon/test/auto-review.test.mjs b/packages/daemon/test/auto-review.test.mjs new file mode 100644 index 0000000..f57eca3 --- /dev/null +++ b/packages/daemon/test/auto-review.test.mjs @@ -0,0 +1,659 @@ +import assert from 'node:assert/strict' +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { after, describe, it } from 'node:test' +import { COLLECTIONS, MemoryRecordStore, materialize } from '../../core/dist/index.js' +import { XrpcError } from '../../atproto/dist/index.js' +import { + AutoReviewTrigger, + autoReviewRkey, + selectAutoReviewCandidates, + selectReviewActor, +} from '../dist/index.js' + +const ROOT = 'did:plc:root' +const HUMAN = 'did:plc:human' +const AGENT_A = 'did:plc:agenta' +const AGENT_B = 'did:plc:agentb' + +// --- Minimal builders. The trigger reads index.space, index.members, index.goals/.projects (each a +// TargetView with artifacts/requests/retracted/reviews) and actors' did/artifactTypes/client, so a +// hand-built index gives precise control over config, dedup, membership, and the ledger. --- + +const artUri = (did, rkey) => `at://${did}/${COLLECTIONS.artifact}/${rkey}` + +/** A fulfilling (non-review) request for an artifact type; `autoReview` overrides the project default. */ +function request(did, rkey, { type = 'plan', goal, project, autoReview } = {}) { + return { + did, + uri: `at://${did}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: `cid-${rkey}`, + value: { + $type: COLLECTIONS.artifactRequest, + type, + basedOn: [], + ...(goal ? { goal } : {}), + ...(project ? { project } : {}), + ...(autoReview !== undefined ? { autoReview } : {}), + createdAt: '2026-01-01T00:00:00Z', + }, + } +} + +/** An artifact version fulfilling `req`, scoped to a goal (default) or project. */ +function artifact(did, rkey, req, { type = 'plan', goal, project, cid = `cid-${rkey}` } = {}) { + return { + did, + uri: artUri(did, rkey), + cid, + value: { + $type: COLLECTIONS.artifact, + request: { uri: req.uri, cid: req.cid }, + type, + body: '', + links: {}, + ...(goal ? { goal } : {}), + ...(project ? { project } : {}), + createdAt: '2026-01-01T00:00:01Z', + }, + } +} + +/** A trusted `type:"review"` request pinning `subject` (an artifact). */ +function reviewRequest(did, rkey, subject, { goal, project } = {}) { + return { + did, + uri: `at://${did}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: `cid-${rkey}`, + value: { + $type: COLLECTIONS.artifactRequest, + type: 'review', + subject: { uri: subject.uri, cid: subject.cid }, + basedOn: [{ uri: subject.uri, cid: subject.cid }], + ...(goal ? { goal } : {}), + ...(project ? { project } : {}), + createdAt: '2026-01-01T00:00:02Z', + }, + } +} + +/** A trusted review VERDICT pinning `subject`. */ +function verdict(did, rkey, subject) { + return { + did, + uri: `at://${did}/${COLLECTIONS.review}/${rkey}`, + cid: `cid-${rkey}`, + value: { + $type: COLLECTIONS.review, + subject: { uri: subject.uri, cid: subject.cid }, + verdict: 'approve', + findings: [], + createdAt: '2026-01-01T00:00:03Z', + }, + } +} + +// A single-project, single-goal index. `members` is the list of active grants; each entry may be a +// bare DID (agent-kind) or {did, kind}. autoReview is the project's per-type default map. +function makeIndex({ + artifacts = [], + requests = [], + reviews = [], + retracted = [], + members = [AGENT_A], + projectAutoReview = {}, + goalScope = true, + closed = false, + archived = false, + projectArtifacts = [], + projectRequests = [], + projectReviews = [], + projectRetracted = [], +} = {}) { + const spaceUri = `at://${ROOT}/${COLLECTIONS.space}/space` + const projectRef = { uri: `at://${ROOT}/${COLLECTIONS.project}/p`, cid: 'cid-project' } + const goalRef = { uri: `at://${ROOT}/${COLLECTIONS.goal}/g`, cid: 'cid-goal' } + return { + space: { uri: spaceUri, cid: 'cid-space', value: { name: 'S' } }, + members: members.map((m) => + typeof m === 'string' + ? { did: m, active: true, kind: 'agent', role: 'agent' } + : { did: m.did, active: true, kind: m.kind ?? 'agent', role: m.kind === 'human' ? 'member' : 'agent' }, + ), + goals: [ + { + target: { uri: goalRef.uri, cid: goalRef.cid, value: { project: projectRef, closed } }, + archived, + artifacts, + requests, + openRequests: [], + retracted, + reviews, + }, + ], + projects: [ + { + target: { uri: projectRef.uri, cid: projectRef.cid, value: { autoReview: projectAutoReview } }, + artifacts: projectArtifacts, + requests: projectRequests, + openRequests: [], + retracted: projectRetracted, + reviews: projectReviews, + currentSystemArtifacts: [], + }, + ], + // Convenience refs for callers. + _goalRef: goalRef, + _projectRef: projectRef, + } +} + +function fakeActor(did, artifactTypes, creates) { + return { + did, + profile: did, + artifactTypes, + session: { did }, + client: { + async create(collection, value, options) { + creates.push({ did, collection, value, rkey: options?.rkey }) + return { uri: `at://${did}/${collection}/${options?.rkey ?? `rk-${creates.length}`}`, cid: `cid-${creates.length}` } + }, + }, + } +} + +/** An actor over a shared in-memory PDS `store` enforcing rkey uniqueness — so a deterministic-rkey + * collision throws RecordAlreadyExists and getOwnRecord can adopt (or reject) it. */ +function pdsActor(did, artifactTypes, store, creates) { + return { + did, + profile: did, + artifactTypes, + session: { did }, + client: { + async create(collection, value, options) { + const key = `${collection}/${options.rkey}` + if (store.has(key)) throw new XrpcError(400, 'RecordAlreadyExists', 'record already exists') + const ref = { uri: `at://${did}/${collection}/${options.rkey}`, cid: `cid-${store.size + 1}` } + store.set(key, { ...ref, value }) + creates.push({ did, collection, value, rkey: options.rkey }) + return ref + }, + async getOwnRecord(collection, rkey) { + const rec = store.get(`${collection}/${rkey}`) + return rec ? { uri: rec.uri, cid: rec.cid, value: rec.value } : undefined + }, + }, + } +} + +function registry(actors) { + const byDid = new Map() + for (const actor of actors) { + const existing = byDid.get(actor.did) + if (existing) existing.push(actor) + else byDid.set(actor.did, [actor]) + } + return { + all: actors, + byDid, + select: (did, type) => byDid.get(did)?.find((a) => a.artifactTypes.includes(type)), + } +} + +const tmpDirs = [] +function stateDir() { + const dir = mkdtempSync(join(tmpdir(), 'radial-autoreview-')) + tmpDirs.push(dir) + return dir +} +after(async () => { + const { rm } = await import('node:fs/promises') + for (const dir of tmpDirs) await rm(dir, { recursive: true, force: true }).catch(() => {}) +}) + +function trigger(dir, now, log) { + return new AutoReviewTrigger({ stateDir: dir, now: now ?? (() => '2026-06-01T00:00:00.000Z'), ...(log ? { log } : {}) }) +} + +const reviewActors = (creates) => registry([fakeActor(AGENT_A, ['plan', 'review'], creates)]) + +describe('selectReviewActor', () => { + it('picks the lowest DID among eligible actors', () => { + const a = fakeActor(AGENT_A, ['review'], []) + const b = fakeActor(AGENT_B, ['review'], []) + assert.equal(selectReviewActor([b, a]).did, AGENT_A) + assert.equal(selectReviewActor([]), undefined) + }) +}) + +describe('selectAutoReviewCandidates', () => { + const subjectsOf = (candidates) => candidates.map((c) => c.artifact.uri) + + it('project default on selects; off (or absent) does not', () => { + const actors = reviewActors([]) + const on = makeIndex({}) // fill below + const req = request(HUMAN, 'req', { goal: on._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: on._goalRef }) + const idxOn = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idxOn, actors, new Set(), new Set())), [art.uri]) + const idxOff = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: false } }) + assert.equal(selectAutoReviewCandidates(idxOff, actors, new Set(), new Set()).length, 0) + const idxAbsent = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: {} }) + assert.equal(selectAutoReviewCandidates(idxAbsent, actors, new Set(), new Set()).length, 0) + }) + + it('per-request false suppresses despite project true', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef, autoReview: false }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const idx = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + assert.equal(selectAutoReviewCandidates(idx, actors, new Set(), new Set()).length, 0) + }) + + it('per-request true forces despite project false', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef, autoReview: true }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const idx = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: false } }) + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idx, actors, new Set(), new Set())), [art.uri]) + }) + + it('a live review request on the subject skips it', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const rr = reviewRequest(AGENT_A, 'rr', art, { goal: base._goalRef }) + const idx = makeIndex({ artifacts: [art], requests: [req, rr], projectAutoReview: { plan: true } }) + assert.equal(selectAutoReviewCandidates(idx, actors, new Set(), new Set()).length, 0) + }) + + it('a RETRACTED review request only does NOT skip', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const rr = reviewRequest(AGENT_A, 'rr', art, { goal: base._goalRef }) + // rr lingers in requests but is listed in retracted → excluded from the dedup. + const idx = makeIndex({ artifacts: [art], requests: [req, rr], retracted: [rr], projectAutoReview: { plan: true } }) + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idx, actors, new Set(), new Set())), [art.uri]) + }) + + it('a direct verdict on the subject (no request) skips it', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const v = verdict(AGENT_A, 'v', art) + const idx = makeIndex({ artifacts: [art], requests: [req], reviews: [v], projectAutoReview: { plan: true } }) + assert.equal(selectAutoReviewCandidates(idx, actors, new Set(), new Set()).length, 0) + }) + + it('a verdict on v1 but v2 landed → v2 is still a candidate', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req1 = request(HUMAN, 'req1', { goal: base._goalRef }) + const req2 = request(HUMAN, 'req2', { goal: base._goalRef }) + const v1 = artifact(AGENT_A, 'plan-1', req1, { goal: base._goalRef }) + const v2 = artifact(AGENT_A, 'plan-2', req2, { goal: base._goalRef }) + const verdictV1 = verdict(AGENT_A, 'v', v1) + const idx = makeIndex({ + artifacts: [v1, v2], + requests: [req1, req2], + reviews: [verdictV1], + projectAutoReview: { plan: true }, + }) + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idx, actors, new Set(), new Set())), [v2.uri]) + }) + + it('closed or archived goals are skipped', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const opts = { artifacts: [art], requests: [req], projectAutoReview: { plan: true } } + assert.equal(selectAutoReviewCandidates(makeIndex({ ...opts, closed: true }), actors, new Set(), new Set()).length, 0) + assert.equal(selectAutoReviewCandidates(makeIndex({ ...opts, archived: true }), actors, new Set(), new Set()).length, 0) + assert.equal(selectAutoReviewCandidates(makeIndex(opts), actors, new Set(), new Set()).length, 1) + }) + + it('the observed-subjects ledger governs candidacy (seeded/added/downtime)', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req1 = request(HUMAN, 'req1', { goal: base._goalRef }) + const req2 = request(HUMAN, 'req2', { goal: base._goalRef }) + const v1 = artifact(AGENT_A, 'plan-1', req1, { goal: base._goalRef }) + const v2 = artifact(AGENT_A, 'plan-2', req2, { goal: base._goalRef }) + const idx = makeIndex({ artifacts: [v1, v2], requests: [req1, req2], projectAutoReview: { plan: true } }) + // Both pre-existing (seeded on a first snapshot) → never candidates. + const seeded = new Set([`${v1.uri}#${v1.cid}`, `${v2.uri}#${v2.cid}`]) + assert.equal(selectAutoReviewCandidates(idx, actors, seeded, new Set()).length, 0) + // v1 was seen, v2 appeared after → only v2. + const onlyV1 = new Set([`${v1.uri}#${v1.cid}`]) + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idx, actors, onlyV1, new Set())), [v2.uri]) + // A ledger predating both (e.g. daemon downtime) → both still candidates on restart. + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idx, actors, new Set(), new Set())), [v1.uri, v2.uri]) + }) + + it('the in-process alreadyWritten set skips a subject', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const idx = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + const written = new Set([`${art.uri}#${art.cid}`]) + assert.equal(selectAutoReviewCandidates(idx, actors, new Set(), written).length, 0) + }) + + it('a human-kind membership actor is excluded (agent-kind grant required)', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + // AGENT_A holds only a human-kind grant here → not eligible to author a review. + const idx = makeIndex({ + artifacts: [art], + requests: [req], + members: [{ did: AGENT_A, kind: 'human' }], + projectAutoReview: { plan: true }, + }) + let skip + assert.equal(selectAutoReviewCandidates(idx, actors, new Set(), new Set(), (r) => (skip = r)).length, 0) + assert.match(skip, /active agent membership grant/) + }) + + it('logs once and skips when no eligible review actor exists', () => { + const actors = registry([fakeActor(AGENT_A, ['plan'], [])]) // produces plan, not review + const base = makeIndex({}) + const req1 = request(HUMAN, 'req1', { goal: base._goalRef }) + const req2 = request(HUMAN, 'req2', { goal: base._goalRef }) + const a1 = artifact(AGENT_A, 'plan-1', req1, { goal: base._goalRef }) + const a2 = artifact(AGENT_A, 'plan-2', req2, { goal: base._goalRef }) + const idx = makeIndex({ artifacts: [a1, a2], requests: [req1, req2], projectAutoReview: { plan: true } }) + const reasons = [] + assert.equal(selectAutoReviewCandidates(idx, actors, new Set(), new Set(), (r) => reasons.push(r)).length, 0) + assert.equal(reasons.length, 2) // once per candidate; the trigger dedups to once per space + assert.match(reasons[0], /produces review artifacts/) + }) + + it('a custom review-type deliverable artifact with config on is a candidate', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + // A project-scoped `security-review` deliverable (a review-TYPE artifact, distinct from a verdict). + const req = request(HUMAN, 'req', { type: 'security-review', project: base._projectRef }) + const art = artifact(AGENT_A, 'sec-1', req, { type: 'security-review', project: base._projectRef }) + const idx = makeIndex({ + projectArtifacts: [art], + projectRequests: [req], + projectAutoReview: { 'security-review': true }, + }) + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idx, actors, new Set(), new Set())), [art.uri]) + }) + + it('a verdict record in the index is never itself a candidate (terminality)', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const v = verdict(AGENT_A, 'v', art) + // The verdict is in reviews, not artifacts; only artifacts are scanned. The subject already has a + // verdict, so it too is skipped → zero candidates. + const idx = makeIndex({ artifacts: [art], requests: [req], reviews: [v], projectAutoReview: { plan: true } }) + assert.equal(selectAutoReviewCandidates(idx, actors, new Set(), new Set()).length, 0) + }) + + it('orders candidates deterministically by subject uri', () => { + const actors = reviewActors([]) + const base = makeIndex({}) + const rb = request(HUMAN, 'reqb', { goal: base._goalRef }) + const ra = request(HUMAN, 'reqa', { goal: base._goalRef }) + const zzz = artifact(AGENT_A, 'zzz', rb, { goal: base._goalRef }) + const aaa = artifact(AGENT_A, 'aaa', ra, { goal: base._goalRef }) + const idx = makeIndex({ artifacts: [zzz, aaa], requests: [rb, ra], projectAutoReview: { plan: true } }) + assert.deepEqual(subjectsOf(selectAutoReviewCandidates(idx, actors, new Set(), new Set())), [aaa.uri, zzz.uri]) + }) +}) + +describe('AutoReviewTrigger.pump', () => { + it('writes exactly one request with the correct shape after seeding', async () => { + const creates = [] + const actors = reviewActors(creates) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) + t.pump(empty, actors) // first-ever snapshot: seeds, triggers nothing + await t.drain() + assert.equal(creates.length, 0) + + t.pump(withArt, actors) // the artifact landed since the seed → one request + await t.drain() + assert.equal(creates.length, 1) + const written = creates[0] + assert.equal(written.collection, COLLECTIONS.artifactRequest) + assert.equal(written.value.type, 'review') + assert.deepEqual(written.value.goal, base._goalRef) // target copied exactly from the subject + assert.equal(written.value.project, undefined) + assert.deepEqual(written.value.subject, { uri: art.uri, cid: art.cid }) + assert.deepEqual(written.value.basedOn, [{ uri: art.uri, cid: art.cid }]) + assert.equal(written.value.assignee, AGENT_A) + assert.equal('autoReview' in written.value, false) + assert.equal(written.value.createdAt, '2026-06-01T00:00:00.000Z') + assert.equal(written.rkey, autoReviewRkey(art.uri, art.cid)) + assert.equal(written.did, AGENT_A) + }) + + it('does not double-write across ticks on a stale index (dedup)', async () => { + const creates = [] + const actors = reviewActors(creates) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) + t.pump(empty, actors); await t.drain() + t.pump(withArt, actors); await t.drain() + t.pump(withArt, actors); await t.drain() // same stale index (no review request ingested yet) + assert.equal(creates.length, 1) + }) + + it('does not write again once the request is in the index (post-ingest dedup)', async () => { + const creates = [] + const actors = reviewActors(creates) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const rr = reviewRequest(AGENT_A, autoReviewRkey(art.uri, art.cid), art, { goal: base._goalRef }) + // The review request has now been ingested into requests. + const ingested = makeIndex({ artifacts: [art], requests: [req, rr], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) + // A ledger that predates the artifact (fresh dir), but seeded so selection runs: seed empty then + // pump the ingested index; the in-index review request suppresses a second write. + t.pump(makeIndex({ projectAutoReview: { plan: true } }), actors); await t.drain() + t.pump(ingested, actors); await t.drain() + assert.equal(creates.length, 0) + }) + + it('persists the ledger across trigger instances (atomic reload)', async () => { + const creates = [] + const actors = reviewActors(creates) + const store = new Map() + const dir = stateDir() + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t1 = new AutoReviewTrigger({ stateDir: dir, now: () => '2026-06-01T00:00:00.000Z' }) + t1.pump(empty, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t1.drain() + t1.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t1.drain() + assert.equal(creates.length, 1) + + // A brand-new trigger over the SAME stateDir reloads the persisted ledger → the artifact is + // already observed → no re-selection, no second write. + const t2 = new AutoReviewTrigger({ stateDir: dir, now: () => '2026-06-01T00:00:00.000Z' }) + t2.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t2.drain() + assert.equal(creates.length, 1) + }) + + it('adopts a matching deterministic-rkey collision on restart instead of double-writing', async () => { + const creates = [] + const store = new Map() + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + // Process 1 (its own fresh stateDir) writes the review request under the deterministic rkey. + const t1 = trigger(stateDir()) + t1.pump(empty, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t1.drain() + t1.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t1.drain() + assert.equal(creates.length, 1) + assert.equal(store.size, 1) + + // Process 2 with a DIFFERENT (empty) ledger dir but the SAME PDS: it re-selects the artifact and + // re-derives the same rkey → collision → getOwnRecord returns a MATCHING record → adopt, no dup. + const t2 = trigger(stateDir()) + t2.pump(empty, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t2.drain() + t2.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t2.drain() + assert.equal(creates.length, 1) // the colliding create threw before recording → still one write + assert.equal(store.size, 1) + }) + + it('errors (does not adopt) when the existing record at the rkey mismatches', async () => { + const creates = [] + const logs = [] + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + // Pre-seed the PDS with a DIFFERENT record occupying the deterministic rkey (wrong subject cid). + const store = new Map() + const rkey = autoReviewRkey(art.uri, art.cid) + store.set(`${COLLECTIONS.artifactRequest}/${rkey}`, { + uri: `at://${AGENT_A}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: 'cid-pre', + value: { $type: COLLECTIONS.artifactRequest, type: 'review', subject: { uri: art.uri, cid: 'DIFFERENT' }, basedOn: [], goal: base._goalRef, createdAt: 'x' }, + }) + + const t = trigger(stateDir(), undefined, (m) => logs.push(m)) + t.pump(empty, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t.drain() + t.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t.drain() + assert.equal(creates.length, 0) // never adopted, never re-created + assert.equal(store.size, 1) // the pre-existing mismatched record is untouched + assert.equal(logs.filter((m) => /refusing to adopt mismatched/.test(m)).length, 1) + }) + + it('logs once (not per tick) when no eligible review actor exists', async () => { + const creates = [] + const logs = [] + const actors = registry([fakeActor(AGENT_A, ['plan'], creates)]) // no review capability + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir(), undefined, (m) => logs.push(m)) + t.pump(empty, actors); await t.drain() + t.pump(withArt, actors); await t.drain() + t.pump(withArt, actors); await t.drain() + assert.equal(creates.length, 0) + assert.equal(logs.filter((m) => /produces review artifacts/.test(m)).length, 1) + }) +}) + +// --- Round-trip through the REAL core materializer: the written request must land in the target +// view's requests AND openRequests. This guards the silent-drop risk (materializer.ts:487-502). --- + +const rev = (n) => n.toString().padStart(13, '0') +function stored(did, rkey, value, revision, cid = `cid-${rkey}`) { + return { did, collection: value.$type, rkey, uri: `at://${did}/${value.$type}/${rkey}`, cid, rev: rev(revision), value } +} +const strongref = (record) => ({ uri: record.uri, cid: record.cid }) + +/** Builds a valid single-space store with one plan artifact (goal- or project-scoped) and returns + * refs the round-trip needs. */ +function buildStore({ scope }) { + const records = [] + const add = (r) => (records.push(r), r) + const space = add(stored(ROOT, 'space', { $type: COLLECTIONS.space, name: 'S', description: 'd', createdAt: '2026-01-01T00:00:00Z' }, 1, 'cid-space')) + add(stored(ROOT, 'm-human', { $type: COLLECTIONS.addMember, space: strongref(space), did: HUMAN, kind: 'human', role: 'member', createdAt: '2026-01-01T00:00:01Z' }, 2)) + add(stored(ROOT, 'm-agent', { $type: COLLECTIONS.addMember, space: strongref(space), did: AGENT_A, kind: 'agent', role: 'agent', createdAt: '2026-01-01T00:00:02Z' }, 3)) + const type = add(stored(ROOT, 'type-plan', { $type: COLLECTIONS.artifactType, space: strongref(space), name: 'plan', brief: 'b', outputSpec: { format: 'markdown', description: 'd' }, scope, createdAt: '2026-01-01T00:00:03Z' }, 4)) + void type + const project = add(stored(HUMAN, 'project', { $type: COLLECTIONS.project, space: strongref(space), name: 'p', gitUrl: 'https://example.com/r.git', defaultBranch: 'main', checks: [], autoReview: {}, createdAt: '2026-01-01T00:01:00Z' }, 5, 'cid-project')) + const goal = add(stored(HUMAN, 'goal', { $type: COLLECTIONS.goal, space: strongref(space), project: strongref(project), title: 't', body: 'b', createdAt: '2026-01-01T00:02:00Z' }, 6, 'cid-goal')) + const targetRef = scope === 'goal' ? strongref(goal) : strongref(project) + const req = add(stored(HUMAN, 'req', { $type: COLLECTIONS.artifactRequest, ...(scope === 'goal' ? { goal: targetRef } : { project: targetRef }), type: 'plan', basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:03:00Z' }, 7)) + const art = add(stored(AGENT_A, 'plan-1', { $type: COLLECTIONS.artifact, request: strongref(req), ...(scope === 'goal' ? { goal: targetRef } : { project: targetRef }), type: 'plan', body: 'the plan', links: {}, createdAt: '2026-01-01T00:04:00Z' }, 8, 'cid-plan-1')) + return { records, space, targetRef, art, scope } +} + +describe('written request round-trips through core.materialize', () => { + for (const scope of ['goal', 'project']) { + it(`lands in the ${scope}-scoped view's requests and openRequests`, async () => { + const { records, space, art } = buildStore({ scope }) + const store = new MemoryRecordStore() + for (const r of records) store.put(r) + + // An index whose single artifact carries the REAL goal/project ref from the store (so the + // written record copies it exactly) and whose fulfilling request forces auto-review on. + const spaceUri = space.uri + const artView = { did: AGENT_A, uri: art.uri, cid: art.cid, value: { ...art.value } } + const reqView = { + did: HUMAN, + uri: art.value.request.uri, + cid: art.value.request.cid, + value: { $type: COLLECTIONS.artifactRequest, type: 'plan', basedOn: [], autoReview: true, createdAt: 'x' }, + } + const emptyTarget = { requests: [], openRequests: [], retracted: [], reviews: [], artifacts: [] } + const target = { ...emptyTarget, artifacts: [artView], requests: [reqView] } + const buildIndex = (withArtifact) => ({ + space: { uri: spaceUri, cid: 'cid-space', value: { name: 'S' } }, + members: [{ did: AGENT_A, active: true, kind: 'agent', role: 'agent' }], + goals: + scope === 'goal' + ? [{ target: { uri: art.value.goal.uri, cid: art.value.goal.cid, value: { project: strongref(records[4]), closed: false } }, archived: false, ...(withArtifact ? target : emptyTarget) }] + : [], + projects: + scope === 'project' + ? [{ target: { uri: art.value.project.uri, cid: art.value.project.cid, value: { autoReview: {} } }, currentSystemArtifacts: [], ...(withArtifact ? target : emptyTarget) }] + : [{ target: { uri: strongref(records[4]).uri, cid: strongref(records[4]).cid, value: { autoReview: {} } }, currentSystemArtifacts: [], ...emptyTarget }], + }) + + const creates = [] + const actor = fakeActor(AGENT_A, ['plan', 'review'], creates) + const t = trigger(stateDir()) + t.pump(buildIndex(false), registry([actor])); await t.drain() // seed + t.pump(buildIndex(true), registry([actor])); await t.drain() + assert.equal(creates.length, 1) + const written = creates[0] + + // Ingest the actual written record under the actor's repo and materialize the real index. + store.put(stored(AGENT_A, written.rkey, written.value, 100, `cid-${written.rkey}`)) + const materialized = materialize(store, { spaceUri: space.uri }) + const view = scope === 'goal' ? materialized.goals[0] : materialized.projects[0] + const found = view.requests.filter((r) => r.value.type === 'review') + assert.equal(found.length, 1, 'review request present in view.requests') + assert.deepEqual(found[0].value.subject, { uri: art.uri, cid: art.cid }) + const open = view.openRequests.filter((r) => r.value.type === 'review') + assert.equal(open.length, 1, 'unfulfilled review request present in openRequests') + }) + } +}) -- knotmirror 0.0.1 From ec105f1310617651e6a2808b0f30b8fd7472dd0b Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 13:11:50 -0700 Subject: [PATCH 03/13] CLI review fixes: duplicate-type guard, ref validation, strict flag, warning scope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. type create refuses a name already in the trusted registry (materialized CLI-side via findArtifactType), preventing core (earliest-wins) / daemon (latest-wins) desync. Best-effort guard, not a lock — noted in a comment. 2. type list resolves its --space ref (validating a supplied #CID and the collection) instead of blindly stripping the fragment. 3. project set-auto-review --enabled strict-parses "true"/"false"; anything else is a usage error instead of a silent disable. 4. The unapproved-plan warning only considers basedOn refs that resolved as com.disnetdev.radial.artifact records, not any record with value.type "plan". Tests extended for all four (duplicate refusal incl. built-in, wrong-CID rejection, strict --enabled, non-artifact basedOn ignored). Co-Authored-By: Claude Fable 5 --- packages/sidecar/src/cli.ts | 17 +++++-- packages/sidecar/src/commands.ts | 31 +++++++++++- packages/sidecar/test/human-loop.test.mjs | 62 ++++++++++++++++++++++- 3 files changed, 103 insertions(+), 7 deletions(-) diff --git a/packages/sidecar/src/cli.ts b/packages/sidecar/src/cli.ts index 5553b3f..e662964 100644 --- a/packages/sidecar/src/cli.ts +++ b/packages/sidecar/src/cli.ts @@ -13,7 +13,7 @@ import { resolveHandleDid, resolveIdentityPds, } from '@radial/atproto' -import { MemoryRecordStore } from '@radial/core' +import { COLLECTIONS, MemoryRecordStore } from '@radial/core' import { MemorySyncStateStore, RepoPoller, SpaceIngestor } from '@radial/ingest' import { runCli } from './commands.js' import { buildTurnRpc, sendTurnRpc } from './socket.js' @@ -104,10 +104,12 @@ export async function main(args = argv.slice(2)): Promise { if (args[0] === 'type' && args[1] === 'list') { const spaceLocator = value(args, '--space') if (!spaceLocator) throw new Error('type list requires --space') - const spaceUri = spaceLocator.split('#')[0] as string + // Resolve the ref like the write commands do (validates a supplied #CID and the collection) + // rather than blindly stripping the fragment, which would list the space for a wrong CID. + const space = await resolver.resolve(spaceLocator, COLLECTIONS.space) const records = new MemoryRecordStore() const ingestor = new SpaceIngestor( - spaceUri, + space.uri, new RepoPoller(transport, records, new MemorySyncStateStore()), records, ) @@ -152,6 +154,15 @@ export async function main(args = argv.slice(2)): Promise { } return target.membership }, + findArtifactType: async (name, spaceUri) => { + const records = new MemoryRecordStore() + const index = await new SpaceIngestor( + spaceUri, + new RepoPoller(transport, records, new MemorySyncStateStore()), + records, + ).sync() + return index.artifactTypes.find((type) => type.value.name === name)?.uri + }, hasApprovingReview: async (subject, spaceUri) => { const records = new MemoryRecordStore() const ingestor = new SpaceIngestor( diff --git a/packages/sidecar/src/commands.ts b/packages/sidecar/src/commands.ts index f6f0d44..18a7231 100644 --- a/packages/sidecar/src/commands.ts +++ b/packages/sidecar/src/commands.ts @@ -26,6 +26,12 @@ export interface CliDependencies { resolveMembership?: (spaceUri: string, did: string) => Promise /** Handle → DID. Records always store the DID, which outlives any handle pointing at it. */ resolveActor?: (identifier: string) => Promise + /** + * The URI of an existing trusted artifact type with this name in the space, if any. Used to refuse + * duplicate `type create` names (the materializer resolves duplicate names earliest-wins while the + * daemon registry is latest-wins, so a duplicate could desync them). Best-effort by design. + */ + findArtifactType?: (name: string, spaceUri: string) => Promise /** * Whether the space has a trusted `approve` review pinning the given subject. Used only to warn on * `request create --type implementation` off an unapproved plan — soft policy (§7), never a gate. @@ -162,6 +168,18 @@ export async function runCli(args: string[], deps: CliDependencies): Promise { ), ) } + // Mirrors cli.ts: the URI of an existing trusted type with this name, if any. + const findArtifactType = async (name, spaceUri) => { + const store = new MemoryRecordStore() + const index = await new SpaceIngestor( + spaceUri, + new RepoPoller(transport, store, new MemorySyncStateStore()), + store, + ).sync() + return index.artifactTypes.find((type) => type.value.name === name)?.uri + } const space = await runCli( ['space', 'create', '--name', 'Radial', '--description', 'config loop'], @@ -217,11 +227,32 @@ describe('Phase 2 human-only artifact loop', () => { await runCli( ['type', 'create', '--space', locator(space), '--name', 'security-review', '--brief', 'Audit the change for vulnerabilities.', '--output-description', 'A security audit', '--scope', 'goal'], - at(aliceDid, 1), + { ...at(aliceDid, 1), findArtifactType }, ) const [afterType] = await sync() assert.equal(afterType.artifactTypes.some((type) => type.value.name === 'security-review'), true) + // Duplicate names are refused CLI-side (they would desync core's earliest-wins fold from the + // daemon's latest-wins registry) — both a re-create of the custom type and a built-in (`plan`). + await assert.rejects( + () => + runCli( + ['type', 'create', '--space', locator(space), '--name', 'security-review', + '--brief', 'again', '--output-description', 'again'], + { ...at(aliceDid, 12), findArtifactType }, + ), + /already exists in the registry/, + ) + await assert.rejects( + () => + runCli( + ['type', 'create', '--space', locator(space), '--name', 'plan', + '--brief', 'shadow the builtin', '--output-description', 'x', '--scope', 'project'], + { ...at(aliceDid, 13), findArtifactType }, + ), + /already exists in the registry/, + ) + // Bob authors the plan artifact below, so he must be an active member for it (and its review) to // be trusted into the materialized view that hasApprovingReview consults. await runCli( @@ -281,5 +312,32 @@ describe('Phase 2 human-only artifact loop', () => { ) assert.match(implTwo.primary.uri, /artifactRequest/) assert.deepEqual(approved, []) + + // `type list` resolves its --space ref (CID + collection) before ingesting: a wrong CID is + // rejected rather than silently listing the current space. + await assert.rejects( + () => resolver.resolve(`${space.primary.uri}#bafyreiawrongcidxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`, COLLECTIONS.space), + /CID mismatch/, + ) + + // `--enabled` is strict: a typo like "treu" is a usage error, not a silent disable. + await assert.rejects( + () => + runCli( + ['project', 'set-auto-review', '--project', locator(project), '--type', 'plan', '--enabled', 'treu'], + at(aliceDid, 14), + ), + /--enabled must be/, + ) + + // The soft-policy warning only fires for real plan *artifacts*. A basedOn ref that resolves to a + // non-artifact record (the plan *request*, whose value.type is also 'plan') must be ignored. + const spurious = [] + const implThree = await runCli( + ['request', 'create', '--goal', locator(goal), '--type', 'implementation', '--based-on', locator(request)], + { ...at(aliceDid, 15), hasApprovingReview, warn: (message) => spurious.push(message) }, + ) + assert.match(implThree.primary.uri, /artifactRequest/) + assert.deepEqual(spurious, []) }) }) -- knotmirror 0.0.1 From 0038b9499bb12a5d5f0b70c32bff84ec114be930 Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 13:19:55 -0700 Subject: [PATCH 04/13] core: review turn protocol + bundle subject - lexicon: com.disnetdev.radial.review key tid -> any (permits the deterministic review- rkey); regenerated records.ts via codegen. - turn-protocol: add SubmitReviewRpc (verdict + findings, no body) to the TurnRpcRequest union; raise maxFrameBytes to 2MB to cover a max review payload (100 findings x 10k-char bodies), keeping per-field limits. - bundle: add TurnBundle.subject; a review request seeds its subject (and the subject's prev ancestry, findings and checkruns) into the existing basedOn walk, idempotently (subject-also-in-basedOn is not duplicated). - tests: review-request bundle scenario + permutation invariance. Co-Authored-By: Claude Fable 5 --- packages/core/src/bundle.ts | 23 +++++- packages/core/src/generated/records.ts | 2 +- packages/core/src/turn-protocol.ts | 13 +++- packages/core/test/bundle.test.mjs | 72 +++++++++++++++++++ .../lexicons/com.disnetdev.radial.review.json | 2 +- 5 files changed, 106 insertions(+), 6 deletions(-) diff --git a/packages/core/src/bundle.ts b/packages/core/src/bundle.ts index 2e28e71..b2b71ab 100644 --- a/packages/core/src/bundle.ts +++ b/packages/core/src/bundle.ts @@ -25,6 +25,10 @@ export interface TurnBundle { goal: { uri: string; cid: string; title: string; body: string } project: { uri: string; cid: string; name: string; gitUrl: string; defaultBranch: string } basedOn: BundleArtifact[] + /** For a `review`-type request: the artifact under review. It is also seeded into the basedOn + * ancestry walk, so its version history, prior review findings and checkruns flow into the bundle + * the same way basedOn artifacts do. Absent for non-review requests. */ + subject?: BundleArtifact reviewFindings: Array<{ subject: StrongRef; verdict: 'approve' | 'request_changes'; findings: ReviewFinding[] }> checkruns: Array<{ artifact: StrongRef; results: CheckrunResult[] }> currentSystemArtifacts: BundleArtifact[] @@ -110,7 +114,10 @@ export function buildTurnBundle( artifact.value.goal?.uri ?? artifact.value.project?.uri const resolvedArtifacts = new Map>() - for (const reference of request.value.basedOn) { + // Walk an artifact's `prev` ancestry, adding each resolved version to `resolvedArtifacts`. + // Keyed by uri#cid, so seeding the same artifact from more than one entry point (e.g. a review + // subject that also appears in basedOn) is naturally idempotent. + const walkAncestry = (reference: StrongRef): void => { let current = resolve(reference) while (current) { const key = recordRefKey(current) @@ -135,6 +142,19 @@ export function buildTurnBundle( current = previous } } + for (const reference of request.value.basedOn) walkAncestry(reference) + + // A review request names the artifact under review via `subject`. Seed it (and its ancestry) + // into the same walk so its prior findings/checkruns flow into the bundle, and surface it + // explicitly as `bundle.subject`. The materializer only materializes a review request whose + // subject resolves under the same target (materializer.ts), so the resolve here always succeeds + // for a real review turn — no unresolved-subject branch is needed. + let subject: BundleArtifact | undefined + if (request.value.type === 'review' && request.value.subject) { + walkAncestry(request.value.subject) + const resolvedSubject = artifactByRef.get(refKey(request.value.subject)) + if (resolvedSubject) subject = toBundleArtifact(resolvedSubject) + } const basedOn = [...resolvedArtifacts.values()].map(toBundleArtifact).sort(byCreatedThenUri) @@ -205,6 +225,7 @@ export function buildTurnBundle( defaultBranch: projectView.target.value.defaultBranch, }, basedOn, + ...(subject ? { subject } : {}), reviewFindings, checkruns, currentSystemArtifacts, diff --git a/packages/core/src/generated/records.ts b/packages/core/src/generated/records.ts index bdbe61a..c0f7265 100644 --- a/packages/core/src/generated/records.ts +++ b/packages/core/src/generated/records.ts @@ -991,7 +991,7 @@ export const lexiconSchemas = [ }, "main": { "type": "record", - "key": "tid", + "key": "any", "record": { "type": "object", "required": [ diff --git a/packages/core/src/turn-protocol.ts b/packages/core/src/turn-protocol.ts index 6ec8a47..4187efd 100644 --- a/packages/core/src/turn-protocol.ts +++ b/packages/core/src/turn-protocol.ts @@ -1,12 +1,19 @@ -import type { StrongRef } from './generated/records.js' +import type { ReviewFinding, StrongRef } from './generated/records.js' export interface SubmitArtifactRpc { method: 'submitArtifact'; token: string; body: string; criteria?: string[]; branch?: string; commit?: string; pr?: string } export interface AskQuestionRpc { method: 'askQuestion'; token: string; body: string } -export type TurnRpcRequest = SubmitArtifactRpc | AskQuestionRpc +/** A review turn's terminal RPC. No `body` field — a ReviewRecord has none; the verdict plus + * structured findings are the whole payload. The daemon owns `subject` and `request` (from turn + * context), so they are deliberately absent from the wire envelope. */ +export interface SubmitReviewRpc { method: 'submitReview'; token: string; verdict: 'approve' | 'request_changes'; findings: ReviewFinding[] } +export type TurnRpcRequest = SubmitArtifactRpc | AskQuestionRpc | SubmitReviewRpc export type TurnRpcResponse = { ok: true; ref: StrongRef } | { ok: false; error: string } export const TURN_LIMITS = { artifactBodyChars: 100_000, messageBodyChars: 30_000, - maxFrameBytes: 100_000 * 4 + 8_192, + // The review lexicon caps findings at 100 entries × 10,000-char bodies (~1MB of body text alone, + // more once JSON-encoded with per-finding path/line/severity). 2MB comfortably covers the largest + // valid review payload; the per-field character limits above still bound artifact/message bodies. + maxFrameBytes: 2_000_000, frameTimeoutMs: 30_000, } as const diff --git a/packages/core/test/bundle.test.mjs b/packages/core/test/bundle.test.mjs index 59298ee..3e00a3e 100644 --- a/packages/core/test/bundle.test.mjs +++ b/packages/core/test/bundle.test.mjs @@ -604,3 +604,75 @@ describe('buildTurnBundle (generalized types)', () => { assert.deepEqual(bundle.basedOn[0].links, scenario.links) }) }) + +// --- Review requests -------------------------------------------------------- + +// A two-version plan chain (v1 -> v2), a review on each, and a checkrun on v2; then a review request +// whose subject is v2 and whose basedOn ALSO lists v2 (to exercise idempotent seeding). `review` is +// not a registry type — the materializer materializes a review request purely from a resolving +// same-target subject. +function reviewRequestScenario() { + const records = [] + const add = (r) => (records.push(r), r) + const space = add(make(ROOT, COLLECTIONS.space, 'space', 'cid-space', { $type: COLLECTIONS.space, name: 'S', description: '', createdAt: '2026-01-01T00:00:00Z' })) + add(make(ROOT, COLLECTIONS.addMember, 'm-h', 'cid-mh', { $type: COLLECTIONS.addMember, space: ref(space), did: HUMAN, kind: 'human', role: 'member', createdAt: '2026-01-01T00:00:01Z' })) + add(make(ROOT, COLLECTIONS.addMember, 'm-a', 'cid-ma', { $type: COLLECTIONS.addMember, space: ref(space), did: AGENT_A, kind: 'agent', role: 'agent', createdAt: '2026-01-01T00:00:02Z' })) + add(make(ROOT, COLLECTIONS.artifactType, 't-plan', 'cid-t-plan', { $type: COLLECTIONS.artifactType, space: ref(space), name: 'plan', brief: 'p', outputSpec: { format: 'markdown', description: 'x' }, scope: 'goal', createdAt: '2026-01-01T00:00:10Z' })) + const project = add(make(HUMAN, COLLECTIONS.project, 'proj', 'cid-proj', { $type: COLLECTIONS.project, space: ref(space), name: 'p', gitUrl: 'https://github.com/acme/widget.git', defaultBranch: 'main', checks: [], autoReview: {}, createdAt: '2026-01-01T00:01:00Z' })) + const goal = add(make(HUMAN, COLLECTIONS.goal, 'goal', 'cid-goal', { $type: COLLECTIONS.goal, space: ref(space), project: ref(project), title: 'G', body: 'b', createdAt: '2026-01-01T00:02:00Z' })) + const reqV1 = add(make(HUMAN, COLLECTIONS.artifactRequest, 'req-v1', 'cid-req-v1', { $type: COLLECTIONS.artifactRequest, goal: ref(goal), type: 'plan', basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:03:00Z' })) + const artV1 = add(make(AGENT_A, COLLECTIONS.artifact, 'plan-v1', 'cid-plan-v1', { $type: COLLECTIONS.artifact, request: ref(reqV1), goal: ref(goal), type: 'plan', body: 'v1', links: {}, criteria: ['a'], createdAt: '2026-01-01T00:04:00Z' })) + add(make(HUMAN, COLLECTIONS.review, 'rev-v1', 'cid-rev-v1', { $type: COLLECTIONS.review, subject: ref(artV1), verdict: 'request_changes', findings: [{ severity: 'warning', body: 'more detail' }], createdAt: '2026-01-01T00:04:30Z' })) + const reqV2 = add(make(HUMAN, COLLECTIONS.artifactRequest, 'req-v2', 'cid-req-v2', { $type: COLLECTIONS.artifactRequest, goal: ref(goal), type: 'plan', basedOn: [ref(artV1)], assignee: AGENT_A, createdAt: '2026-01-01T00:05:00Z' })) + const artV2 = add(make(AGENT_A, COLLECTIONS.artifact, 'plan-v2', 'cid-plan-v2', { $type: COLLECTIONS.artifact, request: ref(reqV2), goal: ref(goal), type: 'plan', prev: ref(artV1), body: 'v2', links: {}, criteria: ['a', 'b'], createdAt: '2026-01-01T00:06:00Z' })) + add(make(AGENT_A, COLLECTIONS.review, 'rev-v2', 'cid-rev-v2', { $type: COLLECTIONS.review, subject: ref(artV2), verdict: 'approve', findings: [], createdAt: '2026-01-01T00:06:15Z' })) + add(make(AGENT_A, COLLECTIONS.checkrun, 'chk-v2', 'cid-chk-v2', { $type: COLLECTIONS.checkrun, artifact: ref(artV2), commit: 'deadbeef', results: [{ name: 't', pass: true, log: 'ok' }], createdAt: '2026-01-01T00:06:45Z' })) + const reviewReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'review-req', 'cid-review-req', { $type: COLLECTIONS.artifactRequest, goal: ref(goal), type: 'review', subject: ref(artV2), basedOn: [ref(artV2)], assignee: AGENT_A, createdAt: '2026-01-01T00:07:00Z' })) + return { records, spaceUri: space.uri, requestUri: reviewReq.uri, requestCid: reviewReq.cid, subjectRef: ref(artV2), v1Ref: ref(artV1), v2Ref: ref(artV2) } +} + +function buildReviewBundle(records, scenario) { + const store = new MemoryRecordStore() + records.forEach((r) => store.put(r)) + const index = materialize(store, { spaceUri: scenario.spaceUri, asOf: AS_OF }) + return buildTurnBundle(index, scenario.requestUri, scenario.requestCid) +} + +describe('buildTurnBundle (review requests)', () => { + it('surfaces the subject and seeds its ancestry/findings/checkruns; a subject also in basedOn is not duplicated', () => { + const scenario = reviewRequestScenario() + const bundle = buildReviewBundle(scenario.records, scenario) + + assert.equal(bundle.request.type, 'review') + assert.ok(bundle.subject) + assert.equal(bundle.subject.uri, scenario.subjectRef.uri) + assert.equal(bundle.subject.type, 'plan') + + // Subject (v2) + its ancestry (v1) both flow in, each exactly once despite v2 being in basedOn AND + // the subject. + assert.deepEqual( + bundle.basedOn.map((a) => a.uri), + [scenario.v1Ref.uri, scenario.v2Ref.uri], + ) + assert.equal(bundle.basedOn.filter((a) => a.uri === scenario.v2Ref.uri).length, 1) + + // Prior findings on both versions and the v2 checkrun ride in. + assert.deepEqual( + bundle.reviewFindings.map((r) => [r.subject.uri, r.verdict]), + [ + [scenario.v1Ref.uri, 'request_changes'], + [scenario.v2Ref.uri, 'approve'], + ], + ) + assert.deepEqual(bundle.checkruns.map((c) => c.artifact.uri), [scenario.v2Ref.uri]) + }) + + it('is invariant under 100 deterministic random arrival permutations', () => { + const scenario = reviewRequestScenario() + const expected = buildReviewBundle(scenario.records, scenario) + for (let seed = 1; seed <= 100; seed += 1) { + const actual = buildReviewBundle(shuffled(scenario.records, seed), scenario) + assert.deepEqual(actual, expected, `seed ${seed}`) + } + }) +}) diff --git a/packages/lexicons/lexicons/com.disnetdev.radial.review.json b/packages/lexicons/lexicons/com.disnetdev.radial.review.json index d18914d..d4d8ed9 100644 --- a/packages/lexicons/lexicons/com.disnetdev.radial.review.json +++ b/packages/lexicons/lexicons/com.disnetdev.radial.review.json @@ -14,7 +14,7 @@ }, "main": { "type": "record", - "key": "tid", + "key": "any", "record": { "type": "object", "required": ["subject", "verdict", "findings", "createdAt"], -- knotmirror 0.0.1 From 8f3d6deccd9ecebf60551cab70d17587dd2e9b93 Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 13:20:08 -0700 Subject: [PATCH 05/13] daemon: dispatch and run review turns end-to-end - turn-socket: replace the optional artifactType with a fail-closed discriminated TurnMode ({artifact,type} | {review,subject}); add #submitReview (daemon owns subject+request from context, full boundary validation of verdict/findings), deterministic review- rkey, crash-safe adoption keyed on subject/request only (findings/verdict may differ on a retry), and mutual exclusion both ways sharing the submit reservation. Add TurnObservation.review. - turn: synthetic built-in REVIEW_TYPE (never registry data); derive and verify the turn mode against requestRecord.type (mismatch -> no launch); review turns get a read-only checkout, commit-pinned to the subject's links.commit when present (checkoutCommit) else default branch, and the operator GH_TOKEN for PR recon. Outcome classification handles review (fulfilled) and both-terminals (crashed) via exported classifyTurnObservation. - dispatch: review branch in selectDispatchable (resolve subject, select a review-producing actor by the same assigned/deterministic path, gates, bundle, artifactType=REVIEW_TYPE) never hitting the registry; #launch pins the subject commit as checkoutRef. - harness/bundle-writer: review prompt mode; "## Under review" summary section. - tests: socket happy-path/mutual-exclusion/validation/adoption/concurrency; turn classification + read-only + commit-pin + GH_TOKEN + mode mismatch; dispatch selection matrix rewrite + review E2E via LocalPds. Co-Authored-By: Claude Fable 5 --- packages/daemon/src/bundle-writer.ts | 3 + packages/daemon/src/dispatch.ts | 46 +++- packages/daemon/src/harness.ts | 20 +- packages/daemon/src/turn-socket.ts | 152 +++++++++++-- packages/daemon/src/turn.ts | 160 +++++++++++--- packages/daemon/test/bundle-writer.test.mjs | 29 +++ packages/daemon/test/dispatch.test.mjs | 169 +++++++++++++-- packages/daemon/test/harness.test.mjs | 20 ++ packages/daemon/test/turn-socket.test.mjs | 229 +++++++++++++++++++- packages/daemon/test/turn.test.mjs | 186 ++++++++++++++++ 10 files changed, 943 insertions(+), 71 deletions(-) diff --git a/packages/daemon/src/bundle-writer.ts b/packages/daemon/src/bundle-writer.ts index 6259b76..cabab9a 100644 --- a/packages/daemon/src/bundle-writer.ts +++ b/packages/daemon/src/bundle-writer.ts @@ -17,6 +17,9 @@ function summarizeBundle(bundle: PlanTurnBundle): string { '', '## Project', `${bundle.project.name} — ${bundle.project.gitUrl} (${bundle.project.defaultBranch})`, + ...(bundle.subject + ? ['', '## Under review', `${bundle.subject.type} ${bundle.subject.uri}`] + : []), '', '## Based on', ...(bundle.basedOn.length > 0 diff --git a/packages/daemon/src/dispatch.ts b/packages/daemon/src/dispatch.ts index 95e7894..5652dd8 100644 --- a/packages/daemon/src/dispatch.ts +++ b/packages/daemon/src/dispatch.ts @@ -16,7 +16,7 @@ import type { ActorRegistry, LoadedActor } from './actors.js' import { parseGitHubPullUrl, parseGitHubRepo, type ForgeAdapter } from './forge.js' import type { TurnLedger } from './ledger.js' import { implBranchName, planArtifactRkey } from './turn-socket.js' -import { IMPLEMENTATION_TYPE, turnContainerLabel, type TurnInput, type TurnResult } from './turn.js' +import { IMPLEMENTATION_TYPE, REVIEW_TYPE, REVIEW_TYPE_NAME, turnContainerLabel, type TurnInput, type TurnResult } from './turn.js' /** A resolved v2 predecessor for an implementation request: the exact prior artifact plus its * branch/PR links, used to decide branch reuse and to stamp `prev`. */ @@ -41,6 +41,9 @@ export interface Dispatchable { bundle: TurnBundle /** Present only for `implementation` requests (the exact built-in type name). */ implementation?: ImplementationDispatch + /** Present only for `review` requests: the subject under review and, when the subject links an + * exact commit, the commit the read-only checkout is pinned to. */ + review?: { subject: StrongRef; commit?: string } } const refKey = (reference: StrongRef): string => `${reference.uri}#${reference.cid}` @@ -135,6 +138,11 @@ export function selectDispatchable( onReject?: (requestUri: string, reason: string) => void, ): Dispatchable[] { const registry = new Map(index.artifactTypes.map((type) => [type.value.name, type.value])) + const allArtifacts: Array> = [ + ...index.goals.flatMap((view) => view.artifacts), + ...index.projects.flatMap((view) => view.artifacts), + ] + const artifactByRef = new Map(allArtifacts.map((artifact) => [refKey(artifact), artifact])) const results: Dispatchable[] = [] for (const goalView of index.goals) { @@ -143,10 +151,31 @@ export function selectDispatchable( if (goalView.archived || goalView.target.value.closed) continue for (const request of goalView.openRequests) { const type = request.value.type - const artifactType = registry.get(type) - // Silently skip anything that isn't a dispatchable goal-scoped artifact type: no such - // registered type, a project-scoped type (dispatched elsewhere), or `review` (Phase 5). - if (!artifactType || artifactType.scope !== 'goal' || type === 'review') continue + + // Resolve the artifact type this request dispatches with, and (for review requests) the + // subject under review. `review` is deliberately NOT registry data — it must never hit + // registry.get; it uses the synthetic built-in REVIEW_TYPE. A review request only materializes + // when its subject resolves under the same target (materializer.ts), so the subject resolution + // here always succeeds for a materialized review request; the guards are defensive. + let artifactType: ArtifactTypeRecord + let review: { subject: StrongRef; commit?: string } | undefined + if (type === REVIEW_TYPE_NAME) { + const subject = request.value.subject + if (!subject) continue + const subjectArtifact = artifactByRef.get(refKey(subject)) + if (!subjectArtifact) continue + artifactType = REVIEW_TYPE + review = { + subject, + ...(subjectArtifact.value.links?.commit ? { commit: subjectArtifact.value.links.commit } : {}), + } + } else { + const registered = registry.get(type) + // Silently skip anything that isn't a dispatchable goal-scoped artifact type: no such + // registered type, or a project-scoped type (dispatched elsewhere). + if (!registered || registered.scope !== 'goal') continue + artifactType = registered + } const author = index.members.find( (member) => member.did === request.did && member.active && member.kind === 'human', @@ -255,6 +284,7 @@ export function selectDispatchable( artifactType, bundle, ...(implementation ? { implementation } : {}), + ...(review ? { review } : {}), }) } } @@ -407,6 +437,12 @@ export class TurnDispatcher { this.#deps.log?.(`could not validate predecessor PR ${predecessor.prUrl} for ${uri}: ${error instanceof Error ? error.message : String(error)}; opening a fresh branch`) } } + } else if (item.review?.commit) { + // A review turn takes the non-impl path: no branch, read-only checkout, pinned to the exact + // commit the subject implementation links so the reviewer reads precisely the reviewed code. + // A subject without a linked commit (a plan/non-code artifact) leaves checkoutRef unset, so + // turn.ts clones the default branch read-only. + checkoutRef = item.review.commit } const turnInput: TurnInput = { diff --git a/packages/daemon/src/harness.ts b/packages/daemon/src/harness.ts index 7d72878..7aca528 100644 --- a/packages/daemon/src/harness.ts +++ b/packages/daemon/src/harness.ts @@ -13,6 +13,10 @@ export interface HarnessInvocationInput { /** True for an implementation turn: the prompt tells the agent to commit, push, open or update * the PR, and submit the resulting branch/commit/PR links. */ implementation?: boolean + /** True for a review turn: the prompt tells the agent to judge the subject and submit a verdict + * (or ask a question), and never to modify the read-only checkout. Mutually exclusive with + * `implementation`. */ + review?: boolean } export interface Harness { @@ -45,11 +49,25 @@ export function composeBrief(type: ArtifactTypeRecord, request: ArtifactRequestR * how to deliver its result — through the sidecar RPCs, never through stdout (which is ignored by * design; a turn that only prints is classified `crashed`, see turn.ts). */ -function buildPrompt(input: { bundleDir: string; workdir: string; implementation?: boolean }): string { +function buildPrompt(input: { bundleDir: string; workdir: string; implementation?: boolean; review?: boolean }): string { const context = [ `Read your brief at ${input.bundleDir}/brief.md — the artifact-type brief plus this request's extra instructions.`, `For full context, also read ${input.bundleDir}/bundle.md (a human-readable summary of the goal, project, based-on artifacts, prior review findings, and thread) and ${input.bundleDir}/bundle.json (the same data, structured).`, ] + if (input.review) { + return [ + ...context, + `The artifact under review is named in the "## Under review" section of ${input.bundleDir}/bundle.md (and in bundle.json as \`subject\`). Judge it against the goal, its criteria, the prior review findings, and the checkruns in your bundle.`, + `The project's checkout is at ${input.workdir}, mounted READ-ONLY — inspect it for reconnaissance, but do not modify it.`, + 'Forge reconnaissance (`gh pr view`, `gh api`, and ordinary web fetches) is allowed so you can read the subject implementation\'s PR. Do not merge or modify anything.', + '', + 'When you are ready, do exactly ONE of the following:', + '- Deliver your verdict: write your findings as a JSON array to a file (each finding an object with `severity` ("info"|"warning"|"error"), `body`, and optional `path`/`line`), then run `radial review submit --verdict --findings-file `. Submit an empty `[]` findings array if you have none.', + '- If you cannot judge the subject without more input: run `radial message post --body ""` instead, and stop.', + '', + 'Do not print your result to stdout — it is ignored. `radial` is on PATH and is already authenticated for this turn; do not look for or ask for credentials.', + ].join('\n') + } if (input.implementation) { return [ ...context, diff --git a/packages/daemon/src/turn-socket.ts b/packages/daemon/src/turn-socket.ts index 39c473b..aa51c03 100644 --- a/packages/daemon/src/turn-socket.ts +++ b/packages/daemon/src/turn-socket.ts @@ -12,6 +12,8 @@ import { type MessageRecord, type RadialRecord, type RecordByCollection, + type ReviewFinding, + type ReviewRecord, type StrongRef, type TurnRpcResponse, } from '@radial/core' @@ -34,20 +36,31 @@ export function sha256Hex(text: string): string { return createHash('sha256').update(text).digest('hex') } +/** + * The daemon-owned, fail-closed turn mode. An `artifact` turn may only submit an artifact of the + * named `type`; a `review` turn may only submit a verdict on the named `subject`. runTurn populates + * this from the request record and verifies it against `requestRecord.type`, so submitArtifact can + * never silently default to a plan for a review request (and vice versa). + */ +export type TurnMode = + | { kind: 'artifact'; type: string } + | { kind: 'review'; subject: StrongRef } + export interface TurnRequestContext { token: string /** The goal-scoped request being fulfilled. */ request: { uri: string; cid: string; goal: StrongRef } client: TurnRecordWriter now?: () => string - /** The artifact type this turn produces, owned by the daemon. */ - artifactType?: string + /** Discriminated turn mode, owned by the daemon (see TurnMode). */ + mode: TurnMode /** Daemon-owned implementation provenance. */ implementation?: { gitUrl: string; branch: string; prev?: StrongRef } } export interface TurnObservation { artifact?: StrongRef + review?: StrongRef questions: StrongRef[] } @@ -109,6 +122,14 @@ export function implArtifactRkey(requestUri: string, requestCid: string): string return artifactRkey(requestUri, requestCid, 'impl-') } +/** `review-` prefixed deterministic rkey for the verdict answering a review request. Distinct + * prefix from the artifact rkeys so a review turn and an (impossible, but defensively distinct) + * artifact turn for the same request never collide, and a retried review turn recomputes the same + * rkey and adopts rather than double-writing. The lexicon key was changed to `any` to permit it. */ +export function reviewRkey(requestUri: string, requestCid: string): string { + return artifactRkey(requestUri, requestCid, 'review-') +} + /** Deterministic push branch for a fresh implementation turn: `radial/impl-<12 hex of * sha256(requestUri#requestCid)>`. Stable across retries so a re-push targets the same branch. (A * v2 turn reusing an open predecessor PR pushes to the predecessor's branch instead.) */ @@ -129,15 +150,10 @@ function concatBytes(chunks: Uint8Array[]): Uint8Array { return result } -interface ParsedEnvelope { - method: 'submitArtifact' | 'askQuestion' - token: string - body: string - criteria?: string[] - branch?: string - commit?: string - pr?: string -} +type ParsedEnvelope = + | { method: 'submitArtifact'; token: string; body: string; criteria?: string[]; branch?: string; commit?: string; pr?: string } + | { method: 'askQuestion'; token: string; body: string } + | { method: 'submitReview'; token: string; verdict: 'approve' | 'request_changes'; findings: ReviewFinding[] } const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value) @@ -147,11 +163,43 @@ const isObject = (value: unknown): value is Record => const isShaShaped = (value: unknown): value is string => typeof value === 'string' && /^[0-9a-fA-F]{7,64}$/.test(value) +/** + * Full, defense-in-depth validation of a submitReview envelope at the untrusted socket edge. The + * daemon owns subject/request (from turn context, not the wire), so only verdict + findings are + * parsed here. Findings mirror the review lexicon exactly: ≤100 entries, each with a valid severity, + * a ≤10,000-char body, an optional string path, and an optional integer line. Anything else → reject + * (undefined, surfaced to the caller as an invalid-envelope error). + */ +function parseReviewEnvelope(raw: Record, token: string): ParsedEnvelope | undefined { + const { verdict, findings } = raw + if (verdict !== 'approve' && verdict !== 'request_changes') return undefined + if (!Array.isArray(findings) || findings.length > 100) return undefined + const parsed: ReviewFinding[] = [] + for (const finding of findings) { + if (!isObject(finding)) return undefined + const { path, line, severity, body } = finding + if (severity !== 'info' && severity !== 'warning' && severity !== 'error') return undefined + if (typeof body !== 'string' || body.length > 10_000) return undefined + if (path !== undefined && typeof path !== 'string') return undefined + if (line !== undefined && (typeof line !== 'number' || !Number.isInteger(line))) return undefined + parsed.push({ + severity, + body, + ...(path !== undefined ? { path } : {}), + ...(line !== undefined ? { line } : {}), + }) + } + return { method: 'submitReview', token, verdict, findings: parsed } +} + function parseEnvelope(raw: unknown): ParsedEnvelope | undefined { if (!isObject(raw)) return undefined - const { method, token, body, criteria, branch, commit, pr } = raw + const { method, token } = raw + if (typeof token !== 'string') return undefined + if (method === 'submitReview') return parseReviewEnvelope(raw, token) if (method !== 'submitArtifact' && method !== 'askQuestion') return undefined - if (typeof token !== 'string' || typeof body !== 'string') return undefined + const { body, criteria, branch, commit, pr } = raw + if (typeof body !== 'string') return undefined if (method === 'submitArtifact') { let parsedCriteria: string[] | undefined if (criteria !== undefined) { @@ -321,6 +369,7 @@ export class TurnSocketServer { if (envelope.method === 'askQuestion' && envelope.body.length > limits.messageBodyChars) { return { ok: false, error: `body exceeds ${limits.messageBodyChars} characters` } } + if (envelope.method === 'submitReview') return this.#submitReview(envelope) return envelope.method === 'submitArtifact' ? this.#submitArtifact(envelope) : this.#askQuestion(envelope) } @@ -328,8 +377,13 @@ export class TurnSocketServer { return this.#context.now?.() ?? new Date().toISOString() } - async #submitArtifact(envelope: ParsedEnvelope): Promise { - if (this.#observation.artifact || this.#submitReserved) { + async #submitArtifact(envelope: Extract): Promise { + // Fail-closed mutual exclusion: a review turn cannot emit an artifact. This is the daemon-side + // enforcement of the §13 invariant that a review turn can only produce a verdict of its subject. + if (this.#context.mode.kind === 'review') { + return { ok: false, error: 'this is a review turn; only a review verdict may be submitted, not an artifact' } + } + if (this.#observation.artifact || this.#observation.review || this.#submitReserved) { return { ok: false, error: 'an artifact was already submitted for this request' } } // Reserve synchronously, before the first `await` below, so a second concurrent submit (a @@ -338,7 +392,7 @@ export class TurnSocketServer { // silently adopt a different body than the one that actually landed. this.#submitReserved = true const { request, client } = this.#context - const type = this.#context.artifactType ?? 'plan' + const type = this.#context.mode.type let links: ArtifactRecord['links'] = {} let prev: StrongRef | undefined @@ -432,7 +486,7 @@ export class TurnSocketServer { return { ok: true, ref } } - async #askQuestion(envelope: ParsedEnvelope): Promise { + async #askQuestion(envelope: Extract): Promise { const { request, client } = this.#context const record: MessageRecord = { $type: COLLECTIONS.message, @@ -446,4 +500,68 @@ export class TurnSocketServer { this.#observation.questions.push(ref) return { ok: true, ref } } + + async #submitReview(envelope: Extract): Promise { + const { request, client, mode } = this.#context + // Fail-closed mutual exclusion: submitReview is only valid on a review turn. An artifact turn + // that somehow issues it is rejected (the daemon owns no subject to anchor a verdict to). + if (mode.kind !== 'review') { + return { ok: false, error: 'this is not a review turn; a review verdict may not be submitted' } + } + if (this.#observation.review || this.#observation.artifact || this.#submitReserved) { + return { ok: false, error: 'a review was already submitted for this request' } + } + // Reserve synchronously before the first await — shared with #submitArtifact so a review turn's + // reservation covers both submit paths (concurrent submits can never both land). + this.#submitReserved = true + const subject = mode.subject + // The daemon constructs the record: subject + request come from turn context, NEVER the + // envelope, so a review turn structurally cannot review anything but its named subject. + const record: ReviewRecord = { + $type: COLLECTIONS.review, + subject, + request: { uri: request.uri, cid: request.cid }, + verdict: envelope.verdict, + findings: envelope.findings, + createdAt: this.#now(), + } + const rkey = reviewRkey(request.uri, request.cid) + let ref: StrongRef + try { + ref = await client.create(COLLECTIONS.review, record, { rkey }) + } catch (error) { + if (error instanceof XrpcError && error.status === 400 && error.error === 'RecordAlreadyExists') { + const existing = await client.getOwnRecord(COLLECTIONS.review, rkey) + if (!existing) { + // The PDS claims the record exists but it isn't fetchable — a hard error, not an + // adoption. Release the reservation to allow a genuine later retry. + this.#submitReserved = false + throw error + } + const current = existing.value as ReviewRecord + // Adopt iff the deterministic-rkey record was written for THIS same request+subject by this + // actor — the deterministic rkey already proves same request+actor. A retried review turn + // legitimately produces DIFFERENT findings/verdict, so those are deliberately NOT compared; + // only the anchoring subject and request backref must match. A mismatch means the rkey was + // somehow claimed for a different subject/request — refuse rather than silently adopt. + if ( + current.$type !== COLLECTIONS.review || + !current.request || + current.request.uri !== request.uri || + current.request.cid !== request.cid || + current.subject.uri !== subject.uri || + current.subject.cid !== subject.cid + ) { + this.#submitReserved = false + throw new Error(`refusing to adopt review record at ${rkey} with a mismatched subject/request`) + } + ref = { uri: existing.uri, cid: existing.cid } + } else { + this.#submitReserved = false + throw error + } + } + this.#observation.review = ref + return { ok: true, ref } + } } diff --git a/packages/daemon/src/turn.ts b/packages/daemon/src/turn.ts index 9f4c786..e4203c8 100644 --- a/packages/daemon/src/turn.ts +++ b/packages/daemon/src/turn.ts @@ -2,15 +2,47 @@ import { appendFile, chmod, mkdir, rm } from 'node:fs/promises' import { dirname, join } from 'node:path' import { COLLECTIONS, type ArtifactRequestRecord, type ArtifactTypeRecord, type TurnBundle, type StrongRef } from '@radial/core' import type { LoadedActor } from './actors.js' -import { checkoutRepo, writeBundle } from './bundle-writer.js' +import { checkoutCommit, checkoutRepo, writeBundle } from './bundle-writer.js' import { RADIAL_HOME_TMPFS, type ContainerOutputStream, type ContainerRunner, type ContainerSpec } from './container.js' import { composeBrief, type Harness } from './harness.js' -import { TurnSocketServer, implArtifactRkey, planArtifactRkey } from './turn-socket.js' +import { TurnSocketServer, implArtifactRkey, planArtifactRkey, type TurnMode, type TurnObservation, type TurnRequestContext } from './turn-socket.js' /** The exact built-in artifact-type name that gets the implementation code path (rw /work and * git identity). Every other type dispatches as a plan-style turn. */ export const IMPLEMENTATION_TYPE = 'implementation' +/** The built-in `review` type name. A request of this type dispatches a review turn whose terminal + * record is a `com.disnetdev.radial.review` verdict rather than an artifact. */ +export const REVIEW_TYPE_NAME = 'review' + +/** + * Synthetic, built-in artifact type for review turns. Review is deliberately NOT registry data — it + * ships in the daemon so a space never has to register it, and so a member can't redefine what a + * review turn is by writing a registry record. Only `name`/`brief`/`outputSpec`/`scope` are + * meaningful (composeBrief reads them); `space`/`createdAt` are placeholders since this is never a + * real PDS record. + */ +export const REVIEW_TYPE: ArtifactTypeRecord = { + $type: COLLECTIONS.artifactType, + space: { uri: 'at://radial/builtin/review', cid: 'builtin-review' }, + name: REVIEW_TYPE_NAME, + brief: [ + 'You are reviewing the artifact shown under `## Under review` in your bundle. Evaluate it', + 'against the goal, its criteria, the prior review findings and the checkrun results also in the', + 'bundle. Do NOT modify the checkout — it is mounted read-only for reconnaissance only. Deliver', + 'a verdict and structured findings with', + '`radial review submit --verdict --findings-file `; if you', + 'cannot judge the subject without more information, ask a question with `radial message post`', + 'instead and stop.', + ].join(' '), + outputSpec: { + format: 'json', + description: 'A verdict (approve or request_changes) plus a JSON array of structured findings.', + }, + scope: 'goal', + createdAt: '1970-01-01T00:00:00.000Z', +} + export type TurnOutcome = 'fulfilled' | 'awaiting_input' | 'crashed' export interface TurnResult { @@ -19,6 +51,26 @@ export interface TurnResult { label: string } +/** + * Classify a turn purely from what the harness told the socket — never from stdout/exit code. A + * review verdict or an artifact is a fulfillment (`acceptedRef` is whichever landed); a bare + * question is awaiting-input; neither is a crash. An observation carrying BOTH an artifact and a + * review is a bug (the socket's mutual exclusion makes it unreachable) — it is classified crashed + * with `reason: 'both_terminals'`, never silently preferring one. `reason: 'empty'` distinguishes + * the produced-nothing crash so the caller can log the right diagnostic. + */ +export function classifyTurnObservation(observation: TurnObservation): { + outcome: TurnOutcome + acceptedRef?: StrongRef + reason?: 'both_terminals' | 'empty' +} { + if (observation.artifact && observation.review) return { outcome: 'crashed', reason: 'both_terminals' } + if (observation.review) return { outcome: 'fulfilled', acceptedRef: observation.review } + if (observation.artifact) return { outcome: 'fulfilled', acceptedRef: observation.artifact } + if (observation.questions.length > 0) return { outcome: 'awaiting_input' } + return { outcome: 'crashed', reason: 'empty' } +} + export interface TurnInput { bundle: TurnBundle request: { uri: string; cid: string; goal: StrongRef } @@ -61,6 +113,15 @@ export interface TurnDeps { allowedSchemes: string[] githubToken?: string }) => Promise<{ path: string; commit: string }> + /** Commit-pinned checkout, used for review turns whose subject links an exact commit. Defaults to + * bundle-writer's checkoutCommit. */ + checkoutCommit?: (input: { + gitUrl: string + commit: string + dest: string + allowedSchemes: string[] + githubToken?: string + }) => Promise<{ path: string; commit: string }> now?: () => string makeToken?: () => string anthropicApiKey?: string @@ -223,6 +284,7 @@ export async function runTurn(input: TurnInput, deps: TurnDeps): Promise 0) { - return { outcome: 'awaiting_input', label } + return { + outcome: classified.outcome, + ...(classified.acceptedRef ? { acceptedRef: classified.acceptedRef } : {}), + label, } - deps.log?.( - `turn ${input.request.uri} exited without an artifact or question; marked crashed` + - (input.logPath ? ` (container output: ${input.logPath})` : ''), - ) - return { outcome: 'crashed', label } } catch (error) { await saveTurnError(input, error, [ token, diff --git a/packages/daemon/test/bundle-writer.test.mjs b/packages/daemon/test/bundle-writer.test.mjs index 86c1240..735ba56 100644 --- a/packages/daemon/test/bundle-writer.test.mjs +++ b/packages/daemon/test/bundle-writer.test.mjs @@ -38,6 +38,35 @@ it('writeBundle round-trips bundle.json and writes brief.md', async () => { assert.match(summary, /radial-ng/) }) +it('writeBundle summary includes an "Under review" section naming the subject when present', async () => { + const dir = await mkdtemp(join(tmpdir(), 'radial-bundle-review-')) + const target = join(dir, 'turn-review') + const reviewBundle = { + ...bundle, + request: { ...bundle.request, type: 'review' }, + subject: { + uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/impl-1', + cid: 'subj-cid', + type: 'implementation', + body: 'the implementation', + links: { commit: 'b'.repeat(40) }, + createdAt: '2026-01-01T00:04:00Z', + }, + } + await writeBundle({ bundle: reviewBundle, brief: '# review brief\n', dir: target }) + const summary = await readFile(join(target, 'bundle.md'), 'utf8') + assert.match(summary, /## Under review/) + assert.match(summary, /implementation at:\/\/did:plc:agent\/com\.disnetdev\.radial\.artifact\/impl-1/) +}) + +it('writeBundle summary omits the "Under review" section for a non-review bundle', async () => { + const dir = await mkdtemp(join(tmpdir(), 'radial-bundle-noreview-')) + const target = join(dir, 'turn-plain') + await writeBundle({ bundle, brief: '# plan brief\n', dir: target }) + const summary = await readFile(join(target, 'bundle.md'), 'utf8') + assert.doesNotMatch(summary, /## Under review/) +}) + it('assertGitUrlAllowed rejects file:// by default but allows https://, and allows file:// when opted in', () => { assert.throws(() => assertGitUrlAllowed('file:///tmp/repo', ['https']), /not allowed/) assert.doesNotThrow(() => assertGitUrlAllowed('https://example.test/repo.git', ['https'])) diff --git a/packages/daemon/test/dispatch.test.mjs b/packages/daemon/test/dispatch.test.mjs index ae608ea..5bc51ea 100644 --- a/packages/daemon/test/dispatch.test.mjs +++ b/packages/daemon/test/dispatch.test.mjs @@ -15,6 +15,7 @@ import { TurnLedger, implBranchName, planArtifactRkey, + reviewRkey, runTurn, selectDispatchable, } from '../dist/index.js' @@ -292,29 +293,98 @@ it('generalization: dispatches a goal-scoped NON-plan registered type when an ac ledger.close() }) -it('skips a review-type request (handled elsewhere) even when goal-scoped and actor-capable', () => { - const { records } = buildScenario({ requestOverrides: { type: 'review' } }) - // Register a goal-scoped 'review' type so scope alone doesn't filter it — the `name === 'review'` - // gate is what must skip it. - const withReview = [ - ...records, - mk(ROOT, COLLECTIONS.artifactType, 'type-review', 'cid-type-review', { - $type: COLLECTIONS.artifactType, - space: ref(records[0]), - name: 'review', - brief: 'Review it.', - outputSpec: { format: 'markdown', description: 'A review' }, - scope: 'goal', - createdAt: '2026-01-01T00:00:12Z', - }), - ] - const index = materialize(store(withReview), { spaceUri: SPACE_URI }) +// A valid review scenario: the base plan request is fulfilled by an artifact (so it drops out of the +// work queue), and a review request pins that artifact as its subject. `review` is never registry +// data — a review request materializes purely from its resolving same-target subject. +function withReviewRequest({ assignee = AGENT, subjectLinks = { commit: 'a'.repeat(40) } } = {}) { + const base = buildScenario() + const artifact = mk(AGENT, COLLECTIONS.artifact, 'plan-art', 'cid-plan-art', { + $type: COLLECTIONS.artifact, + request: ref(base.request), + goal: ref(base.goal), + type: 'plan', + body: 'the plan', + links: subjectLinks, + createdAt: '2026-01-01T00:04:00Z', + }) + const reviewReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'review-req', 'cid-review-req', { + $type: COLLECTIONS.artifactRequest, + goal: ref(base.goal), + type: 'review', + subject: ref(artifact), + basedOn: [], + ...(assignee ? { assignee } : {}), + createdAt: '2026-01-01T00:05:00Z', + }) + return { ...base, artifact, reviewReq, records: [...base.records, artifact, reviewReq] } +} + +it('dispatches a review-type request to a review-producing actor, pinning the checkout to the subject commit', () => { + const { records, reviewReq } = withReviewRequest() + const index = materialize(store(records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT, ['plan', 'review'])]) + const result = selectDispatchable(index, actors, ledger) + // The base plan request is fulfilled by the artifact; only the review request is dispatchable. + assert.deepEqual(uris(result), [reviewReq.uri]) + assert.equal(result[0].artifactType.name, 'review') + assert.equal(result[0].actor.did, AGENT) + assert.deepEqual(result[0].review.subject, reviewReq.value.subject) + assert.equal(result[0].review.commit, 'a'.repeat(40)) + assert.ok(result[0].bundle.subject) + assert.equal(result[0].bundle.subject.uri, reviewReq.value.subject.uri) + ledger.close() +}) + +it('a review request whose subject links no commit leaves review.commit unset (default-branch checkout)', () => { + const { records, reviewReq } = withReviewRequest({ subjectLinks: {} }) + const index = materialize(store(records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT, ['plan', 'review'])]) + const result = selectDispatchable(index, actors, ledger) + assert.deepEqual(uris(result), [reviewReq.uri]) + assert.equal(result[0].review.commit, undefined) + ledger.close() +}) + +it('an unassigned review request is picked up by the deterministic review-capable agent', () => { + const { records, reviewReq } = withReviewRequest({ assignee: undefined }) + const index = materialize(store(records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT, ['plan', 'review'])]) + const result = selectDispatchable(index, actors, ledger) + assert.deepEqual(uris(result), [reviewReq.uri]) + assert.equal(result[0].actor.did, AGENT) + assert.equal(result[0].artifactType.name, 'review') + ledger.close() +}) + +it('a review request with an unanswered question from the assignee is gated (awaiting input)', () => { + const { records, reviewReq, goal } = withReviewRequest() + const question = mk(AGENT, COLLECTIONS.message, 'q-review', 'cid-q-review', { + $type: COLLECTIONS.message, + goal: ref(goal), + body: 'which standard applies?', + mentions: [], + re: ref(reviewReq), + createdAt: '2026-01-01T00:06:00Z', + }) + const index = materialize(store([...records, question]), { spaceUri: SPACE_URI }) const ledger = new TurnLedger() const actors = registryFor([actorFor(AGENT, ['plan', 'review'])]) assert.deepEqual(selectDispatchable(index, actors, ledger), []) ledger.close() }) +it('does not dispatch a review request to an actor that does not produce reviews', () => { + const { records } = withReviewRequest() + const index = materialize(store(records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT, ['plan'])]) + assert.deepEqual(selectDispatchable(index, actors, ledger), []) + ledger.close() +}) + it('skips a request whose type is not a registered artifact type', () => { const { records } = buildScenario({ requestOverrides: { type: 'nonesuch' } }) const index = materialize(store(records), { spaceUri: SPACE_URI }) @@ -1054,3 +1124,68 @@ it('unassigned request with an unanswered agent question is not dispatched (fres assert.deepEqual(uris(selectDispatchable(index2, actors, ledger)), [base.request.uri]) ledger.close() }) + +// --- Review turn end-to-end via TurnDispatcher ------------------------------- + +it('E2E: a review request drives a real review verdict and fulfills the request in a fresh materialize', async () => { + await withTempDir(async (runsDir) => { + const pds = new LocalPds(AGENT) + const session = await createSession(pds.service, pds.handle, 'pw', pds.fetch.bind(pds)) + const client = new CredentialClient(session, pds.fetch.bind(pds)) + // No subject commit so the turn takes the default-branch (noopCheckout) path; the commit-pin path + // is covered by turn.test.mjs against a checkoutCommit stub. + const { records, reviewReq } = withReviewRequest({ subjectLinks: {} }) + const recordStore = store(records) + const index = materialize(recordStore, { spaceUri: SPACE_URI }) + const actors = registryFor([{ ...actorFor(AGENT, ['plan', 'review']), client }]) + const ledger = new TurnLedger() + + const { dispatcher } = makeDispatcher({ + ledger, + runsDir, + runnerFn: async (spec) => { + const response = await sendLine(hostSocketPath(spec), { + method: 'submitReview', + token: spec.env.RADIAL_TURN_TOKEN, + verdict: 'approve', + findings: [{ severity: 'info', body: 'looks good' }], + }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }, + }) + + dispatcher.pump(index, actors) + assert.equal(dispatcher.inFlight, 1) + await dispatcher.drain() + + const row = ledger.get(reviewReq.uri) + assert.equal(row.state, 'fulfilled') + const expectedRkey = reviewRkey(reviewReq.uri, reviewReq.cid) + assert.equal(row.acceptedRef.uri, `at://${AGENT}/${COLLECTIONS.review}/${expectedRkey}`) + + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.review) + assert.equal(stored.length, 1) + assert.deepEqual(stored[0].value.subject, reviewReq.value.subject) + assert.deepEqual(stored[0].value.request, { uri: reviewReq.uri, cid: reviewReq.cid }) + assert.equal(stored[0].value.verdict, 'approve') + assert.deepEqual(stored[0].value.findings, [{ severity: 'info', body: 'looks good' }]) + + // A fresh, independent materialize that has ingested the written verdict shows the review request + // fulfilled (no longer open). + const written = stored[0] + const wrkey = written.uri.slice(written.uri.lastIndexOf('/') + 1) + recordStore.put({ + did: AGENT, + collection: COLLECTIONS.review, + rkey: wrkey, + uri: written.uri, + cid: written.cid, + rev: '0000000000009', + value: written.value, + }) + const index2 = materialize(recordStore, { spaceUri: SPACE_URI }) + assert.equal(index2.goals[0].openRequests.some((r) => r.uri === reviewReq.uri), false) + ledger.close() + }) +}) diff --git a/packages/daemon/test/harness.test.mjs b/packages/daemon/test/harness.test.mjs index 49c84ab..cd60ab2 100644 --- a/packages/daemon/test/harness.test.mjs +++ b/packages/daemon/test/harness.test.mjs @@ -88,6 +88,26 @@ it('ClaudeCodeHarness.invocation tolerates an empty models array by omitting --m assert.ok(!invocation.argv.includes('--model')) }) +it('review prompt directs the agent to judge the subject and submit a verdict without modifying the checkout', () => { + const invocation = new ClaudeCodeHarness().invocation({ + briefPath: '/bundle/brief.md', + bundleDir: '/bundle', + workdir: '/work', + models: [], + review: true, + }) + const prompt = invocation.argv[2] + + assert.match(prompt, /## Under review/) + assert.match(prompt, /READ-ONLY/) + assert.match(prompt, /do not modify it/) + assert.match(prompt, /radial review submit --verdict --findings-file/) + assert.match(prompt, /radial message post/) + // A review prompt must NOT contain the implementation push/PR workflow. + assert.doesNotMatch(prompt, /gh pr create/) + assert.doesNotMatch(prompt, /radial artifact submit/) +}) + it('implementation prompt owns the GitHub branch, commit, push, and PR workflow', () => { const invocation = new ClaudeCodeHarness().invocation({ briefPath: '/bundle/brief.md', diff --git a/packages/daemon/test/turn-socket.test.mjs b/packages/daemon/test/turn-socket.test.mjs index a779d9f..1eaf0dc 100644 --- a/packages/daemon/test/turn-socket.test.mjs +++ b/packages/daemon/test/turn-socket.test.mjs @@ -7,7 +7,7 @@ import { it } from 'node:test' import { CredentialClient, createSession } from '../../atproto/dist/index.js' import { COLLECTIONS } from '../../core/dist/index.js' import { LocalPds } from '../../atproto/test/local-pds.mjs' -import { TurnSocketServer, implArtifactRkey, planArtifactRkey } from '../dist/index.js' +import { TurnSocketServer, implArtifactRkey, planArtifactRkey, reviewRkey } from '../dist/index.js' const REQUEST = { uri: 'at://did:plc:human/com.disnetdev.radial.artifactRequest/req1', @@ -16,6 +16,8 @@ const REQUEST = { } const TOKEN = 'turn-token-1' const NOW = '2026-07-19T00:00:00.000Z' +const SUBJECT = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/impl-1', cid: 'subjcid' } +const REVIEW_MODE = { mode: { kind: 'review', subject: SUBJECT } } function sendLine(socketPath, obj) { return new Promise((resolve, reject) => { @@ -43,7 +45,8 @@ async function makeClient(pds) { async function startServer(directory, client, options = {}) { const socketPath = join(directory, `turn-${Math.random().toString(36).slice(2)}.sock`) - const context = { token: TOKEN, request: REQUEST, client, now: () => NOW, ...options.context } + // Default to a plan-style artifact turn; individual tests override `mode` via options.context. + const context = { token: TOKEN, request: REQUEST, client, now: () => NOW, mode: { kind: 'artifact', type: 'plan' }, ...options.context } const server = new TurnSocketServer(socketPath, context, options.limits ? { limits: options.limits } : {}) await server.listen() return { server, socketPath, context } @@ -229,7 +232,7 @@ it('rejects a mismatched turn token and writes no record', async () => { it('tcp transport: submitArtifact over a raw TCP connection to boundPort writes a plan artifact (no Docker needed)', async () => { const pds = new LocalPds('did:plc:agent-tcp') const client = await makeClient(pds) - const context = { token: TOKEN, request: REQUEST, client, now: () => NOW } + const context = { token: TOKEN, request: REQUEST, client, now: () => NOW, mode: { kind: 'artifact', type: 'plan' } } const server = new TurnSocketServer({ kind: 'tcp', host: '127.0.0.1', port: 0 }, context) await server.listen() try { @@ -284,7 +287,7 @@ it('implementation submit synchronously writes the deterministic artifact with v const prev = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/impl-old', cid: 'oldcid' } const branch = 'radial/impl-123456789abc' const { server, socketPath } = await startServer(directory, client, { - context: { artifactType: 'implementation', implementation: { gitUrl: 'https://github.com/acme/widget.git', branch, prev } }, + context: { mode: { kind: 'artifact', type: 'implementation' }, implementation: { gitUrl: 'https://github.com/acme/widget.git', branch, prev } }, }) try { const response = await sendLine(socketPath, { method: 'submitArtifact', token: TOKEN, body: 'done', branch, commit: 'a'.repeat(40), pr: 'https://github.com/acme/widget/pull/7' }) @@ -304,7 +307,7 @@ it('implementation submit rejects the wrong branch, noncanonical PR URLs, and cr const branch = 'radial/impl-123456789abc' const { server, socketPath } = await startServer(directory, client, { context: { - artifactType: 'implementation', + mode: { kind: 'artifact', type: 'implementation' }, implementation: { gitUrl: 'https://github.com/acme/widget.git', branch }, }, }) @@ -344,7 +347,7 @@ it('implementation adoption refuses an existing deterministic record with differ const client = await makeClient(pds) const branch = 'radial/impl-123456789abc' const context = { - artifactType: 'implementation', + mode: { kind: 'artifact', type: 'implementation' }, implementation: { gitUrl: 'https://github.com/acme/widget.git', branch }, } const frame = { @@ -371,3 +374,217 @@ it('implementation adoption refuses an existing deterministic record with differ } }) }) + +// --- Review turns --------------------------------------------------------- + +const findings = [{ severity: 'error', path: 'src/x.ts', line: 12, body: 'Bug here.' }] + +it('submitReview: writes a verdict anchored to the context subject and request backref, at the deterministic review- rkey', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-review') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { context: REVIEW_MODE }) + try { + const response = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'request_changes', + findings, + }) + assert.equal(response.ok, true) + const expectedRkey = reviewRkey(REQUEST.uri, REQUEST.cid) + assert.match(expectedRkey, /^review-[a-z2-7]+$/) + assert.equal(response.ref.uri, `at://${pds.did}/${COLLECTIONS.review}/${expectedRkey}`) + + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.review) + assert.equal(stored.length, 1) + const record = stored[0].value + // subject + request come from CONTEXT, never the envelope. + assert.deepEqual(record.subject, SUBJECT) + assert.deepEqual(record.request, { uri: REQUEST.uri, cid: REQUEST.cid }) + assert.equal(record.verdict, 'request_changes') + assert.deepEqual(record.findings, findings) + assert.equal(record.createdAt, NOW) + } finally { + await server.close() + } + }) +}) + +it('submitReview: an envelope-supplied subject/request is ignored — the daemon anchors from context', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-review-anchor') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { context: REVIEW_MODE }) + try { + const response = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [], + subject: { uri: 'at://did:plc:attacker/x/y', cid: 'evil' }, + request: { uri: 'at://did:plc:attacker/a/b', cid: 'evil2' }, + }) + assert.equal(response.ok, true) + const record = [...pds.records.values()].find((r) => r.value.$type === COLLECTIONS.review).value + assert.deepEqual(record.subject, SUBJECT) + assert.deepEqual(record.request, { uri: REQUEST.uri, cid: REQUEST.cid }) + } finally { + await server.close() + } + }) +}) + +it('mutual exclusion: submitReview is rejected on an artifact turn, submitArtifact is rejected on a review turn', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-mutex') + const client = await makeClient(pds) + + // Artifact (plan) turn: submitReview rejected. + const artifactTurn = await startServer(directory, client) + const reviewOnArtifact = await sendLine(artifactTurn.socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [], + }) + await artifactTurn.server.close() + assert.equal(reviewOnArtifact.ok, false) + assert.match(reviewOnArtifact.error, /not a review turn/) + + // Review turn: submitArtifact rejected. + const reviewTurn = await startServer(directory, client, { context: REVIEW_MODE }) + const artifactOnReview = await sendLine(reviewTurn.socketPath, { + method: 'submitArtifact', + token: TOKEN, + body: 'sneaky artifact', + }) + await reviewTurn.server.close() + assert.equal(artifactOnReview.ok, false) + assert.match(artifactOnReview.error, /review turn/) + + assert.equal(pds.records.size, 0) + }) +}) + +it('submitReview: rejects a bad verdict, an invalid severity, and >100 findings; writes no record', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-review-validation') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { context: REVIEW_MODE }) + try { + const badVerdict = await sendLine(socketPath, { method: 'submitReview', token: TOKEN, verdict: 'lgtm', findings: [] }) + assert.equal(badVerdict.ok, false) + + const badSeverity = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [{ severity: 'critical', body: 'x' }], + }) + assert.equal(badSeverity.ok, false) + + const oversizedBody = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [{ severity: 'info', body: 'x'.repeat(10_001) }], + }) + assert.equal(oversizedBody.ok, false) + + const tooMany = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: Array.from({ length: 101 }, () => ({ severity: 'info', body: 'x' })), + }) + assert.equal(tooMany.ok, false) + + assert.equal(pds.records.size, 0) + } finally { + await server.close() + } + }) +}) + +it('submitReview: adoption on retry with DIFFERENT findings succeeds (same subject/request), converging on one record', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-review-adopt') + const client = await makeClient(pds) + + const first = await startServer(directory, client, { context: REVIEW_MODE }) + const firstResponse = await sendLine(first.socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'request_changes', + findings: [{ severity: 'warning', body: 'first pass' }], + }) + await first.server.close() + assert.equal(firstResponse.ok, true) + + // A retried review turn legitimately produces a different verdict + findings; adoption keys on + // subject/request only, so it converges on the already-written record. + const second = await startServer(directory, client, { context: REVIEW_MODE }) + const secondResponse = await sendLine(second.socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [{ severity: 'info', body: 'second pass, different' }], + }) + await second.server.close() + + assert.equal(secondResponse.ok, true) + assert.deepEqual(secondResponse.ref, firstResponse.ref) + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.review) + assert.equal(stored.length, 1) + // The adopted record is the ORIGINAL (findings/verdict are not overwritten on adoption). + assert.equal(stored[0].value.verdict, 'request_changes') + }) +}) + +it('submitReview: adoption refuses an existing review- record with a mismatched subject', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-review-mismatch') + const client = await makeClient(pds) + + const first = await startServer(directory, client, { context: REVIEW_MODE }) + const firstResponse = await sendLine(first.socketPath, { method: 'submitReview', token: TOKEN, verdict: 'approve', findings: [] }) + await first.server.close() + assert.equal(firstResponse.ok, true) + + // A second review turn for the same request but a DIFFERENT subject would collide on the same + // deterministic rkey — it must refuse to adopt rather than serve a verdict of the wrong subject. + const otherSubject = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/impl-2', cid: 'othercid' } + const second = await startServer(directory, client, { context: { mode: { kind: 'review', subject: otherSubject } } }) + try { + const secondResponse = await sendLine(second.socketPath, { method: 'submitReview', token: TOKEN, verdict: 'approve', findings: [] }) + assert.equal(secondResponse.ok, false) + assert.match(secondResponse.error, /mismatched subject\/request/) + } finally { + await second.server.close() + } + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.review) + assert.equal(stored.length, 1) + assert.deepEqual(stored[0].value.subject, SUBJECT) + }) +}) + +it('submitReview: two concurrent submits on one review turn land exactly one record (reservation)', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-review-concurrent') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { context: REVIEW_MODE }) + try { + const [a, b] = await Promise.all([ + sendLine(socketPath, { method: 'submitReview', token: TOKEN, verdict: 'approve', findings: [] }), + sendLine(socketPath, { method: 'submitReview', token: TOKEN, verdict: 'request_changes', findings: [] }), + ]) + const oks = [a, b].filter((r) => r.ok) + assert.equal(oks.length, 1) + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.review) + assert.equal(stored.length, 1) + } finally { + await server.close() + } + }) +}) diff --git a/packages/daemon/test/turn.test.mjs b/packages/daemon/test/turn.test.mjs index 421ad79..f767894 100644 --- a/packages/daemon/test/turn.test.mjs +++ b/packages/daemon/test/turn.test.mjs @@ -10,8 +10,11 @@ import { LocalPds } from '../../atproto/test/local-pds.mjs' import { ClaudeCodeHarness, FakeContainerRunner, + REVIEW_TYPE, + classifyTurnObservation, implArtifactRkey, planArtifactRkey, + reviewRkey, runTurn, } from '../dist/index.js' @@ -465,3 +468,186 @@ it('propagates a container-runner infra error to the caller (never silently swal await assert.rejects(stat(runDir)) }) }) + +// --- Review turns --------------------------------------------------------- + +const COMMIT = 'b'.repeat(40) +const SUBJECT = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/impl-1', cid: 'subj-cid' } +const REVIEW_REQUEST_RECORD = { + $type: COLLECTIONS.artifactRequest, + goal: GOAL, + type: 'review', + subject: SUBJECT, + basedOn: [], + assignee: 'did:plc:agent', + createdAt: '2026-01-01T00:03:00Z', +} +const REVIEW_BUNDLE = { + ...BUNDLE, + request: { ...BUNDLE.request, type: 'review' }, + subject: { uri: SUBJECT.uri, cid: SUBJECT.cid, type: 'implementation', body: 'impl body', links: { commit: COMMIT }, createdAt: '2026-01-01T00:04:00Z' }, +} + +function reviewInput(runDir, overrides = {}) { + return baseInput(runDir, { + bundle: REVIEW_BUNDLE, + artifactType: REVIEW_TYPE, + requestRecord: REVIEW_REQUEST_RECORD, + ...overrides, + }) +} + +it('review fulfilled: submitReview over the socket produces a fulfilled outcome and a verdict anchored to the subject', async () => { + const { pds, actor } = await makeActor('did:plc:agent') + await withRunDir(async (runDir) => { + const runner = new FakeContainerRunner(async (spec) => { + const response = await sendLine(hostSocketPath(spec), { + method: 'submitReview', + token: spec.env.RADIAL_TURN_TOKEN, + verdict: 'request_changes', + findings: [{ severity: 'error', body: 'needs work' }], + }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }) + const result = await runTurn(reviewInput(runDir, { actor }), { + runner, + harness: new ClaudeCodeHarness(), + checkout: noopCheckout, + }) + assert.equal(result.outcome, 'fulfilled') + const expectedRkey = reviewRkey(BUNDLE.request.uri, BUNDLE.request.cid) + assert.equal(result.acceptedRef.uri, `at://${actor.did}/${COLLECTIONS.review}/${expectedRkey}`) + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.review) + assert.equal(stored.length, 1) + assert.deepEqual(stored[0].value.subject, SUBJECT) + assert.deepEqual(stored[0].value.request, { uri: BUNDLE.request.uri, cid: BUNDLE.request.cid }) + assert.equal(stored[0].value.verdict, 'request_changes') + }) +}) + +it('review awaiting_input: a review turn that asks a question is awaiting_input with no verdict', async () => { + const { pds, actor } = await makeActor('did:plc:agent-review-q') + await withRunDir(async (runDir) => { + const runner = new FakeContainerRunner(async (spec) => { + const response = await sendLine(hostSocketPath(spec), { + method: 'askQuestion', + token: spec.env.RADIAL_TURN_TOKEN, + body: 'what standard applies?', + }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }) + const result = await runTurn(reviewInput(runDir, { actor }), { + runner, + harness: new ClaudeCodeHarness(), + checkout: noopCheckout, + }) + assert.equal(result.outcome, 'awaiting_input') + assert.equal(result.acceptedRef, undefined) + assert.equal([...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.review).length, 0) + assert.equal([...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.message).length, 1) + }) +}) + +it('review crashed: a review turn producing no verdict or question is crashed', async () => { + const { actor } = await makeActor('did:plc:agent-review-crash') + await withRunDir(async (runDir) => { + const runner = new FakeContainerRunner(async () => ({ exitCode: 0, timedOut: false })) + const result = await runTurn(reviewInput(runDir, { actor }), { + runner, + harness: new ClaudeCodeHarness(), + checkout: noopCheckout, + }) + assert.equal(result.outcome, 'crashed') + }) +}) + +it('classifyTurnObservation: an observation with BOTH an artifact and a review is crashed (never a silent preference)', () => { + const both = classifyTurnObservation({ + artifact: { uri: 'at://a/x/1', cid: 'c1' }, + review: { uri: 'at://a/y/2', cid: 'c2' }, + questions: [], + }) + assert.equal(both.outcome, 'crashed') + assert.equal(both.reason, 'both_terminals') + assert.equal(both.acceptedRef, undefined) +}) + +it('review checkout is read-only and, when the subject links a commit, pinned to that commit', async () => { + const { actor } = await makeActor('did:plc:agent-review-checkout') + await withRunDir(async (runDir) => { + let pinnedCommit + const checkoutCommitStub = async ({ commit, dest }) => { + pinnedCommit = commit + await mkdir(dest, { recursive: true }) + return { path: dest, commit } + } + const runner = new FakeContainerRunner(async (spec) => { + // The subject implementation's exact commit was pinned via checkoutCommit. + assert.equal(pinnedCommit, COMMIT) + // The checkout is mounted READ-ONLY for a review turn. + assert.equal(spec.mounts.find((m) => m.target === '/work').readOnly, true) + const response = await sendLine(hostSocketPath(spec), { + method: 'submitReview', + token: spec.env.RADIAL_TURN_TOKEN, + verdict: 'approve', + findings: [], + }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }) + const result = await runTurn(reviewInput(runDir, { actor, checkoutRef: COMMIT }), { + runner, + harness: new ClaudeCodeHarness(), + checkout: noopCheckout, + checkoutCommit: checkoutCommitStub, + }) + assert.equal(result.outcome, 'fulfilled') + }) +}) + +it('a review turn receives GH_TOKEN for PR reconnaissance (same as an implementation turn)', async () => { + const { actor } = await makeActor('did:plc:agent-review-gh') + await withRunDir(async (runDir) => { + const runner = new FakeContainerRunner(async (spec) => { + assert.equal(spec.env.GH_TOKEN, 'operator-github-token') + const response = await sendLine(hostSocketPath(spec), { + method: 'submitReview', + token: spec.env.RADIAL_TURN_TOKEN, + verdict: 'approve', + findings: [], + }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }) + const result = await runTurn(reviewInput(runDir, { actor }), { + runner, + harness: new ClaudeCodeHarness(), + checkout: noopCheckout, + githubToken: 'operator-github-token', + }) + assert.equal(result.outcome, 'fulfilled') + }) +}) + +it('refuses to launch when the selected artifact type does not match the request record type', async () => { + const { actor } = await makeActor('did:plc:agent-mode-mismatch') + await withRunDir(async (runDir) => { + let ran = false + const runner = new FakeContainerRunner(async () => { + ran = true + return { exitCode: 0, timedOut: false } + }) + // artifactType is REVIEW_TYPE but the request record declares type 'plan' — a dispatcher bug. + await assert.rejects( + runTurn(baseInput(runDir, { actor, artifactType: REVIEW_TYPE, requestRecord: REQUEST_RECORD, bundle: REVIEW_BUNDLE }), { + runner, + harness: new ClaudeCodeHarness(), + checkout: noopCheckout, + }), + /turn mode mismatch/, + ) + assert.equal(ran, false) + }) +}) -- knotmirror 0.0.1 From 74231c27f933018591cb3aa8931b69f85e5e88ec Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 13:20:13 -0700 Subject: [PATCH 06/13] sidecar: map `radial review submit` to submitReview in turn mode - buildTurnRpc: add the `review submit` turn command, mapping --verdict and a JSON --findings-file to a submitReview RPC; reject --subject (the daemon owns the subject); update the allowlist message to list the three permitted turn commands. - tests: mapping, empty findings, --subject rejection, bad-verdict/missing-file. Co-Authored-By: Claude Fable 5 --- packages/sidecar/src/socket.ts | 36 +++++++++++++++++-- packages/sidecar/test/socket.test.mjs | 50 ++++++++++++++++++++++++++- 2 files changed, 83 insertions(+), 3 deletions(-) diff --git a/packages/sidecar/src/socket.ts b/packages/sidecar/src/socket.ts index cdf045e..aae63c2 100644 --- a/packages/sidecar/src/socket.ts +++ b/packages/sidecar/src/socket.ts @@ -1,5 +1,5 @@ import { createConnection } from 'node:net' -import { TURN_LIMITS, type TurnRpcRequest, type TurnRpcResponse } from '@radial/core' +import { TURN_LIMITS, type ReviewFinding, type TurnRpcRequest, type TurnRpcResponse } from '@radial/core' function allValues(args: string[], flag: string): string[] { const results: string[] = [] @@ -56,6 +56,36 @@ export async function buildTurnRpc( } } + if (group === 'review' && action === 'submit') { + // A review turn's terminal command. The daemon owns the subject and the request backref (from + // turn context), so `--subject` is rejected here — a review turn cannot redirect its verdict at + // a different artifact than the one its request named. + if (lastValue(args, '--subject') !== undefined) { + throw new Error('In turn socket mode `radial review submit` must not pass --subject; the daemon owns the review subject') + } + const verdict = lastValue(args, '--verdict') + if (verdict !== 'approve' && verdict !== 'request_changes') { + throw new Error('radial review submit requires --verdict approve|request_changes') + } + const findingsFile = lastValue(args, '--findings-file') + if (findingsFile === undefined) { + throw new Error('radial review submit requires --findings-file ') + } + const raw = await readText(findingsFile) + let findings: unknown + try { + findings = JSON.parse(raw) + } catch (error) { + throw new Error(`--findings-file is not valid JSON: ${error instanceof Error ? error.message : String(error)}`) + } + if (!Array.isArray(findings)) { + throw new Error('--findings-file must contain a JSON array of findings') + } + // The daemon performs full per-finding validation at the socket boundary (the untrusted edge); + // the sidecar only shapes the envelope. + return { method: 'submitReview', token, verdict, findings: findings as ReviewFinding[] } + } + if (group === 'message' && action === 'post') { // In socket mode a message is always the can't-complete question; the daemon anchors it to // the turn's goal/artifact, so --goal/--artifact/--re (used in direct-PDS mode) are ignored. @@ -64,7 +94,9 @@ export async function buildTurnRpc( } const command = args.slice(0, 2).filter((part) => part !== undefined).join(' ') || '(none)' - throw new Error(`In turn socket mode only "artifact submit" and "message post" are permitted, got: ${command}`) + throw new Error( + `In turn socket mode only "artifact submit", "review submit", and "message post" are permitted, got: ${command}`, + ) } function concatBytes(chunks: Uint8Array[]): Uint8Array { diff --git a/packages/sidecar/test/socket.test.mjs b/packages/sidecar/test/socket.test.mjs index 7358851..775bbc4 100644 --- a/packages/sidecar/test/socket.test.mjs +++ b/packages/sidecar/test/socket.test.mjs @@ -72,6 +72,54 @@ describe('buildTurnRpc mapping', () => { assert.deepEqual(rpc, { method: 'askQuestion', token: 'tok', body: 'q' }) }) + it('maps review submit with a findings file to submitReview', async () => { + const findings = [{ severity: 'error', path: 'src/x.ts', line: 3, body: 'bug' }] + const calls = [] + const rt = async (path) => { + calls.push(path) + return JSON.stringify(findings) + } + const rpc = await buildTurnRpc( + ['review', 'submit', '--verdict', 'request_changes', '--findings-file', '/tmp/findings.json'], + 'tok', + rt, + ) + assert.deepEqual(rpc, { method: 'submitReview', token: 'tok', verdict: 'request_changes', findings }) + assert.deepEqual(calls, ['/tmp/findings.json']) + }) + + it('accepts an empty findings array on review submit', async () => { + const rt = async () => '[]' + const rpc = await buildTurnRpc(['review', 'submit', '--verdict', 'approve', '--findings-file', '/tmp/f.json'], 'tok', rt) + assert.deepEqual(rpc, { method: 'submitReview', token: 'tok', verdict: 'approve', findings: [] }) + }) + + it('rejects review submit with --subject in turn mode (the daemon owns the subject)', async () => { + await assert.rejects( + buildTurnRpc( + ['review', 'submit', '--verdict', 'approve', '--findings-file', '/tmp/f.json', '--subject', 'at://x/y/z'], + 'tok', + async () => '[]', + ), + /must not pass --subject/, + ) + }) + + it('rejects review submit with a bad verdict, a missing findings file, or non-array findings JSON', async () => { + await assert.rejects( + buildTurnRpc(['review', 'submit', '--verdict', 'lgtm', '--findings-file', '/tmp/f.json'], 'tok', async () => '[]'), + /--verdict approve\|request_changes/, + ) + await assert.rejects( + buildTurnRpc(['review', 'submit', '--verdict', 'approve'], 'tok', readText), + /--findings-file/, + ) + await assert.rejects( + buildTurnRpc(['review', 'submit', '--verdict', 'approve', '--findings-file', '/tmp/f.json'], 'tok', async () => '{}'), + /must contain a JSON array/, + ) + }) + for (const args of [ ['auth', 'login', '--profile', 'p'], ['artifact', 'post', '--request', 'at://x/y/z'], @@ -82,7 +130,7 @@ describe('buildTurnRpc mapping', () => { it(`rejects the disallowed command: ${args.join(' ')}`, async () => { await assert.rejects( buildTurnRpc(args, 'tok', readText), - /In turn socket mode only "artifact submit" and "message post" are permitted/, + /In turn socket mode only "artifact submit", "review submit", and "message post" are permitted/, ) }) } -- knotmirror 0.0.1 From 565ff56a0a961ecffea451f3876767a0a5f3d3a6 Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 14:35:25 -0700 Subject: [PATCH 07/13] daemon: harden auto-review write/ledger boundary (review findings) Fixes five holes found in cross-model review: 1. Lost writes: a candidate is now ledger-marked (and added to alreadyWritten) only AFTER its create succeeds or a valid adoption occurs. A failed/crashed write leaves the subject unmarked, so the next pump reselects and retries it; the deterministic rkey + adoption make the retry duplicate-safe. Observable non-candidate artifacts keep being marked every tick as before. 2. Cross-actor duplicate window: before creating, probe the deterministic rkey via getOwnRecord across EVERY currently-eligible loaded actor (not just the selected writer); a matching record in any repo is adopted. Closes the lowest-DID-changed-on-restart double-write. 3. Closed/archived-goal artifacts are no longer ledger-marked (observableArtifacts excludes them), so they become candidates if the goal reopens. 4. Retracted-request wedge: autoReviewRkey is salted with the count of retracted review requests pinning the subject (0 reproduces the old rkey); a rewrite after a retraction gets a fresh rkey and lands in openRequests instead of adopting the tombstoned request. Adoption probing uses the same salted rkey. 5. Adoption shape check also verifies basedOn === [subject] and assignee equals the DID of the repo the record was found in. Adds 6 tests (one per finding, incl. round-trip materialize for #4). Co-Authored-By: Claude Fable 5 --- packages/daemon/src/auto-review.ts | 224 +++++++++++++++------ packages/daemon/test/auto-review.test.mjs | 231 ++++++++++++++++++++++ 2 files changed, 394 insertions(+), 61 deletions(-) diff --git a/packages/daemon/src/auto-review.ts b/packages/daemon/src/auto-review.ts index 38217b3..5aa28ad 100644 --- a/packages/daemon/src/auto-review.ts +++ b/packages/daemon/src/auto-review.ts @@ -11,6 +11,7 @@ import { type IndexedRecord, type MaterializedIndex, type ProjectView, + type RadialRecord, type StrongRef, } from '@radial/core' import type { ActorRegistry, LoadedActor } from './actors.js' @@ -29,13 +30,19 @@ const sameRef = (left: StrongRef | undefined, right: StrongRef | undefined): boo /** * Deterministic rkey for the auto-review request pinning an exact artifact version: `autoreview-` - * plus 24 base32 chars of sha256(subjectUri#subjectCid). Per-actor repos make this unique per - * daemon-actor, so a restart that re-derives the same rkey collides on the PDS (RecordAlreadyExists) - * instead of writing a second request — closing the restart-window double-write the in-memory - * `alreadyWritten` set alone cannot (it is lost on restart). Mirrors `mergeRkey` in merge-poll.ts. + * plus 24 base32 chars of sha256(subjectUri#subjectCid[#retractedCount]). Per-actor repos make this + * stable per daemon-actor, so a restart that re-derives the same rkey collides on the PDS + * (RecordAlreadyExists) instead of writing a second request — closing the restart-window double-write + * the in-memory `alreadyWritten` set alone cannot (it is lost on restart). Mirrors `mergeRkey`. + * + * `retractedCount` salts the key with how many prior auto-review requests for this exact subject have + * been retracted: 0 reproduces the historical rkey; after a retraction the rewrite gets a FRESH rkey + * (design fix) so it does not collide with — and adopt — the tombstoned request, which the + * materializer keeps out of `openRequests` forever. */ -export function autoReviewRkey(subjectUri: string, subjectCid: string): string { - const digest = createHash('sha256').update(`${subjectUri}#${subjectCid}`).digest() +export function autoReviewRkey(subjectUri: string, subjectCid: string, retractedCount = 0): string { + const salt = retractedCount > 0 ? `#${retractedCount}` : '' + const digest = createHash('sha256').update(`${subjectUri}#${subjectCid}${salt}`).digest() return `autoreview-${base32Encode(digest).slice(0, 24)}` } @@ -51,6 +58,20 @@ export function projectAutoReviewConfig(projectView: ProjectView): Record) : {} } +/** + * The loaded actors eligible to author a review in this space: each holds an active AGENT-kind + * membership grant (mirroring dispatch.ts's agent-kind check) and produces `review` artifacts. + * Sorted by DID, so `[0]` is the deterministic writer and the list is a stable probe order. + */ +export function eligibleReviewActors(index: MaterializedIndex, actors: ActorRegistry): LoadedActor[] { + const activeAgentDids = new Set( + index.members.filter((member) => member.active && member.kind === 'agent').map((member) => member.did), + ) + return actors.all + .filter((actor) => activeAgentDids.has(actor.did) && actor.artifactTypes.includes(REVIEW_TYPE)) + .sort((a, b) => a.did.localeCompare(b.did)) +} + /** * The review actor is deterministic: among the ELIGIBLE actors (each holds an active AGENT-kind * membership grant in the space and produces `review` artifacts) pick the lowest DID. Returns @@ -65,6 +86,9 @@ export interface AutoReviewCandidate { artifact: IndexedRecord /** The actor whose repo the review request is written into (see `selectReviewActor`). */ actor: LoadedActor + /** Count of RETRACTED trusted `review` requests already pinning this exact subject — salts the + * deterministic rkey so a rewrite after a retraction never collides with the tombstoned request. */ + retractedCount: number } /** @@ -91,13 +115,7 @@ export function selectAutoReviewCandidates( alreadyWritten: Set, onSkip?: (reason: string) => void, ): AutoReviewCandidate[] { - const activeAgentDids = new Set( - index.members.filter((member) => member.active && member.kind === 'agent').map((member) => member.did), - ) - const eligible = actors.all.filter( - (actor) => activeAgentDids.has(actor.did) && actor.artifactTypes.includes(REVIEW_TYPE), - ) - const actor = selectReviewActor(eligible) + const actor = selectReviewActor(eligibleReviewActors(index, actors)) // An artifact's `request` backref resolves against the fulfilling requests of ANY target (a // project-scoped artifact's request lives under the project; a goal artifact's under the goal). @@ -134,7 +152,15 @@ export function selectAutoReviewCandidates( onSkip?.('no loaded actor holds an active agent membership grant and produces review artifacts') continue } - candidates.push({ artifact, actor }) + // Salt the rkey with how many auto-review requests for this exact subject were retracted, so a + // rewrite after a retraction gets a fresh rkey (never collides with the tombstoned request). + const retractedCount = view.retracted.filter( + (request) => + request.value.type === REVIEW_TYPE && + request.value.subject !== undefined && + refKey(request.value.subject) === key, + ).length + candidates.push({ artifact, actor, retractedCount }) } } @@ -152,9 +178,17 @@ export function selectAutoReviewCandidates( return candidates.sort((a, b) => a.artifact.uri.localeCompare(b.artifact.uri)) } -const allArtifactVersions = (index: MaterializedIndex): Array> => [ - ...index.goals.flatMap((view) => view.artifacts), +/** + * The artifact versions the ledger is allowed to mark as observed: every project artifact plus every + * OPEN-goal artifact. Artifacts under a closed/archived goal are deliberately EXCLUDED — they stay + * unobserved so that if the goal reopens (or the artifact and its closure arrived in the same first + * sync) they become candidates then, instead of being permanently wedged out by an early mark. + */ +const observableArtifacts = (index: MaterializedIndex): Array> => [ ...index.projects.flatMap((view) => view.artifacts), + ...index.goals.flatMap((view) => + view.archived || view.target.value.closed ? [] : view.artifacts, + ), ] /** On-disk shape of a per-space observed-subjects ledger. Presence of the file means the space has @@ -187,18 +221,24 @@ export interface AutoReviewTriggerDeps { * identities, with the artifact as `subject`). Fire-and-forget: `pump` never awaits a write, so it * never blocks the ingestion loop. * - * "Landed" is defined by a persisted per-space observed-subjects ledger, NOT a timestamp: every tick, - * AFTER selection, ALL currently-indexed artifact versions are recorded and persisted. The first-ever - * snapshot of a space seeds the ledger without triggering anything (pre-existing artifacts are never + * "Landed" is defined by a persisted per-space observed-subjects ledger, NOT a timestamp. Each tick, + * AFTER selection, every OBSERVABLE non-candidate artifact version (open-goal + project artifacts) is + * recorded and persisted; a CANDIDATE is recorded only AFTER its write succeeds (or a valid adoption + * occurs), so a failed write leaves the subject unmarked and the next pump reselects and retries it + * (the deterministic rkey + adoption make that retry safe against duplicates). Closed/archived-goal + * artifacts are never marked, so they become candidates if the goal reopens. The first-ever snapshot + * of a space seeds the ledger without triggering anything (pre-existing artifacts are never * auto-reviewed); thereafter an artifact is a candidate only if it is not yet in the ledger — which - * also covers artifacts that landed during daemon downtime (never observed, so still reviewed on - * restart) and prevents a backfill storm when a project flips auto-review on. + * also covers artifacts that landed during daemon downtime (still reviewed on restart) and prevents a + * backfill storm when a project flips auto-review on. * - * Double-write defense is two-layered, exactly like `MergePoller`: the in-memory `#alreadyWritten` - * set closes the within-process window before the request is ingested, and the DETERMINISTIC rkey - * (`autoReviewRkey`) makes a re-derived write after a restart collide on the PDS; a collision is - * ADOPTED as success only when the existing record matches (same subject, type, and goal/project - * target) — a mismatch is logged once and never retried. + * Double-write defense is layered: the in-memory `#alreadyWritten` set closes the within-process + * window before the request is ingested; before creating, the DETERMINISTIC rkey is probed via + * `getOwnRecord` across EVERY eligible actor's repo (not just the selected writer, so a lowest-DID + * change on restart cannot escape a peer's existing record); and a collision on create is likewise + * adopted. A record is adopted only when it matches exactly — same subject, type `review`, + * goal/project target, `basedOn` of exactly `[subject]`, and `assignee` equal to the repo it was + * found in — otherwise it is logged once and never adopted or retried. */ export class AutoReviewTrigger { readonly #deps: AutoReviewTriggerDeps @@ -266,22 +306,31 @@ export class AutoReviewTrigger { this.#logOnce(`not auto-reviewing: ${reason}`), ) : [] + const candidateKeys = new Set(candidates.map((candidate) => refKey(candidate.artifact))) - // AFTER selection, record every currently-indexed artifact version (all goals — including - // closed/archived — and all projects) so a later un-archive or auto-review flip never backfills. - for (const artifact of allArtifactVersions(index)) ledger.subjects.add(refKey(artifact)) + // AFTER selection, record every OBSERVABLE NON-candidate artifact version (open-goal + project; + // never closed/archived). Candidates are recorded only once their write lands (see `#write`), so a + // failed or crashed write is reselected and retried next tick instead of being lost. + for (const artifact of observableArtifacts(index)) { + const key = refKey(artifact) + if (!candidateKeys.has(key)) ledger.subjects.add(key) + } ledger.seeded = true this.#persist(spaceUri, ledger) + const eligible = eligibleReviewActors(index, actors) for (const candidate of candidates) { const key = refKey(candidate.artifact) if (this.#inFlight.has(key)) continue - const promise = this.#write(candidate).finally(() => this.#inFlight.delete(key)) + const promise = this.#write(candidate, spaceUri, eligible).finally(() => this.#inFlight.delete(key)) this.#inFlight.set(key, promise) } } - #persist(spaceUri: string, ledger: ObservedLedger): void { + /** Snapshots and persists the ledger, chained per space (tmp+rename can't race a prior tick). The + * returned tail is tracked for `drain`; `#write` awaits it so a mark-on-success is durable before + * its in-flight promise settles. */ + #persist(spaceUri: string, ledger: ObservedLedger): Promise { const snapshot: LedgerFile = { space: spaceUri, subjects: [...ledger.subjects].sort() } const tail = (this.#persists.get(spaceUri) ?? Promise.resolve()) .then(() => this.#writeLedgerFile(ledger.path, snapshot)) @@ -291,6 +340,17 @@ export class AutoReviewTrigger { ), ) this.#persists.set(spaceUri, tail) + return tail + } + + /** Marks a subject observed (ledger + in-process guard) after its write landed, and awaits the + * ledger persist so the durability the deterministic-rkey retry relies on is in place. */ + async #mark(spaceUri: string, key: string): Promise { + this.#alreadyWritten.add(key) + const ledger = this.#ledgers.get(spaceUri) + if (!ledger) return + ledger.subjects.add(key) + await this.#persist(spaceUri, ledger) } async #writeLedgerFile(path: string, snapshot: LedgerFile): Promise { @@ -300,10 +360,62 @@ export class AutoReviewTrigger { await rename(tmp, path) // atomic replace so a crash mid-write never leaves a torn ledger. } - async #write(candidate: AutoReviewCandidate): Promise { - const { artifact, actor } = candidate + /** Whether an already-existing record found in `repoDid`'s repo is the auto-review request we would + * have written for this subject: same type, subject, goal/project target, `basedOn` of exactly + * `[subject]`, and self-assignment to `repoDid`. Anything else is a foreign record at the rkey. */ + #adoptable( + value: ArtifactRequestRecord, + subject: StrongRef, + artifact: IndexedRecord, + repoDid: string, + ): boolean { + const targetMatches = artifact.value.goal + ? sameRef(value.goal, artifact.value.goal) + : sameRef(value.project, artifact.value.project) + const basedOnMatches = + Array.isArray(value.basedOn) && value.basedOn.length === 1 && sameRef(value.basedOn[0], subject) + return ( + value.type === REVIEW_TYPE && + sameRef(value.subject, subject) && + targetMatches && + basedOnMatches && + value.assignee === repoDid + ) + } + + async #write(candidate: AutoReviewCandidate, spaceUri: string, eligible: LoadedActor[]): Promise { + const { artifact, actor, retractedCount } = candidate const subject: StrongRef = { uri: artifact.uri, cid: artifact.cid } const key = refKey(artifact) + const rkey = autoReviewRkey(subject.uri, subject.cid, retractedCount) + + // Probe the deterministic rkey across EVERY eligible actor's repo before creating, so a restart + // that changed the lowest-DID writer still adopts a peer's earlier request instead of writing a + // second one that would never collide with it. + for (const probe of eligible) { + let existing: { uri: string; cid: string; value: RadialRecord } | undefined + try { + existing = await probe.client.getOwnRecord(COLLECTIONS.artifactRequest, rkey) + } catch (error) { + // A probe failure means we cannot rule out an existing request; do not risk a duplicate — + // leave the subject unmarked and let the next pump retry. + this.#deps.log?.( + `auto-review: probe of ${probe.did} for ${subject.uri} failed: ${error instanceof Error ? error.message : String(error)}; retrying next tick`, + ) + return + } + if (!existing) continue + if (this.#adoptable(existing.value as ArtifactRequestRecord, subject, artifact, probe.did)) { + await this.#mark(spaceUri, key) + this.#deps.log?.(`auto-review: adopted existing review request of ${subject.uri} in ${probe.did}: ${existing.uri}`) + return + } + this.#logOnce( + `auto-review: refusing to adopt mismatched record at ${rkey} in ${probe.did} for subject ${subject.uri}`, + ) + return + } + // The review request's goal/project target is copied EXACTLY from the subject artifact's own ref // — the materializer silently drops a review request whose target does not match its subject's // (materializer.ts:487-502). @@ -316,40 +428,30 @@ export class AutoReviewTrigger { assignee: actor.did, createdAt: this.#now(), } - const rkey = autoReviewRkey(subject.uri, subject.cid) + let ref: StrongRef try { - let ref: StrongRef - try { - ref = await actor.client.create(COLLECTIONS.artifactRequest, record, { rkey }) - } catch (error) { - if (error instanceof XrpcError && error.status === 400 && error.error === 'RecordAlreadyExists') { - const existing = await actor.client.getOwnRecord(COLLECTIONS.artifactRequest, rkey) - if (!existing) throw error - const value = existing.value as ArtifactRequestRecord - const targetMatches = artifact.value.goal - ? sameRef(value.goal, artifact.value.goal) - : sameRef(value.project, artifact.value.project) - if (value.type !== REVIEW_TYPE || !sameRef(value.subject, subject) || !targetMatches) { - // A DIFFERENT record already occupies this deterministic rkey (should be impossible — the - // rkey is a pure function of the subject). Do NOT adopt, do NOT mark written, do NOT - // retry-loop; log once per subject. - this.#logOnce( - `auto-review: refusing to adopt mismatched record at ${rkey} for subject ${subject.uri}`, - ) - return - } - ref = { uri: existing.uri, cid: existing.cid } - } else { - throw error + ref = await actor.client.create(COLLECTIONS.artifactRequest, record, { rkey }) + } catch (error) { + if (error instanceof XrpcError && error.status === 400 && error.error === 'RecordAlreadyExists') { + // Raced with a write between the probe and this create: re-fetch from the selected actor. + const existing = await actor.client.getOwnRecord(COLLECTIONS.artifactRequest, rkey).catch(() => undefined) + if (existing && this.#adoptable(existing.value as ArtifactRequestRecord, subject, artifact, actor.did)) { + await this.#mark(spaceUri, key) + return } + this.#logOnce( + `auto-review: refusing to adopt mismatched record at ${rkey} in ${actor.did} for subject ${subject.uri}`, + ) + return } - this.#alreadyWritten.add(key) - this.#deps.log?.(`auto-review: requested review of ${subject.uri} as ${actor.did}: ${ref.uri}`) - } catch (error) { + // A transient failure: leave the subject UNMARKED so the next pump reselects and retries it. this.#deps.log?.( - `auto-review: failed to write review request for ${subject.uri}: ${error instanceof Error ? error.message : String(error)}`, + `auto-review: failed to write review request for ${subject.uri}: ${error instanceof Error ? error.message : String(error)}; retrying next tick`, ) + return } + await this.#mark(spaceUri, key) + this.#deps.log?.(`auto-review: requested review of ${subject.uri} as ${actor.did}: ${ref.uri}`) } /** Awaits every in-flight write and ledger persist (best-effort graceful shutdown). */ diff --git a/packages/daemon/test/auto-review.test.mjs b/packages/daemon/test/auto-review.test.mjs index f57eca3..401df32 100644 --- a/packages/daemon/test/auto-review.test.mjs +++ b/packages/daemon/test/auto-review.test.mjs @@ -160,6 +160,30 @@ function fakeActor(did, artifactTypes, creates) { creates.push({ did, collection, value, rkey: options?.rkey }) return { uri: `at://${did}/${collection}/${options?.rkey ?? `rk-${creates.length}`}`, cid: `cid-${creates.length}` } }, + // The write path probes every eligible actor's repo before creating; a bare fake owns nothing. + async getOwnRecord() { + return undefined + }, + }, + } +} + +/** An actor whose create throws (transient failure), counting attempts so a test can assert a + * failed write is reselected and retried on the next pump. */ +function throwingActor(did, artifactTypes, counter) { + return { + did, + profile: did, + artifactTypes, + session: { did }, + client: { + async create() { + counter.attempts += 1 + throw new Error('PDS unreachable') + }, + async getOwnRecord() { + return undefined + }, }, } } @@ -657,3 +681,210 @@ describe('written request round-trips through core.materialize', () => { }) } }) + +// --- Write/ledger boundary (cross-model review findings 1-5). --- + +describe('AutoReviewTrigger.pump — write/ledger boundary', () => { + // Finding 1: a candidate is marked only AFTER its write lands; a failed write leaves it unmarked so + // the next pump reselects and retries it. + it('retries a failed write on the next pump (candidate never marked on failure)', async () => { + const counter = { attempts: 0 } + const actors = registry([throwingActor(AGENT_A, ['plan', 'review'], counter)]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) + t.pump(empty, actors); await t.drain() // seed + t.pump(withArt, actors); await t.drain() // write #1 throws → unmarked + t.pump(withArt, actors); await t.drain() // reselected → write #2 throws + assert.equal(counter.attempts, 2, 'the failed subject was reselected and retried, not lost') + }) + + // Finding 1: a "crash" after create-success but before the ledger persisted (fresh ledger dir, same + // PDS) → the restarted trigger reselects, probes the deterministic rkey, adopts, and never dups. + it('adopts after a crash between create-success and ledger persist', async () => { + const creates = [] + const store = new Map() + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t1 = trigger(stateDir()) + t1.pump(empty, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t1.drain() + t1.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t1.drain() + assert.equal(creates.length, 1) + + // Restart with a DIFFERENT (empty) ledger dir but the SAME PDS: reselects, probes, adopts. + const t2 = trigger(stateDir()) + t2.pump(empty, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t2.drain() + t2.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t2.drain() + // A further pump must NOT re-attempt — adoption marked the subject. + t2.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t2.drain() + assert.equal(creates.length, 1, 'adopted, no duplicate write') + assert.equal(store.size, 1) + }) + + // Finding 2: the rkey is unique only within one actor's repo; probe EVERY eligible actor before + // creating. A record in actor A's repo is adopted even when B is now the selected (lowest-DID) writer. + it("adopts a peer actor's existing request (cross-actor probe) instead of writing a second", async () => { + const creates = [] + const logs = [] + const repoA = new Map() + const repoB = new Map() + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true }, members: [AGENT_A, AGENT_B] }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true }, members: [AGENT_A, AGENT_B] }) + + // AGENT_B's repo already holds the matching auto-review request (assignee = AGENT_B), even though + // AGENT_A is the lowest-DID selected writer. + const rkey = autoReviewRkey(art.uri, art.cid) + repoB.set(`${COLLECTIONS.artifactRequest}/${rkey}`, { + uri: `at://${AGENT_B}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: 'cid-b', + value: { + $type: COLLECTIONS.artifactRequest, + type: 'review', + subject: { uri: art.uri, cid: art.cid }, + basedOn: [{ uri: art.uri, cid: art.cid }], + goal: base._goalRef, + assignee: AGENT_B, + createdAt: 'x', + }, + }) + + const actorsFor = () => + registry([pdsActor(AGENT_A, ['plan', 'review'], repoA, creates), pdsActor(AGENT_B, ['plan', 'review'], repoB, creates)]) + const t = trigger(stateDir(), undefined, (m) => logs.push(m)) + t.pump(empty, actorsFor()); await t.drain() // seed + t.pump(withArt, actorsFor()); await t.drain() + assert.equal(creates.length, 0, "no second request written; AGENT_A adopted AGENT_B's record") + assert.equal(repoA.size, 0) + assert.equal(logs.filter((m) => new RegExp(`adopted.*${AGENT_B}`).test(m)).length, 1) + }) + + // Finding 3: closed/archived-goal artifacts are neither selected NOR ledger-marked, so they become + // candidates if the goal reopens. + it('does not mark closed-goal artifacts, and selects them once the goal reopens', async () => { + const creates = [] + const actors = reviewActors(creates) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const closedIdx = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true }, closed: true }) + const openIdx = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) + t.pump(empty, actors); await t.drain() // seed + t.pump(closedIdx, actors); await t.drain() // closed → not selected, NOT marked + assert.equal(creates.length, 0) + t.pump(openIdx, actors); await t.drain() // reopened → the still-unobserved artifact is a candidate + assert.equal(creates.length, 1) + assert.deepEqual(creates[0].value.subject, { uri: art.uri, cid: art.cid }) + }) + + // Finding 4: after a retraction, the rewrite gets a FRESH (salted) rkey and lands in openRequests + // rather than colliding with — and adopting — the tombstoned request. + it('salts the rkey after a retraction; the rewrite round-trips into openRequests', async () => { + const creates = [] + const actors = reviewActors(creates) + const { records, space, art } = buildStore({ scope: 'goal' }) + const goalRef = strongref(records[5]) + + // A prior auto-review request (rkey salt 0) plus a trusted retract tombstone for it. + const subject = { uri: art.uri, cid: art.cid } + const oldRkey = autoReviewRkey(art.uri, art.cid, 0) + const oldAuto = stored( + AGENT_A, + oldRkey, + { $type: COLLECTIONS.artifactRequest, type: 'review', subject, basedOn: [subject], goal: goalRef, assignee: AGENT_A, createdAt: '2026-01-01T00:05:00Z' }, + 9, + ) + const retract = stored( + AGENT_A, + 'retract', + { $type: COLLECTIONS.retractRequest, request: strongref(oldAuto), createdAt: '2026-01-01T00:06:00Z' }, + 10, + ) + + // A fake index for the pump showing the old request as retracted (retractedCount = 1). + const oldReqView = { did: AGENT_A, uri: oldAuto.uri, cid: oldAuto.cid, value: { ...oldAuto.value } } + const artView = { did: AGENT_A, uri: art.uri, cid: art.cid, value: { ...art.value } } + const reqView = { + did: HUMAN, + uri: art.value.request.uri, + cid: art.value.request.cid, + value: { $type: COLLECTIONS.artifactRequest, type: 'plan', basedOn: [], autoReview: true, createdAt: 'x' }, + } + const emptyTarget = { requests: [], openRequests: [], retracted: [], reviews: [], artifacts: [] } + const buildIndex = (withArtifact) => ({ + space: { uri: space.uri, cid: 'cid-space', value: { name: 'S' } }, + members: [{ did: AGENT_A, active: true, kind: 'agent', role: 'agent' }], + goals: [ + { + target: { uri: goalRef.uri, cid: goalRef.cid, value: { project: strongref(records[4]), closed: false } }, + archived: false, + ...(withArtifact + ? { ...emptyTarget, artifacts: [artView], requests: [reqView, oldReqView], retracted: [oldReqView] } + : emptyTarget), + }, + ], + projects: [{ target: { uri: strongref(records[4]).uri, cid: strongref(records[4]).cid, value: { autoReview: {} } }, currentSystemArtifacts: [], ...emptyTarget }], + }) + + const t = trigger(stateDir()) + t.pump(buildIndex(false), actors); await t.drain() // seed + t.pump(buildIndex(true), actors); await t.drain() + assert.equal(creates.length, 1) + const written = creates[0] + assert.equal(written.rkey, autoReviewRkey(art.uri, art.cid, 1)) + assert.notEqual(written.rkey, oldRkey, 'the rewrite gets a fresh salted rkey') + + // Round-trip: old request + tombstone + new request through the real materializer. + const store = new MemoryRecordStore() + for (const r of records) store.put(r) + store.put(oldAuto) + store.put(retract) + store.put(stored(AGENT_A, written.rkey, written.value, 100, `cid-${written.rkey}`)) + const view = materialize(store, { spaceUri: space.uri }).goals[0] + const openReviews = view.openRequests.filter((r) => r.value.type === 'review') + assert.equal(openReviews.length, 1, 'exactly the fresh request is open') + assert.equal(openReviews[0].uri, `at://${AGENT_A}/${COLLECTIONS.artifactRequest}/${written.rkey}`) + assert.equal(view.retracted.some((r) => r.uri === oldAuto.uri), true, 'the old request stays retracted') + }) + + // Finding 5: a record at the rkey is adopted only when subject, type, target, basedOn === [subject], + // AND assignee === the repo it was found in all match. A basedOn/assignee mismatch is refused. + it('refuses to adopt when basedOn or assignee mismatches', async () => { + const creates = [] + const logs = [] + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + // Correct subject/type/target, but basedOn is empty and assignee is not the repo owner. + const store = new Map() + const rkey = autoReviewRkey(art.uri, art.cid) + store.set(`${COLLECTIONS.artifactRequest}/${rkey}`, { + uri: `at://${AGENT_A}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: 'cid-pre', + value: { $type: COLLECTIONS.artifactRequest, type: 'review', subject: { uri: art.uri, cid: art.cid }, basedOn: [], goal: base._goalRef, assignee: HUMAN, createdAt: 'x' }, + }) + + const t = trigger(stateDir(), undefined, (m) => logs.push(m)) + t.pump(empty, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t.drain() + t.pump(withArt, registry([pdsActor(AGENT_A, ['plan', 'review'], store, creates)])); await t.drain() + assert.equal(creates.length, 0, 'never adopted, never re-created') + assert.equal(store.size, 1) + assert.equal(logs.filter((m) => /refusing to adopt mismatched/.test(m)).length, 1) + }) +}) -- knotmirror 0.0.1 From 33387f48d16dc4368a6dd6bf3cdb76fa655e9cc9 Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 14:48:17 -0700 Subject: [PATCH 08/13] daemon: auto-review re-review findings (semantics + 3 fixes) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Retraction semantics (ruling): the trigger fires at most once per subject version, decided at landing time; a post-landing retraction is a stop signal, not a re-trigger (the ledger/alreadyWritten short-circuit precedes the retracted-request check). Documented the contract on selection + the class; the salted rkey remains for the created-and-retracted-before-first-observation case. Test: create → ingest → retract on the same ledger → no resurrection. 2. No-reviewer subjects are deferred, not swallowed: selection reports them via a new onDefer callback and pump excludes deferred keys (and in-flight-write keys, by ANY overlapping pump) from bulk-marking, so they stay unobserved until a reviewer exists / a failed write retries. Tests: no-reviewer→added-later fires; overlapping pump doesn't mark an in-flight candidate whose write then fails. 3. Probe across ALL loaded review-capable actors (new loadedReviewActors), independent of current index eligibility, so a writer that lost its grant but is still loaded is probed. Accepted+documented residual: prior writer removed from config entirely between crash and restart → at most one redundant request (bounded, same as merge-poll). Test: index-ineligible-but-loaded A → adopted. 4. Probe loop continues past a mismatched record and only refuses when no valid match exists in any repo. Test: repo1 mismatched, repo2 valid → adopt repo2. Co-Authored-By: Claude Fable 5 --- packages/daemon/src/auto-review.ts | 115 +++++++++++---- packages/daemon/test/auto-review.test.mjs | 165 ++++++++++++++++++++++ 2 files changed, 250 insertions(+), 30 deletions(-) diff --git a/packages/daemon/src/auto-review.ts b/packages/daemon/src/auto-review.ts index 5aa28ad..07f8196 100644 --- a/packages/daemon/src/auto-review.ts +++ b/packages/daemon/src/auto-review.ts @@ -72,6 +72,19 @@ export function eligibleReviewActors(index: MaterializedIndex, actors: ActorRegi .sort((a, b) => a.did.localeCompare(b.did)) } +/** + * ALL loaded actors that produce `review` artifacts, regardless of their CURRENT index eligibility — + * the set of repos probed for an already-written request before creating a new one. It is + * deliberately broader than `eligibleReviewActors`: an actor that wrote the request and then lost its + * membership grant (but is still loaded) must still be probed, or its record is missed and a + * duplicate is written. Sorted by DID for a stable probe order. + */ +export function loadedReviewActors(actors: ActorRegistry): LoadedActor[] { + return actors.all + .filter((actor) => actor.artifactTypes.includes(REVIEW_TYPE)) + .sort((a, b) => a.did.localeCompare(b.did)) +} + /** * The review actor is deterministic: among the ELIGIBLE actors (each holds an active AGENT-kind * membership grant in the space and produces `review` artifacts) pick the lowest DID. Returns @@ -105,8 +118,20 @@ export interface AutoReviewCandidate { * path, which has no request); * - it is not in the in-process `alreadyWritten` set; and * - it is not in the observed-subjects `ledger` (i.e. it appeared since the last tick). - * When an artifact would be a candidate but no eligible review actor exists, `onSkip` is invoked - * (deduped to once per space by the caller). Ordered deterministically by subject uri. + * + * RETRACTION SEMANTICS (contract). The trigger fires AT MOST ONCE per subject version, decided at + * landing time. The `ledger`/`alreadyWritten` short-circuit above is checked BEFORE the retracted + * request is even inspected, so a human retracting the auto-written request after the subject has + * been observed does NOT re-fire the trigger — a retraction is a deliberate stop signal, and the + * remedy for wanting a review after all is the UI's Review button. The retracted-request handling and + * salted rkey below cover only the genuinely-once case: a request created AND retracted before the + * subject's first observation (so its subject was never in the ledger), where the rewrite must land + * at a fresh rkey rather than adopt the tombstone. + * + * When an artifact would be a candidate but NO eligible review actor exists, `onSkip` is invoked + * (deduped to once per space by the caller) AND `onDefer` records the subject key so the caller can + * keep it UNOBSERVED (not ledger-marked) — otherwise it would be lost the moment a reviewer is + * configured later. Ordered deterministically by subject uri. */ export function selectAutoReviewCandidates( index: MaterializedIndex, @@ -114,6 +139,7 @@ export function selectAutoReviewCandidates( ledger: Set, alreadyWritten: Set, onSkip?: (reason: string) => void, + onDefer?: (subjectKey: string) => void, ): AutoReviewCandidate[] { const actor = selectReviewActor(eligibleReviewActors(index, actors)) @@ -150,6 +176,8 @@ export function selectAutoReviewCandidates( if (view.reviews.some((review) => refKey(review.value.subject) === key)) continue if (!actor) { onSkip?.('no loaded actor holds an active agent membership grant and produces review artifacts') + // Defer, don't drop: keep this subject unobserved so it fires once a reviewer is available. + onDefer?.(key) continue } // Salt the rkey with how many auto-review requests for this exact subject were retracted, so a @@ -222,23 +250,30 @@ export interface AutoReviewTriggerDeps { * never blocks the ingestion loop. * * "Landed" is defined by a persisted per-space observed-subjects ledger, NOT a timestamp. Each tick, - * AFTER selection, every OBSERVABLE non-candidate artifact version (open-goal + project artifacts) is - * recorded and persisted; a CANDIDATE is recorded only AFTER its write succeeds (or a valid adoption - * occurs), so a failed write leaves the subject unmarked and the next pump reselects and retries it - * (the deterministic rkey + adoption make that retry safe against duplicates). Closed/archived-goal - * artifacts are never marked, so they become candidates if the goal reopens. The first-ever snapshot - * of a space seeds the ledger without triggering anything (pre-existing artifacts are never - * auto-reviewed); thereafter an artifact is a candidate only if it is not yet in the ledger — which - * also covers artifacts that landed during daemon downtime (still reviewed on restart) and prevents a - * backfill storm when a project flips auto-review on. + * AFTER selection, every OBSERVABLE artifact version is recorded and persisted EXCEPT the ones the + * ledger must not swallow: current candidates (recorded only once their write lands), subjects with a + * write still in flight from an overlapping pump, and subjects deferred for want of an eligible + * reviewer. A failed write therefore leaves its subject unmarked and the next pump reselects and + * retries it (the deterministic rkey + adoption make that retry safe against duplicates). + * Closed/archived-goal artifacts are never marked, so they become candidates if the goal reopens. The + * first-ever snapshot of a space seeds the ledger without triggering anything (pre-existing artifacts + * are never auto-reviewed); thereafter an artifact is a candidate only if it is not yet in the ledger + * — which also covers artifacts that landed during daemon downtime (still reviewed on restart) and + * prevents a backfill storm when a project flips auto-review on. The trigger fires AT MOST ONCE per + * subject version, decided at landing time; a post-landing retraction is a stop signal, not a + * re-trigger (see `selectAutoReviewCandidates`). * * Double-write defense is layered: the in-memory `#alreadyWritten` set closes the within-process * window before the request is ingested; before creating, the DETERMINISTIC rkey is probed via - * `getOwnRecord` across EVERY eligible actor's repo (not just the selected writer, so a lowest-DID - * change on restart cannot escape a peer's existing record); and a collision on create is likewise - * adopted. A record is adopted only when it matches exactly — same subject, type `review`, - * goal/project target, `basedOn` of exactly `[subject]`, and `assignee` equal to the repo it was - * found in — otherwise it is logged once and never adopted or retried. + * `getOwnRecord` across every LOADED review-capable actor's repo (`loadedReviewActors` — broader than + * current index eligibility, so an actor that wrote the request and then lost its grant is still + * probed); and a collision on create is likewise adopted. A record is adopted only when it matches + * exactly — same subject, type `review`, goal/project target, `basedOn` of exactly `[subject]`, and + * `assignee` equal to the repo it was found in; a mismatched record in one repo does not stop the + * probe (a valid match in another repo is still adopted). ACCEPTED residual corner: if the prior + * writer is removed from the daemon config ENTIRELY between crash and restart, it is no longer loaded + * and cannot be probed, so at most one duplicate review request may be written — the same bounded, + * attributable corner `MergePoller` accepts, and harmless (a redundant review request). */ export class AutoReviewTrigger { readonly #deps: AutoReviewTriggerDeps @@ -301,28 +336,39 @@ export class AutoReviewTrigger { // Select against the ledger as it stood at the START of this tick. A first-ever snapshot // (unseeded) triggers nothing: pre-existing artifacts are seeded below and never reviewed. + const deferred = new Set() const candidates = ledger.seeded - ? selectAutoReviewCandidates(index, actors, ledger.subjects, this.#alreadyWritten, (reason) => - this.#logOnce(`not auto-reviewing: ${reason}`), + ? selectAutoReviewCandidates( + index, + actors, + ledger.subjects, + this.#alreadyWritten, + (reason) => this.#logOnce(`not auto-reviewing: ${reason}`), + (key) => deferred.add(key), ) : [] const candidateKeys = new Set(candidates.map((candidate) => refKey(candidate.artifact))) - // AFTER selection, record every OBSERVABLE NON-candidate artifact version (open-goal + project; - // never closed/archived). Candidates are recorded only once their write lands (see `#write`), so a - // failed or crashed write is reselected and retried next tick instead of being lost. + // AFTER selection, record every OBSERVABLE artifact version (open-goal + project; never + // closed/archived) EXCEPT the ones the ledger must not swallow: this tick's candidates (marked + // only once their write lands — see `#write`), subjects deferred for want of a reviewer (must fire + // once one is configured), and subjects with a write still in flight from an overlapping pump (so + // a failed write always retries). This keeps a failed/crashed/deferred subject reselectable. for (const artifact of observableArtifacts(index)) { const key = refKey(artifact) - if (!candidateKeys.has(key)) ledger.subjects.add(key) + if (candidateKeys.has(key) || deferred.has(key) || this.#inFlight.has(key)) continue + ledger.subjects.add(key) } ledger.seeded = true this.#persist(spaceUri, ledger) - const eligible = eligibleReviewActors(index, actors) + // Probe across ALL loaded review-capable actors (not just those currently index-eligible), so an + // actor that wrote the request and then lost its grant is still probed before we re-create. + const probeActors = loadedReviewActors(actors) for (const candidate of candidates) { const key = refKey(candidate.artifact) if (this.#inFlight.has(key)) continue - const promise = this.#write(candidate, spaceUri, eligible).finally(() => this.#inFlight.delete(key)) + const promise = this.#write(candidate, spaceUri, probeActors).finally(() => this.#inFlight.delete(key)) this.#inFlight.set(key, promise) } } @@ -383,16 +429,19 @@ export class AutoReviewTrigger { ) } - async #write(candidate: AutoReviewCandidate, spaceUri: string, eligible: LoadedActor[]): Promise { + async #write(candidate: AutoReviewCandidate, spaceUri: string, probeActors: LoadedActor[]): Promise { const { artifact, actor, retractedCount } = candidate const subject: StrongRef = { uri: artifact.uri, cid: artifact.cid } const key = refKey(artifact) const rkey = autoReviewRkey(subject.uri, subject.cid, retractedCount) - // Probe the deterministic rkey across EVERY eligible actor's repo before creating, so a restart - // that changed the lowest-DID writer still adopts a peer's earlier request instead of writing a - // second one that would never collide with it. - for (const probe of eligible) { + // Probe the deterministic rkey across EVERY loaded review-capable actor's repo before creating, so + // a restart that changed the lowest-DID writer (or an actor that lost its grant) still surfaces a + // peer's earlier request instead of writing a second one that would never collide with it. A + // mismatched record in one repo does NOT stop the probe — keep scanning; a valid match anywhere + // wins. Only if none of the repos holds a valid match do we fall through to a create. + let sawMismatch = false + for (const probe of probeActors) { let existing: { uri: string; cid: string; value: RadialRecord } | undefined try { existing = await probe.client.getOwnRecord(COLLECTIONS.artifactRequest, rkey) @@ -410,8 +459,14 @@ export class AutoReviewTrigger { this.#deps.log?.(`auto-review: adopted existing review request of ${subject.uri} in ${probe.did}: ${existing.uri}`) return } + sawMismatch = true // foreign record at this rkey here; keep probing the remaining repos. + } + if (sawMismatch) { + // No repo held a valid match, but at least one held a foreign record at the deterministic rkey + // (should be impossible — the rkey is a pure function of subject + retraction count). Do NOT + // create (a peer's foreign record is unexpected), do NOT mark; log once per subject. this.#logOnce( - `auto-review: refusing to adopt mismatched record at ${rkey} in ${probe.did} for subject ${subject.uri}`, + `auto-review: refusing to adopt mismatched record at ${rkey} for subject ${subject.uri}`, ) return } diff --git a/packages/daemon/test/auto-review.test.mjs b/packages/daemon/test/auto-review.test.mjs index 401df32..1975d68 100644 --- a/packages/daemon/test/auto-review.test.mjs +++ b/packages/daemon/test/auto-review.test.mjs @@ -188,6 +188,33 @@ function throwingActor(did, artifactTypes, counter) { } } +function deferred() { + let resolve + const promise = new Promise((r) => { resolve = r }) + return { promise, resolve } +} + +/** A throwing actor whose create BLOCKS on `gate.promise` before failing — lets a test hold a write + * in flight across an overlapping pump, then release it to fail. Counts attempts. */ +function gatedThrowingActor(did, artifactTypes, counter, gate) { + return { + did, + profile: did, + artifactTypes, + session: { did }, + client: { + async create() { + counter.attempts += 1 + await gate.promise + throw new Error('PDS unreachable') + }, + async getOwnRecord() { + return undefined + }, + }, + } +} + /** An actor over a shared in-memory PDS `store` enforcing rkey uniqueness — so a deterministic-rkey * collision throws RecordAlreadyExists and getOwnRecord can adopt (or reject) it. */ function pdsActor(did, artifactTypes, store, creates) { @@ -888,3 +915,141 @@ describe('AutoReviewTrigger.pump — write/ledger boundary', () => { assert.equal(logs.filter((m) => /refusing to adopt mismatched/.test(m)).length, 1) }) }) + +// --- Re-review verdict findings (semantics ruling + three fixes). --- + +describe('AutoReviewTrigger.pump — re-review findings', () => { + // Finding 1 (semantics ruling): the trigger fires at most once per subject version, decided at + // landing time. A post-landing retraction is a stop signal, NOT a re-trigger. + it('does not re-fire after a post-landing retraction (once per subject version)', async () => { + const creates = [] + const actors = reviewActors(creates) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const rr = reviewRequest(AGENT_A, autoReviewRkey(art.uri, art.cid), art, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + const ingested = makeIndex({ artifacts: [art], requests: [req, rr], projectAutoReview: { plan: true } }) + const retracted = makeIndex({ artifacts: [art], requests: [req, rr], retracted: [rr], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) // SAME trigger + persisted ledger throughout + t.pump(empty, actors); await t.drain() // seed + t.pump(withArt, actors); await t.drain() // fires once, marks + assert.equal(creates.length, 1) + t.pump(ingested, actors); await t.drain() // request ingested → still skipped (already observed) + t.pump(retracted, actors); await t.drain() // retraction is a stop signal → no resurrection + assert.equal(creates.length, 1) + }) + + // Finding 2: a subject that passes every gate but has no eligible reviewer is DEFERRED (left + // unobserved), not swallowed by the bulk mark — so it fires once a reviewer is configured. + it('defers a no-reviewer subject (unmarked) and fires once a reviewer is added', async () => { + const creates = [] + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) + const noReviewer = registry([fakeActor(AGENT_A, ['plan'], creates)]) // AGENT_A produces no reviews + t.pump(empty, noReviewer); await t.drain() // seed + t.pump(withArt, noReviewer); await t.drain() // deferred, NOT marked + assert.equal(creates.length, 0) + // A reviewer becomes available; the still-unobserved subject fires. + const withReviewer = registry([fakeActor(AGENT_A, ['plan', 'review'], creates)]) + t.pump(withArt, withReviewer); await t.drain() + assert.equal(creates.length, 1) + assert.deepEqual(creates[0].value.subject, { uri: art.uri, cid: art.cid }) + }) + + // Finding 2 (overlap race): an overlapping pump must not bulk-mark a subject whose write is still in + // flight — otherwise a subsequently-failed write is lost. Here the second pump sees the subject as + // deduped (so it is NOT a candidate there) yet must still leave it unobserved. + it('an overlapping pump does not mark an in-flight candidate whose write then fails', async () => { + const creates = [] + const counter = { attempts: 0 } + const gate = deferred() + const actors = registry([gatedThrowingActor(AGENT_A, ['plan', 'review'], counter, gate)]) + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const rr = reviewRequest(AGENT_A, autoReviewRkey(art.uri, art.cid), art, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true } }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true } }) + const ingested = makeIndex({ artifacts: [art], requests: [req, rr], projectAutoReview: { plan: true } }) + + const t = trigger(stateDir()) + t.pump(empty, actors); await t.drain() // seed + t.pump(withArt, actors) // pump #1: fires the write, which blocks on the gate (in flight) + t.pump(ingested, actors) // pump #2 (overlapping): subject looks deduped → not a candidate here + gate.resolve() // release → pump #1's write throws + await t.drain() + // pump #2 must NOT have marked the in-flight subject; so it is reselected and retried now. + t.pump(withArt, actors); await t.drain() + assert.equal(counter.attempts, 2, 'the in-flight-then-failed write was retried, not lost') + assert.equal(creates.length, 0) + }) + + // Finding 3: probe across ALL loaded review-capable actors, regardless of current index eligibility. + // A record written by an actor that has since lost its grant (but is still loaded) is adopted. + it('adopts from a still-loaded but index-ineligible prior writer', async () => { + const creates = [] + const logs = [] + const repoA = new Map() + const repoB = new Map() + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + // Only AGENT_B is an active member now → B is the eligible writer; AGENT_A is loaded but ineligible. + const empty = makeIndex({ projectAutoReview: { plan: true }, members: [AGENT_B] }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true }, members: [AGENT_B] }) + const rkey = autoReviewRkey(art.uri, art.cid) + repoA.set(`${COLLECTIONS.artifactRequest}/${rkey}`, { + uri: `at://${AGENT_A}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: 'cid-a', + value: { $type: COLLECTIONS.artifactRequest, type: 'review', subject: { uri: art.uri, cid: art.cid }, basedOn: [{ uri: art.uri, cid: art.cid }], goal: base._goalRef, assignee: AGENT_A, createdAt: 'x' }, + }) + const actorsFor = () => + registry([pdsActor(AGENT_A, ['plan', 'review'], repoA, creates), pdsActor(AGENT_B, ['plan', 'review'], repoB, creates)]) + const t = trigger(stateDir(), undefined, (m) => logs.push(m)) + t.pump(empty, actorsFor()); await t.drain() // seed + t.pump(withArt, actorsFor()); await t.drain() + assert.equal(creates.length, 0, 'adopted A\'s record; B wrote nothing') + assert.equal(repoB.size, 0) + assert.equal(logs.filter((m) => new RegExp(`adopted.*${AGENT_A}`).test(m)).length, 1) + }) + + // Finding 4: a mismatched record in one repo must not stop the probe — a valid match elsewhere wins. + it('continues past a mismatched repo and adopts a valid match in another', async () => { + const creates = [] + const logs = [] + const repoA = new Map() // AGENT_A (selected writer): a foreign record at the rkey + const repoB = new Map() // AGENT_B: the valid match + const base = makeIndex({}) + const req = request(HUMAN, 'req', { goal: base._goalRef }) + const art = artifact(AGENT_A, 'plan-1', req, { goal: base._goalRef }) + const empty = makeIndex({ projectAutoReview: { plan: true }, members: [AGENT_A, AGENT_B] }) + const withArt = makeIndex({ artifacts: [art], requests: [req], projectAutoReview: { plan: true }, members: [AGENT_A, AGENT_B] }) + const rkey = autoReviewRkey(art.uri, art.cid) + repoA.set(`${COLLECTIONS.artifactRequest}/${rkey}`, { + uri: `at://${AGENT_A}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: 'cid-a', + value: { $type: COLLECTIONS.artifactRequest, type: 'review', subject: { uri: art.uri, cid: 'WRONG' }, basedOn: [], goal: base._goalRef, assignee: AGENT_A, createdAt: 'x' }, + }) + repoB.set(`${COLLECTIONS.artifactRequest}/${rkey}`, { + uri: `at://${AGENT_B}/${COLLECTIONS.artifactRequest}/${rkey}`, + cid: 'cid-b', + value: { $type: COLLECTIONS.artifactRequest, type: 'review', subject: { uri: art.uri, cid: art.cid }, basedOn: [{ uri: art.uri, cid: art.cid }], goal: base._goalRef, assignee: AGENT_B, createdAt: 'x' }, + }) + const actorsFor = () => + registry([pdsActor(AGENT_A, ['plan', 'review'], repoA, creates), pdsActor(AGENT_B, ['plan', 'review'], repoB, creates)]) + const t = trigger(stateDir(), undefined, (m) => logs.push(m)) + t.pump(empty, actorsFor()); await t.drain() // seed + t.pump(withArt, actorsFor()); await t.drain() + assert.equal(creates.length, 0, 'adopted B\'s valid record despite A\'s mismatch') + assert.equal(logs.filter((m) => new RegExp(`adopted.*${AGENT_B}`).test(m)).length, 1) + assert.equal(logs.filter((m) => /refusing to adopt/.test(m)).length, 0) + }) +}) -- knotmirror 0.0.1 From 8de58da6f11c1dc401143e6ed1319763bc4cd6c2 Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 14:50:02 -0700 Subject: [PATCH 09/13] daemon: auto-review reads effective ProjectView.autoReview overlay Co-Authored-By: Claude Fable 5 --- packages/daemon/src/auto-review.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/daemon/src/auto-review.ts b/packages/daemon/src/auto-review.ts index 07f8196..266b233 100644 --- a/packages/daemon/src/auto-review.ts +++ b/packages/daemon/src/auto-review.ts @@ -48,12 +48,11 @@ export function autoReviewRkey(subjectUri: string, subjectCid: string, retracted /** * The project's per-artifact-type auto-review defaults, read through THIS single helper on purpose. - * A concurrent issue is adding a computed `ProjectView.autoReview` overlay (standing `setAutoReview` - * records), and at merge the switch is a ONE-LINER here: prefer the overlay when present, e.g. - * `return ((projectView as { autoReview?: Record }).autoReview ?? onRecord)`. - * Today only the on-project-record default exists. + * `ProjectView.autoReview` already merges the on-record default with the admin `setAutoReview` + * overlay (latest-wins per type), so it is the single source of truth. */ export function projectAutoReviewConfig(projectView: ProjectView): Record { + if (projectView.autoReview) return projectView.autoReview const config = projectView.target.value.autoReview return config && typeof config === 'object' ? (config as Record) : {} } -- knotmirror 0.0.1 From 39981f39ebff548cb7aee1a42a4b484f2e38b40a Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 14:53:24 -0700 Subject: [PATCH 10/13] core: generalize turn bundle for project-scoped owners + capture source goals buildTurnBundle now resolves a request from either index.goals or index.projects, making TurnBundle.goal optional: a goal-scoped request keeps its own goal; a project-scoped CAPTURE request derives the source goal from the goal anchor of its directly-resolved basedOn artifacts (lowest goal uri on a tie), and a direct project request has no goal. The project view is the owning project for a project-scoped request. Thread merges the anchoring goal's messages with the owning project view's messages anchored to a resolved artifact. currentSystemArtifacts continues to ride in every bundle (goal- and project-scoped alike). The review subject-seeding composes unchanged, so a project-scoped review bundle works too. Also fix awaiting-input to scan the space-global trusted message set rather than a single view's: a project-scoped capture turn's question is anchored to the source goal (goal view) while its request lives in the project view, so a per-view scan would miss it and the daemon would redispatch over the open question. Exact request/question strongref matching keeps the wider scan from mis-attributing. Tests: capture/direct/project-review bundle shapes, multiple-source-goal determinism, goal-scoped bundles carrying system artifacts, cross-view awaiting-input golden + 100-permutation invariance. Co-Authored-By: Claude Fable 5 --- packages/core/src/bundle.ts | 82 ++++++++-- packages/core/src/materializer.ts | 15 +- packages/core/test/awaiting-input.test.mjs | 53 +++++++ packages/core/test/bundle.test.mjs | 168 +++++++++++++++++++++ 4 files changed, 303 insertions(+), 15 deletions(-) diff --git a/packages/core/src/bundle.ts b/packages/core/src/bundle.ts index b2b71ab..5c194ca 100644 --- a/packages/core/src/bundle.ts +++ b/packages/core/src/bundle.ts @@ -4,11 +4,12 @@ import type { ArtifactRequestRecord, CheckrunRecord, CheckrunResult, + MessageRecord, ReviewFinding, ReviewRecord, StrongRef, } from './generated/records.js' -import type { GoalView, IndexedRecord, MaterializedIndex } from './materializer.js' +import type { GoalView, IndexedRecord, MaterializedIndex, ProjectView } from './materializer.js' export interface BundleArtifact { uri: string @@ -22,7 +23,10 @@ export interface BundleArtifact { export interface TurnBundle { request: { uri: string; cid: string; type: string; brief?: string; basedOn: StrongRef[] } - goal: { uri: string; cid: string; title: string; body: string } + /** The anchoring goal. Present for a goal-scoped request (its own goal) and for a project-scoped + * CAPTURE request (the source artifact's goal, reached through basedOn). Absent for a direct + * project-scoped request that isn't distilling from any goal artifact. */ + goal?: { uri: string; cid: string; title: string; body: string } project: { uri: string; cid: string; name: string; gitUrl: string; defaultBranch: string } basedOn: BundleArtifact[] /** For a `review`-type request: the artifact under review. It is also seeded into the basedOn @@ -63,7 +67,10 @@ export function buildTurnBundle( requestUri: string, requestCid: string, ): TurnBundle { + // Owner search: goal-scoped requests live under a goal (index.goals); project-scoped requests + // (both direct and capture) live under a project (index.projects). Track which kind owns it. let owningGoal: GoalView | undefined + let owningProject: ProjectView | undefined let request: IndexedRecord | undefined for (const goal of index.goals) { const candidate = goal.requests.find((entry) => entry.uri === requestUri) @@ -73,17 +80,30 @@ export function buildTurnBundle( break } } - if (!owningGoal || !request) { + if (!request) { + for (const project of index.projects) { + const candidate = project.requests.find((entry) => entry.uri === requestUri) + if (candidate) { + owningProject = project + request = candidate + break + } + } + } + if (!request) { throw new Error(`buildTurnBundle: no request found at ${requestUri}`) } if (request.cid !== requestCid) { throw new Error(`buildTurnBundle: cid mismatch for ${requestUri}`) } - const goalRecord = owningGoal.target - const projectView = index.projects.find((view) => view.target.uri === goalRecord.value.project.uri) + // projectView: a goal-scoped request → the goal's project; a project-scoped request → its own + // owning project view. + const projectView: ProjectView | undefined = owningGoal + ? index.projects.find((view) => view.target.uri === owningGoal.target.value.project.uri) + : owningProject if (!projectView) { - throw new Error(`buildTurnBundle: no project found for goal ${goalRecord.uri}`) + throw new Error(`buildTurnBundle: no project found for request ${requestUri}`) } // basedOn can cross goal/project scopes, so lookup maps are built across the whole index. @@ -156,6 +176,23 @@ export function buildTurnBundle( if (resolvedSubject) subject = toBundleArtifact(resolvedSubject) } + // The bundle's anchoring goal. A goal-owned request uses its own goal. A project-owned (capture) + // request distils from a goal artifact: among its DIRECTLY resolved basedOn artifacts, any that + // carry a `goal` anchor identify the source goal. On more than one distinct source goal, pick the + // lowest goal uri deterministically. None → the bundle has no goal (a direct project request). + let goalView: GoalView | undefined = owningGoal + if (!owningGoal) { + const sourceGoalUris = new Set() + for (const reference of request.value.basedOn) { + const artifact = artifactByRef.get(refKey(reference)) + if (artifact?.value.goal) sourceGoalUris.add(artifact.value.goal.uri) + } + if (sourceGoalUris.size > 0) { + const chosen = [...sourceGoalUris].sort()[0] + goalView = index.goals.find((view) => view.target.uri === chosen) + } + } + const basedOn = [...resolvedArtifacts.values()].map(toBundleArtifact).sort(byCreatedThenUri) const reviewFindings = allReviews @@ -188,7 +225,22 @@ export function buildTurnBundle( .map(toBundleArtifact) .sort(byCreatedThenUri) - const thread = owningGoal.messages + // Thread: the anchoring goal's messages (owning goal, or the capture source goal), PLUS — for a + // project-owned request — the owning project view's messages anchored to a resolved artifact + // (system-artifact threads that carry no goal). Merge, dedupe by uri, then sort with the shared + // byCreatedThenUri so the result is arrival-order invariant. + const threadMessages = new Map>() + if (goalView) { + for (const message of goalView.messages) threadMessages.set(message.uri, message) + } + if (owningProject) { + for (const message of projectView.messages) { + if (message.value.artifact && resolvedArtifacts.has(refKey(message.value.artifact))) { + threadMessages.set(message.uri, message) + } + } + } + const thread = [...threadMessages.values()] .map((message) => ({ uri: message.uri, author: message.did, @@ -211,12 +263,16 @@ export function buildTurnBundle( ...(request.value.brief !== undefined ? { brief: request.value.brief } : {}), basedOn: request.value.basedOn, }, - goal: { - uri: goalRecord.uri, - cid: goalRecord.cid, - title: goalRecord.value.title, - body: goalRecord.value.body, - }, + ...(goalView + ? { + goal: { + uri: goalView.target.uri, + cid: goalView.target.cid, + title: goalView.target.value.title, + body: goalView.target.value.body, + }, + } + : {}), project: { uri: projectView.target.uri, cid: projectView.target.cid, diff --git a/packages/core/src/materializer.ts b/packages/core/src/materializer.ts index 5d2bae0..8b7b454 100644 --- a/packages/core/src/materializer.ts +++ b/packages/core/src/materializer.ts @@ -298,6 +298,13 @@ interface ViewInput { merges: Array> messages: Array> claims: Array> + // Space-global trusted messages, used ONLY for the awaiting-input computation. A question `re`ing a + // request can be anchored to a different target than the request itself (a project-scoped capture + // turn asks its question anchored to the source goal, so the message lands in the goal view while + // the request lives in the project view). Awaiting-input must therefore scan every trusted message, + // not just this target's `messages` (which drive the displayed thread). Matching is by exact + // request/question strongref, so the wider scan never mis-attributes across targets. + allMessages: Array> // refKeys (uri#cid) of requests a trusted retract tombstone has withdrawn. Global set, keyed by // strongref; buildView only sees this target's requests, so cross-target keys never collide. retractedRefs: Set @@ -309,7 +316,10 @@ interface ViewInput { // `q.value.re` pointing at the request (exact uri#cid match), and `q.value.declines` // not `true`, for which no trusted message `a` (authored by a different member, // i.e. `a.did !== q.did`) has `a.value.parent` pointing back at `q`. This is purely -// structural over the already-trusted, target-scoped messages/requests passed in. +// structural over the already-trusted records passed in. `requests` is this target's requests, but +// `messages` is the space-global trusted set (a question can be anchored to a different target than +// the request it answers — see ViewInput.allMessages); exact request/question strongref matching +// keeps the wider scan from mis-attributing across targets. function computeAwaitingInput( requests: Array>, messages: Array>, @@ -397,7 +407,7 @@ function buildView(input: ViewInput): T requests: input.requests.sort(compareRecord), openRequests: openRequests.sort(compareRecord), retracted: retracted.sort(compareRecord), - awaitingInput: computeAwaitingInput(input.requests, input.messages), + awaitingInput: computeAwaitingInput(input.requests, input.allMessages), artifacts: input.artifacts.sort(compareRecord), artifactChains: buildChains(input.artifacts), reviews: input.reviews @@ -606,6 +616,7 @@ export function materialize(store: RecordStore, options: MaterializeOptions): Ma merges: merges.filter((merge) => targetUriForMerge(merge) === target.uri), messages: messages.filter((message) => targetUriForMessage(message) === target.uri), claims: claims.filter((claim) => targetUriForClaim(claim) === target.uri), + allMessages: messages, retractedRefs, asOf, }) diff --git a/packages/core/test/awaiting-input.test.mjs b/packages/core/test/awaiting-input.test.mjs index f37b1a0..952aad8 100644 --- a/packages/core/test/awaiting-input.test.mjs +++ b/packages/core/test/awaiting-input.test.mjs @@ -412,3 +412,56 @@ describe('TargetView.awaitingInput', () => { } }) }) + +// A project-scoped CAPTURE request whose fulfilling turn asks a question anchored to the SOURCE GOAL +// (a project-scoped turn has no goal of its own; per the turn's askQuestion precedence the message +// is anchored to the capture source goal). The question message therefore lands in the goal view +// while the request lives in the project view — so awaitingInput must scan the space-global message +// set, not just the request's own view, or the daemon would redispatch over the open question. +function crossViewAwaitingScenario({ answered = false } = {}) { + const records = [] + const add = (record) => (records.push(record), record) + const space = add(make(ROOT, COLLECTIONS.space, 'space', 'cid-space', { $type: COLLECTIONS.space, name: 'X', description: 'cross-view awaiting', createdAt: '2026-01-01T00:00:00Z' })) + const spaceRef = ref(space) + add(make(ROOT, COLLECTIONS.addMember, 'm-h', 'cid-m-h', { $type: COLLECTIONS.addMember, space: spaceRef, did: HUMAN, kind: 'human', role: 'member', createdAt: '2026-01-01T00:00:01Z' })) + add(make(ROOT, COLLECTIONS.addMember, 'm-a', 'cid-m-a', { $type: COLLECTIONS.addMember, space: spaceRef, did: AGENT_A, kind: 'agent', role: 'agent', createdAt: '2026-01-01T00:00:02Z' })) + add(make(ROOT, COLLECTIONS.artifactType, 't-plan', 'cid-t-plan', { $type: COLLECTIONS.artifactType, space: spaceRef, name: 'plan', brief: 'p', outputSpec: { format: 'markdown', description: 'x' }, scope: 'goal', createdAt: '2026-01-01T00:00:10Z' })) + add(make(ROOT, COLLECTIONS.artifactType, 't-adr', 'cid-t-adr', { $type: COLLECTIONS.artifactType, space: spaceRef, name: 'adr', brief: 'a', outputSpec: { format: 'markdown', description: 'x' }, scope: 'project', createdAt: '2026-01-01T00:00:11Z' })) + const project = add(make(HUMAN, COLLECTIONS.project, 'project', 'cid-project', { $type: COLLECTIONS.project, space: spaceRef, name: 'demo', gitUrl: 'https://example.com/demo.git', defaultBranch: 'main', checks: [], autoReview: {}, createdAt: '2026-01-01T00:01:00Z' })) + const goal = add(make(HUMAN, COLLECTIONS.goal, 'goal', 'cid-goal', { $type: COLLECTIONS.goal, space: spaceRef, project: ref(project), title: 'G', body: 'b', createdAt: '2026-01-01T00:02:00Z' })) + const planReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'plan-req', 'cid-plan-req', { $type: COLLECTIONS.artifactRequest, goal: ref(goal), type: 'plan', basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:03:00Z' })) + const planArt = add(make(AGENT_A, COLLECTIONS.artifact, 'plan-art', 'cid-plan-art', { $type: COLLECTIONS.artifact, request: ref(planReq), goal: ref(goal), type: 'plan', body: 'plan', links: {}, createdAt: '2026-01-01T00:03:30Z' })) + const captureReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'capture-req', 'cid-capture-req', { $type: COLLECTIONS.artifactRequest, project: ref(project), type: 'adr', basedOn: [ref(planArt)], assignee: AGENT_A, createdAt: '2026-01-01T00:04:00Z' })) + // The turn's question: anchored to the source GOAL (goal view), `re` the project-scoped request. + const question = add(make(AGENT_A, COLLECTIONS.message, 'q', 'cid-q', { $type: COLLECTIONS.message, goal: ref(goal), body: 'which decision format?', mentions: [HUMAN], re: ref(captureReq), createdAt: '2026-01-01T00:04:10Z' })) + if (answered) { + add(make(HUMAN, COLLECTIONS.message, 'a', 'cid-a', { $type: COLLECTIONS.message, goal: ref(goal), body: 'use the standard template', mentions: [AGENT_A], parent: ref(question), createdAt: '2026-01-01T00:04:20Z' })) + } + return { records, spaceUri: space.uri, projectUri: project.uri, captureReqUri: captureReq.uri } +} + +describe('ProjectView.awaitingInput (cross-view question)', () => { + it('flags a project-scoped capture request whose question is anchored to the source goal', () => { + const scenario = crossViewAwaitingScenario() + const index = build(scenario.records, scenario.spaceUri) + const project = index.projects.find((view) => view.target.uri === scenario.projectUri) + assert.ok(project.awaitingInput.includes(scenario.captureReqUri)) + // The request is not fulfilled — it stays open, flagged awaiting input. + assert.ok(project.openRequests.some((request) => request.uri === scenario.captureReqUri)) + }) + + it('clears once a different member answers the goal-anchored question', () => { + const scenario = crossViewAwaitingScenario({ answered: true }) + const index = build(scenario.records, scenario.spaceUri) + const project = index.projects.find((view) => view.target.uri === scenario.projectUri) + assert.equal(project.awaitingInput.includes(scenario.captureReqUri), false) + }) + + it('is invariant under 100 deterministic random arrival permutations', () => { + const scenario = crossViewAwaitingScenario() + const expected = build(scenario.records, scenario.spaceUri) + for (let seed = 1; seed <= 100; seed += 1) { + assert.deepEqual(build(shuffled(scenario.records, seed), scenario.spaceUri), expected, `seed ${seed}`) + } + }) +}) diff --git a/packages/core/test/bundle.test.mjs b/packages/core/test/bundle.test.mjs index 3e00a3e..9e13b92 100644 --- a/packages/core/test/bundle.test.mjs +++ b/packages/core/test/bundle.test.mjs @@ -676,3 +676,171 @@ describe('buildTurnBundle (review requests)', () => { } }) }) + +// --- Project-scoped (system artifact) requests ------------------------------ + +// One project with: +// - a goal G with a plan artifact PA (the capture source) and a goal-anchored message M1 +// - a project-scoped adr chain adr1 -> adr2, with a message MA anchored to adr2 +// - a capture request CR (project-scoped `adr`, basedOn the plan artifact PA) +// - a direct request DR (project-scoped `adr`, basedOn adr2 — a prev-chain walk, no source goal) +// - a project-scoped review request RR whose subject is adr2 +function systemArtifactScenario() { + const records = [] + const add = (r) => (records.push(r), r) + const space = add(make(ROOT, COLLECTIONS.space, 'space', 'cid-space', { $type: COLLECTIONS.space, name: 'S', description: '', createdAt: '2026-01-01T00:00:00Z' })) + const spaceRef = ref(space) + add(make(ROOT, COLLECTIONS.addMember, 'm-h', 'cid-mh', { $type: COLLECTIONS.addMember, space: spaceRef, did: HUMAN, kind: 'human', role: 'member', createdAt: '2026-01-01T00:00:01Z' })) + add(make(ROOT, COLLECTIONS.addMember, 'm-a', 'cid-ma', { $type: COLLECTIONS.addMember, space: spaceRef, did: AGENT_A, kind: 'agent', role: 'agent', createdAt: '2026-01-01T00:00:02Z' })) + add(make(ROOT, COLLECTIONS.artifactType, 't-plan', 'cid-t-plan', { $type: COLLECTIONS.artifactType, space: spaceRef, name: 'plan', brief: 'p', outputSpec: { format: 'markdown', description: 'x' }, scope: 'goal', createdAt: '2026-01-01T00:00:10Z' })) + add(make(ROOT, COLLECTIONS.artifactType, 't-adr', 'cid-t-adr', { $type: COLLECTIONS.artifactType, space: spaceRef, name: 'adr', brief: 'a', outputSpec: { format: 'markdown', description: 'x' }, scope: 'project', createdAt: '2026-01-01T00:00:11Z' })) + const project = add(make(HUMAN, COLLECTIONS.project, 'proj', 'cid-proj', { $type: COLLECTIONS.project, space: spaceRef, name: 'p', gitUrl: 'https://github.com/acme/widget.git', defaultBranch: 'main', checks: [], autoReview: {}, createdAt: '2026-01-01T00:01:00Z' })) + const goal = add(make(HUMAN, COLLECTIONS.goal, 'goal', 'cid-goal', { $type: COLLECTIONS.goal, space: spaceRef, project: ref(project), title: 'G', body: 'b', createdAt: '2026-01-01T00:02:00Z' })) + + // Capture source: a goal plan artifact + its message. + const planReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'plan-req', 'cid-plan-req', { $type: COLLECTIONS.artifactRequest, goal: ref(goal), type: 'plan', basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:03:00Z' })) + const planArt = add(make(AGENT_A, COLLECTIONS.artifact, 'plan-art', 'cid-plan-art', { $type: COLLECTIONS.artifact, request: ref(planReq), goal: ref(goal), type: 'plan', body: 'the plan', links: {}, criteria: ['x'], createdAt: '2026-01-01T00:04:00Z' })) + const goalMsg = add(make(HUMAN, COLLECTIONS.message, 'gm', 'cid-gm', { $type: COLLECTIONS.message, goal: ref(goal), body: 'goal thread', mentions: [], createdAt: '2026-01-01T00:04:10Z' })) + + // Project-scoped adr chain adr1 -> adr2 (each needs its own request to materialize). + const adr1Req = add(make(HUMAN, COLLECTIONS.artifactRequest, 'adr1-req', 'cid-adr1-req', { $type: COLLECTIONS.artifactRequest, project: ref(project), type: 'adr', basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:05:00Z' })) + const adr1 = add(make(AGENT_A, COLLECTIONS.artifact, 'adr1', 'cid-adr1', { $type: COLLECTIONS.artifact, request: ref(adr1Req), project: ref(project), type: 'adr', body: 'adr v1', links: {}, createdAt: '2026-01-01T00:05:30Z' })) + const adr2Req = add(make(HUMAN, COLLECTIONS.artifactRequest, 'adr2-req', 'cid-adr2-req', { $type: COLLECTIONS.artifactRequest, project: ref(project), type: 'adr', basedOn: [ref(adr1)], assignee: AGENT_A, createdAt: '2026-01-01T00:06:00Z' })) + const adr2 = add(make(AGENT_A, COLLECTIONS.artifact, 'adr2', 'cid-adr2', { $type: COLLECTIONS.artifact, request: ref(adr2Req), project: ref(project), type: 'adr', prev: ref(adr1), body: 'adr v2', links: {}, createdAt: '2026-01-01T00:06:30Z' })) + const adrMsg = add(make(AGENT_A, COLLECTIONS.message, 'am', 'cid-am', { $type: COLLECTIONS.message, artifact: ref(adr2), body: 'adr thread', mentions: [], createdAt: '2026-01-01T00:06:45Z' })) + + // The three requests under test. + const captureReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'capture-req', 'cid-capture-req', { $type: COLLECTIONS.artifactRequest, project: ref(project), type: 'adr', basedOn: [ref(planArt)], brief: 'Distill an ADR from the plan.', assignee: AGENT_A, createdAt: '2026-01-01T00:07:00Z' })) + const directReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'direct-req', 'cid-direct-req', { $type: COLLECTIONS.artifactRequest, project: ref(project), type: 'adr', basedOn: [ref(adr2)], assignee: AGENT_A, createdAt: '2026-01-01T00:07:30Z' })) + const reviewReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'preview-req', 'cid-preview-req', { $type: COLLECTIONS.artifactRequest, project: ref(project), type: 'review', subject: ref(adr2), basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:08:00Z' })) + + return { + records, + spaceUri: space.uri, + goalUri: goal.uri, + projectUri: project.uri, + planReq, + planArtRef: ref(planArt), + adr1Ref: ref(adr1), + adr2Ref: ref(adr2), + goalMsgBody: goalMsg.value.body, + adrMsgBody: adrMsg.value.body, + captureReq, + directReq, + reviewReq, + } +} + +function buildFor(records, scenario, requestRef) { + const store = new MemoryRecordStore() + records.forEach((r) => store.put(r)) + const index = materialize(store, { spaceUri: scenario.spaceUri, asOf: AS_OF }) + return buildTurnBundle(index, requestRef.uri, requestRef.cid) +} + +describe('buildTurnBundle (project-scoped requests)', () => { + it('capture request: goal is the source goal, basedOn ancestry + source-goal thread + system artifacts', () => { + const scenario = systemArtifactScenario() + const bundle = buildFor(scenario.records, scenario, scenario.captureReq) + + assert.equal(bundle.request.type, 'adr') + // The distilled ADR anchors to the SOURCE goal, reached through basedOn. + assert.ok(bundle.goal) + assert.equal(bundle.goal.uri, scenario.goalUri) + // The source plan artifact rides in. + assert.deepEqual(bundle.basedOn.map((a) => a.uri), [scenario.planArtRef.uri]) + // The project is the owning project. + assert.equal(bundle.project.uri, scenario.projectUri) + // The current system artifact (adr v2, current of the adr1->adr2 chain) is in EVERY bundle. + assert.deepEqual(bundle.currentSystemArtifacts.map((a) => a.uri), [scenario.adr2Ref.uri]) + // Thread is the SOURCE goal's thread (the adr-anchored message is not on a resolved artifact here). + assert.deepEqual(bundle.thread.map((m) => m.body), [scenario.goalMsgBody]) + }) + + it('direct project request: no goal, prev-chain walk, and artifact-anchored thread messages included', () => { + const scenario = systemArtifactScenario() + const bundle = buildFor(scenario.records, scenario, scenario.directReq) + + assert.equal(bundle.goal, undefined) // a direct project request distils from no goal + assert.equal(bundle.project.uri, scenario.projectUri) + // basedOn adr2 walks its prev chain back to adr1. + assert.deepEqual(bundle.basedOn.map((a) => a.uri).sort(), [scenario.adr1Ref.uri, scenario.adr2Ref.uri].sort()) + // The message anchored to adr2 (a resolved artifact) rides in the thread. + assert.deepEqual(bundle.thread.map((m) => m.body), [scenario.adrMsgBody]) + assert.deepEqual(bundle.currentSystemArtifacts.map((a) => a.uri), [scenario.adr2Ref.uri]) + }) + + it('project-scoped review request: subject seeded, owner is the project, no goal', () => { + const scenario = systemArtifactScenario() + const bundle = buildFor(scenario.records, scenario, scenario.reviewReq) + + assert.equal(bundle.request.type, 'review') + assert.ok(bundle.subject) + assert.equal(bundle.subject.uri, scenario.adr2Ref.uri) + assert.equal(bundle.subject.type, 'adr') + assert.equal(bundle.goal, undefined) + assert.equal(bundle.project.uri, scenario.projectUri) + // The subject and its ancestry seed basedOn. + assert.deepEqual(bundle.basedOn.map((a) => a.uri).sort(), [scenario.adr1Ref.uri, scenario.adr2Ref.uri].sort()) + }) + + it('a goal-scoped bundle also carries the current system artifacts (long-term memory)', () => { + const scenario = systemArtifactScenario() + const bundle = buildFor(scenario.records, scenario, scenario.planReq) + assert.ok(bundle.goal) + assert.deepEqual(bundle.currentSystemArtifacts.map((a) => a.uri), [scenario.adr2Ref.uri]) + }) + + it('capture and direct bundles are invariant under 100 deterministic arrival permutations', () => { + const scenario = systemArtifactScenario() + for (const requestRef of [scenario.captureReq, scenario.directReq, scenario.reviewReq]) { + const expected = buildFor(scenario.records, scenario, requestRef) + for (let seed = 1; seed <= 100; seed += 1) { + const actual = buildFor(shuffled(scenario.records, seed), scenario, requestRef) + assert.deepEqual(actual, expected, `${requestRef.rkey} seed ${seed}`) + } + } + }) +}) + +// Two goals each with a plan artifact; a capture request basedOn BOTH. The source goal is chosen +// deterministically as the lowest goal uri. +function multiSourceCaptureScenario() { + const records = [] + const add = (r) => (records.push(r), r) + const space = add(make(ROOT, COLLECTIONS.space, 'space', 'cid-space', { $type: COLLECTIONS.space, name: 'S', description: '', createdAt: '2026-01-01T00:00:00Z' })) + const spaceRef = ref(space) + add(make(ROOT, COLLECTIONS.addMember, 'm-h', 'cid-mh', { $type: COLLECTIONS.addMember, space: spaceRef, did: HUMAN, kind: 'human', role: 'member', createdAt: '2026-01-01T00:00:01Z' })) + add(make(ROOT, COLLECTIONS.addMember, 'm-a', 'cid-ma', { $type: COLLECTIONS.addMember, space: spaceRef, did: AGENT_A, kind: 'agent', role: 'agent', createdAt: '2026-01-01T00:00:02Z' })) + add(make(ROOT, COLLECTIONS.artifactType, 't-plan', 'cid-t-plan', { $type: COLLECTIONS.artifactType, space: spaceRef, name: 'plan', brief: 'p', outputSpec: { format: 'markdown', description: 'x' }, scope: 'goal', createdAt: '2026-01-01T00:00:10Z' })) + add(make(ROOT, COLLECTIONS.artifactType, 't-adr', 'cid-t-adr', { $type: COLLECTIONS.artifactType, space: spaceRef, name: 'adr', brief: 'a', outputSpec: { format: 'markdown', description: 'x' }, scope: 'project', createdAt: '2026-01-01T00:00:11Z' })) + const project = add(make(HUMAN, COLLECTIONS.project, 'proj', 'cid-proj', { $type: COLLECTIONS.project, space: spaceRef, name: 'p', gitUrl: 'https://github.com/acme/widget.git', defaultBranch: 'main', checks: [], autoReview: {}, createdAt: '2026-01-01T00:01:00Z' })) + // goalA rkey sorts before goalB — the tie-break picks goalA. + const goalA = add(make(HUMAN, COLLECTIONS.goal, 'goal-a', 'cid-goal-a', { $type: COLLECTIONS.goal, space: spaceRef, project: ref(project), title: 'GA', body: 'b', createdAt: '2026-01-01T00:02:00Z' })) + const goalB = add(make(HUMAN, COLLECTIONS.goal, 'goal-b', 'cid-goal-b', { $type: COLLECTIONS.goal, space: spaceRef, project: ref(project), title: 'GB', body: 'b', createdAt: '2026-01-01T00:02:10Z' })) + const reqA = add(make(HUMAN, COLLECTIONS.artifactRequest, 'reqa', 'cid-reqa', { $type: COLLECTIONS.artifactRequest, goal: ref(goalA), type: 'plan', basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:03:00Z' })) + const artA = add(make(AGENT_A, COLLECTIONS.artifact, 'arta', 'cid-arta', { $type: COLLECTIONS.artifact, request: ref(reqA), goal: ref(goalA), type: 'plan', body: 'plan A', links: {}, createdAt: '2026-01-01T00:03:30Z' })) + const reqB = add(make(HUMAN, COLLECTIONS.artifactRequest, 'reqb', 'cid-reqb', { $type: COLLECTIONS.artifactRequest, goal: ref(goalB), type: 'plan', basedOn: [], assignee: AGENT_A, createdAt: '2026-01-01T00:04:00Z' })) + const artB = add(make(AGENT_A, COLLECTIONS.artifact, 'artb', 'cid-artb', { $type: COLLECTIONS.artifact, request: ref(reqB), goal: ref(goalB), type: 'plan', body: 'plan B', links: {}, createdAt: '2026-01-01T00:04:30Z' })) + const captureReq = add(make(HUMAN, COLLECTIONS.artifactRequest, 'cap', 'cid-cap', { $type: COLLECTIONS.artifactRequest, project: ref(project), type: 'adr', basedOn: [ref(artB), ref(artA)], assignee: AGENT_A, createdAt: '2026-01-01T00:05:00Z' })) + return { records, spaceUri: space.uri, captureReq, goalAUri: goalA.uri, goalBUri: goalB.uri } +} + +describe('buildTurnBundle (multiple capture source goals)', () => { + it('picks the lowest goal uri deterministically as the source goal', () => { + const scenario = multiSourceCaptureScenario() + const bundle = buildFor(scenario.records, scenario, scenario.captureReq) + assert.ok(scenario.goalAUri < scenario.goalBUri) // fixture sanity + assert.ok(bundle.goal) + assert.equal(bundle.goal.uri, scenario.goalAUri) + }) + + it('source-goal choice is invariant under 100 deterministic arrival permutations', () => { + const scenario = multiSourceCaptureScenario() + const expected = buildFor(scenario.records, scenario, scenario.captureReq) + for (let seed = 1; seed <= 100; seed += 1) { + const actual = buildFor(shuffled(scenario.records, seed), scenario, scenario.captureReq) + assert.deepEqual(actual, expected, `seed ${seed}`) + } + }) +}) -- knotmirror 0.0.1 From 12bb0963445558785eccf79f243dcd24bf03673e Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 14:53:35 -0700 Subject: [PATCH 11/13] daemon: project-scoped turn anchor, askQuestion precedence, bundle rendering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generalize the turn's request anchor to goal- OR project-scoped (TurnRequestAnchor): runTurn threads it through, #submitArtifact writes whichever anchor is present and its adoption comparison follows suit, and a project-scoped turn stays non-impl so it gets a read-only checkout at the default branch. #askQuestion follows the decided precedence for a project turn with no goal of its own: (1) the capture source goal, (2) else the lowest-uri resolved basedOn artifact, (3) else a clear rejection — the daemon threads the resolved anchor in via TurnRequestContext.questionAnchor. bundle-writer: render a project header for a goal-less bundle and add the missing "## System artifacts" section (currentSystemArtifacts) so the agent actually sees the project's long-term memory the bundle.json already carried. turn-socket: harden parseReviewEnvelope to the review lexicon at the untrusted edge — finding path <= 2000 chars and line an integer >= 1. Tests: project-anchored submitArtifact + adoption, askQuestion precedence (all three branches), review path/line rejection, project-scoped read-only checkout turn, no-goal header + system-artifacts rendering. Co-Authored-By: Claude Fable 5 --- packages/daemon/src/bundle-writer.ts | 15 +- packages/daemon/src/turn-socket.ts | 51 +++++-- packages/daemon/src/turn.ts | 18 ++- packages/daemon/test/bundle-writer.test.mjs | 29 ++++ packages/daemon/test/turn-socket.test.mjs | 146 ++++++++++++++++++++ packages/daemon/test/turn.test.mjs | 58 ++++++++ 6 files changed, 303 insertions(+), 14 deletions(-) diff --git a/packages/daemon/src/bundle-writer.ts b/packages/daemon/src/bundle-writer.ts index cabab9a..5a05757 100644 --- a/packages/daemon/src/bundle-writer.ts +++ b/packages/daemon/src/bundle-writer.ts @@ -11,9 +11,11 @@ export interface WrittenBundle { function summarizeBundle(bundle: PlanTurnBundle): string { const lines = [ - `# ${bundle.goal.title}`, - '', - bundle.goal.body, + // A goal-scoped request (or a project-scoped capture with a source goal) has a goal header; a + // direct project-scoped request has none, so the header names the project instead. + ...(bundle.goal + ? [`# ${bundle.goal.title}`, '', bundle.goal.body] + : [`# ${bundle.project.name} (project-scoped request)`]), '', '## Project', `${bundle.project.name} — ${bundle.project.gitUrl} (${bundle.project.defaultBranch})`, @@ -26,6 +28,13 @@ function summarizeBundle(bundle: PlanTurnBundle): string { ? bundle.basedOn.map((artifact) => `- ${artifact.type} ${artifact.uri}`) : ['(none)']), '', + // The current version of each project-scoped system artifact rides in EVERY bundle — the agents' + // long-term memory (design §8). bundle.json already carries them; render them here too. + '## System artifacts', + ...(bundle.currentSystemArtifacts.length > 0 + ? bundle.currentSystemArtifacts.map((artifact) => `- ${artifact.type} ${artifact.uri}`) + : ['(none)']), + '', '## Review findings', ...(bundle.reviewFindings.length > 0 ? bundle.reviewFindings.map( diff --git a/packages/daemon/src/turn-socket.ts b/packages/daemon/src/turn-socket.ts index aa51c03..a74eaaa 100644 --- a/packages/daemon/src/turn-socket.ts +++ b/packages/daemon/src/turn-socket.ts @@ -46,16 +46,28 @@ export type TurnMode = | { kind: 'artifact'; type: string } | { kind: 'review'; subject: StrongRef } +/** The anchor a turn's artifact/message records hang off. Exactly one of goal|project is present: + * a goal-scoped request carries `goal`, a project-scoped (system-artifact) request carries + * `project`. The lexicon's exactOne(goal, project) invariant is honored by construction. */ +export type TurnRequestAnchor = + | { uri: string; cid: string; goal: StrongRef; project?: undefined } + | { uri: string; cid: string; project: StrongRef; goal?: undefined } + export interface TurnRequestContext { token: string - /** The goal-scoped request being fulfilled. */ - request: { uri: string; cid: string; goal: StrongRef } + /** The request being fulfilled, with its goal- or project-scope anchor. */ + request: TurnRequestAnchor client: TurnRecordWriter now?: () => string /** Discriminated turn mode, owned by the daemon (see TurnMode). */ mode: TurnMode /** Daemon-owned implementation provenance. */ implementation?: { gitUrl: string; branch: string; prev?: StrongRef } + /** Message anchor for a project-scoped turn's question (askQuestion). The message lexicon requires + * exactly one goal|artifact anchor, and a project-scoped request has no goal of its own, so the + * daemon threads the resolved anchor here: the capture source goal, else the lowest-uri resolved + * basedOn artifact. Absent → a direct project turn without basedOn cannot ask a question (v1). */ + questionAnchor?: { goal: StrongRef } | { artifact: StrongRef } } export interface TurnObservation { @@ -180,8 +192,9 @@ function parseReviewEnvelope(raw: Record, token: string): Parse const { path, line, severity, body } = finding if (severity !== 'info' && severity !== 'warning' && severity !== 'error') return undefined if (typeof body !== 'string' || body.length > 10_000) return undefined - if (path !== undefined && typeof path !== 'string') return undefined - if (line !== undefined && (typeof line !== 'number' || !Number.isInteger(line))) return undefined + // Mirror the review lexicon exactly at the untrusted edge: path ≤ 2000 chars, line an integer ≥ 1. + if (path !== undefined && (typeof path !== 'string' || path.length > 2000)) return undefined + if (line !== undefined && (typeof line !== 'number' || !Number.isInteger(line) || line < 1)) return undefined parsed.push({ severity, body, @@ -432,10 +445,12 @@ export class TurnSocketServer { prev = this.#context.implementation.prev } + // Exactly one of goal|project, per the request's scope — the lexicon's exactOne(goal, project). + const anchor = request.goal ? { goal: request.goal } : { project: request.project } const record: ArtifactRecord = { $type: COLLECTIONS.artifact, request: { uri: request.uri, cid: request.cid }, - goal: request.goal, + ...anchor, type, body: envelope.body, links, @@ -460,13 +475,16 @@ export class TurnSocketServer { throw error } const current = existing.value as ArtifactRecord + // Compare against whichever anchor this request carries (goal- or project-scoped). + const currentAnchor = request.goal ? current.goal : current.project + const expectedAnchor = request.goal ?? request.project if ( current.$type !== COLLECTIONS.artifact || current.type !== type || current.request.uri !== request.uri || current.request.cid !== request.cid || - current.goal?.uri !== request.goal.uri || - current.goal?.cid !== request.goal.cid || + currentAnchor?.uri !== expectedAnchor.uri || + currentAnchor?.cid !== expectedAnchor.cid || JSON.stringify(current.links) !== JSON.stringify(links) || JSON.stringify(current.prev) !== JSON.stringify(prev) || JSON.stringify(current.criteria ?? []) !== JSON.stringify(envelope.criteria ?? []) || @@ -487,10 +505,25 @@ export class TurnSocketServer { } async #askQuestion(envelope: Extract): Promise { - const { request, client } = this.#context + const { request, client, questionAnchor } = this.#context + // The message lexicon requires exactly one goal|artifact anchor. A goal-scoped turn anchors to + // its own goal. A project-scoped turn has no goal of its own, so it uses the daemon-threaded + // questionAnchor (capture source goal, else the lowest-uri resolved basedOn artifact). A direct + // project turn without basedOn has neither — it cannot ask a question in v1. + let anchor: { goal: StrongRef } | { artifact: StrongRef } + if (request.goal) { + anchor = { goal: request.goal } + } else if (questionAnchor) { + anchor = questionAnchor + } else { + return { + ok: false, + error: 'a direct project-scoped turn without basedOn cannot ask questions in v1', + } + } const record: MessageRecord = { $type: COLLECTIONS.message, - goal: request.goal, + ...anchor, body: envelope.body, mentions: [], re: { uri: request.uri, cid: request.cid }, diff --git a/packages/daemon/src/turn.ts b/packages/daemon/src/turn.ts index e4203c8..756b18d 100644 --- a/packages/daemon/src/turn.ts +++ b/packages/daemon/src/turn.ts @@ -5,7 +5,7 @@ import type { LoadedActor } from './actors.js' import { checkoutCommit, checkoutRepo, writeBundle } from './bundle-writer.js' import { RADIAL_HOME_TMPFS, type ContainerOutputStream, type ContainerRunner, type ContainerSpec } from './container.js' import { composeBrief, type Harness } from './harness.js' -import { TurnSocketServer, implArtifactRkey, planArtifactRkey, type TurnMode, type TurnObservation, type TurnRequestContext } from './turn-socket.js' +import { TurnSocketServer, implArtifactRkey, planArtifactRkey, type TurnMode, type TurnObservation, type TurnRequestAnchor, type TurnRequestContext } from './turn-socket.js' /** The exact built-in artifact-type name that gets the implementation code path (rw /work and * git identity). Every other type dispatches as a plan-style turn. */ @@ -73,7 +73,8 @@ export function classifyTurnObservation(observation: TurnObservation): { export interface TurnInput { bundle: TurnBundle - request: { uri: string; cid: string; goal: StrongRef } + /** The request being fulfilled, anchored to its goal (goal-scoped) or project (project-scoped). */ + request: TurnRequestAnchor artifactType: ArtifactTypeRecord requestRecord: ArtifactRequestRecord actor: LoadedActor @@ -367,12 +368,25 @@ export async function runTurn(input: TurnInput, deps: TurnDeps): Promise a.uri.localeCompare(b.uri))[0] + if (lowest) questionAnchor = { artifact: { uri: lowest.uri, cid: lowest.cid } } + } + } const context: TurnRequestContext = { token, request: input.request, client: input.actor.client, mode, ...(isImpl && input.branch ? { implementation: { gitUrl: input.bundle.project.gitUrl, branch: input.branch, ...(input.prev ? { prev: input.prev } : {}) } } : {}), + ...(questionAnchor ? { questionAnchor } : {}), ...(deps.now ? { now: deps.now } : {}), } let sidecarSocket: string diff --git a/packages/daemon/test/bundle-writer.test.mjs b/packages/daemon/test/bundle-writer.test.mjs index 735ba56..ee201a3 100644 --- a/packages/daemon/test/bundle-writer.test.mjs +++ b/packages/daemon/test/bundle-writer.test.mjs @@ -67,6 +67,35 @@ it('writeBundle summary omits the "Under review" section for a non-review bundle assert.doesNotMatch(summary, /## Under review/) }) +it('writeBundle summary uses a project header for a goal-less (direct project-scoped) bundle', async () => { + const dir = await mkdtemp(join(tmpdir(), 'radial-bundle-nogoal-')) + const target = join(dir, 'turn-nogoal') + const { goal: _drop, ...projectBundle } = bundle + await writeBundle({ bundle: projectBundle, brief: '# adr brief\n', dir: target }) + const summary = await readFile(join(target, 'bundle.md'), 'utf8') + assert.match(summary, /# radial-ng \(project-scoped request\)/) + assert.doesNotMatch(summary, /# Ship the thing/) // the goal title header is gone +}) + +it('writeBundle summary renders the "## System artifacts" section (currentSystemArtifacts) and (none) fallback', async () => { + const withSystem = { + ...bundle, + currentSystemArtifacts: [ + { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/adr-1', cid: 'adr-cid', type: 'adr', body: 'the adr', links: {}, createdAt: '2026-01-01T00:05:00Z' }, + ], + } + const dirA = await mkdtemp(join(tmpdir(), 'radial-bundle-sys-')) + await writeBundle({ bundle: withSystem, brief: '# brief\n', dir: join(dirA, 'turn') }) + const summaryA = await readFile(join(dirA, 'turn', 'bundle.md'), 'utf8') + assert.match(summaryA, /## System artifacts/) + assert.match(summaryA, /- adr at:\/\/did:plc:agent\/com\.disnetdev\.radial\.artifact\/adr-1/) + + const dirB = await mkdtemp(join(tmpdir(), 'radial-bundle-nosys-')) + await writeBundle({ bundle, brief: '# brief\n', dir: join(dirB, 'turn') }) + const summaryB = await readFile(join(dirB, 'turn', 'bundle.md'), 'utf8') + assert.match(summaryB, /## System artifacts\n\(none\)/) +}) + it('assertGitUrlAllowed rejects file:// by default but allows https://, and allows file:// when opted in', () => { assert.throws(() => assertGitUrlAllowed('file:///tmp/repo', ['https']), /not allowed/) assert.doesNotThrow(() => assertGitUrlAllowed('https://example.test/repo.git', ['https'])) diff --git a/packages/daemon/test/turn-socket.test.mjs b/packages/daemon/test/turn-socket.test.mjs index 1eaf0dc..a976442 100644 --- a/packages/daemon/test/turn-socket.test.mjs +++ b/packages/daemon/test/turn-socket.test.mjs @@ -569,6 +569,152 @@ it('submitReview: adoption refuses an existing review- record with a mismatched }) }) +it('submitReview: rejects an over-long path (>2000) and a line < 1; writes no record', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-review-finding-validation') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { context: REVIEW_MODE }) + try { + const longPath = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [{ severity: 'info', body: 'x', path: 'p'.repeat(2001) }], + }) + assert.equal(longPath.ok, false) + + const zeroLine = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [{ severity: 'info', body: 'x', line: 0 }], + }) + assert.equal(zeroLine.ok, false) + + // A valid boundary (path exactly 2000, line exactly 1) is accepted. + const ok = await sendLine(socketPath, { + method: 'submitReview', + token: TOKEN, + verdict: 'approve', + findings: [{ severity: 'info', body: 'x', path: 'p'.repeat(2000), line: 1 }], + }) + assert.equal(ok.ok, true) + } finally { + await server.close() + } + }) +}) + +// --- Project-scoped (system artifact) turns ------------------------------- + +const PROJECT = { uri: 'at://did:plc:human/com.disnetdev.radial.project/proj1', cid: 'projcid' } +const PROJECT_REQUEST = { + uri: 'at://did:plc:human/com.disnetdev.radial.artifactRequest/adr-req', + cid: 'adr-req-cid', + project: PROJECT, +} +const SOURCE_GOAL = { uri: 'at://did:plc:human/com.disnetdev.radial.goal/src', cid: 'srcgoalcid' } +const BASED_ON_ARTIFACT = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/aaa', cid: 'aaacid' } + +it('project-scoped submitArtifact writes an artifact anchored to the project (no goal)', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-adr') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { + context: { request: PROJECT_REQUEST, mode: { kind: 'artifact', type: 'adr' } }, + }) + try { + const response = await sendLine(socketPath, { method: 'submitArtifact', token: TOKEN, body: 'the adr' }) + assert.equal(response.ok, true) + const record = [...pds.records.values()].find((r) => r.value.$type === COLLECTIONS.artifact).value + assert.deepEqual(record.project, PROJECT) + assert.equal(record.goal, undefined) + assert.equal(record.type, 'adr') + assert.equal(record.body, 'the adr') + } finally { + await server.close() + } + }) +}) + +it('project-scoped submitArtifact adopts on retry, comparing the project anchor', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-adr-adopt') + const client = await makeClient(pds) + const context = { request: PROJECT_REQUEST, mode: { kind: 'artifact', type: 'adr' } } + + const first = await startServer(directory, client, { context }) + const firstResponse = await sendLine(first.socketPath, { method: 'submitArtifact', token: TOKEN, body: 'adr body' }) + await first.server.close() + assert.equal(firstResponse.ok, true) + + const second = await startServer(directory, client, { context }) + const secondResponse = await sendLine(second.socketPath, { method: 'submitArtifact', token: TOKEN, body: 'adr body' }) + await second.server.close() + assert.equal(secondResponse.ok, true) + assert.deepEqual(secondResponse.ref, firstResponse.ref) + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.artifact) + assert.equal(stored.length, 1) + }) +}) + +it('project-scoped askQuestion precedence: capture source goal anchor', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-adr-q1') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { + context: { request: PROJECT_REQUEST, mode: { kind: 'artifact', type: 'adr' }, questionAnchor: { goal: SOURCE_GOAL } }, + }) + try { + const response = await sendLine(socketPath, { method: 'askQuestion', token: TOKEN, body: 'which format?' }) + assert.equal(response.ok, true) + const record = [...pds.records.values()].find((r) => r.value.$type === COLLECTIONS.message).value + assert.deepEqual(record.goal, SOURCE_GOAL) // anchored to the capture source goal + assert.equal(record.artifact, undefined) + assert.deepEqual(record.re, { uri: PROJECT_REQUEST.uri, cid: PROJECT_REQUEST.cid }) + } finally { + await server.close() + } + }) +}) + +it('project-scoped askQuestion precedence: falls back to the basedOn artifact anchor', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-adr-q2') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { + context: { request: PROJECT_REQUEST, mode: { kind: 'artifact', type: 'adr' }, questionAnchor: { artifact: BASED_ON_ARTIFACT } }, + }) + try { + const response = await sendLine(socketPath, { method: 'askQuestion', token: TOKEN, body: 'which format?' }) + assert.equal(response.ok, true) + const record = [...pds.records.values()].find((r) => r.value.$type === COLLECTIONS.message).value + assert.deepEqual(record.artifact, BASED_ON_ARTIFACT) + assert.equal(record.goal, undefined) + } finally { + await server.close() + } + }) +}) + +it('project-scoped askQuestion with no anchor is rejected with a clear error and writes no record', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-adr-q3') + const client = await makeClient(pds) + const { server, socketPath } = await startServer(directory, client, { + context: { request: PROJECT_REQUEST, mode: { kind: 'artifact', type: 'adr' } }, // no questionAnchor + }) + try { + const response = await sendLine(socketPath, { method: 'askQuestion', token: TOKEN, body: 'which format?' }) + assert.equal(response.ok, false) + assert.match(response.error, /project-scoped turn without basedOn cannot ask questions/) + assert.equal(pds.records.size, 0) + } finally { + await server.close() + } + }) +}) + it('submitReview: two concurrent submits on one review turn land exactly one record (reservation)', async () => { await withTempDir(async (directory) => { const pds = new LocalPds('did:plc:agent-review-concurrent') diff --git a/packages/daemon/test/turn.test.mjs b/packages/daemon/test/turn.test.mjs index f767894..dcec8cc 100644 --- a/packages/daemon/test/turn.test.mjs +++ b/packages/daemon/test/turn.test.mjs @@ -563,6 +563,64 @@ it('review crashed: a review turn producing no verdict or question is crashed', }) }) +// --- Project-scoped (system artifact) turns ------------------------------- + +const PROJECT = { uri: BUNDLE.project.uri, cid: BUNDLE.project.cid } +const ADR_ARTIFACT_TYPE = { ...ARTIFACT_TYPE, name: 'adr', brief: 'Distill an ADR.', scope: 'project' } +const ADR_REQUEST_RECORD = { + $type: COLLECTIONS.artifactRequest, + project: PROJECT, + type: 'adr', + basedOn: [], + assignee: 'did:plc:agent', + createdAt: '2026-01-01T00:03:00Z', +} +// A project-scoped bundle has no goal of its own (a direct request). +const ADR_BUNDLE = (() => { + const { goal: _drop, ...rest } = BUNDLE + return { ...rest, request: { ...BUNDLE.request, type: 'adr' } } +})() + +it('project-scoped turn: default-branch read-only checkout and a project-anchored artifact', async () => { + const { pds, actor } = await makeActor('did:plc:agent-adr-turn') + await withRunDir(async (runDir) => { + let checkoutRef + const trackingCheckout = async ({ ref, dest }) => { + checkoutRef = ref + await mkdir(dest, { recursive: true }) + return { path: dest, commit: 'deadbeef' } + } + const runner = new FakeContainerRunner(async (spec) => { + // Not an implementation turn: /work is mounted READ-ONLY. + assert.equal(spec.mounts.find((m) => m.target === '/work').readOnly, true) + const response = await sendLine(hostSocketPath(spec), { + method: 'submitArtifact', + token: spec.env.RADIAL_TURN_TOKEN, + body: 'the ADR', + }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }) + const result = await runTurn( + baseInput(runDir, { + actor, + bundle: ADR_BUNDLE, + request: { uri: BUNDLE.request.uri, cid: BUNDLE.request.cid, project: PROJECT }, + artifactType: ADR_ARTIFACT_TYPE, + requestRecord: ADR_REQUEST_RECORD, + }), + { runner, harness: new ClaudeCodeHarness(), checkout: trackingCheckout }, + ) + assert.equal(result.outcome, 'fulfilled') + // Checkout was the project default branch (no branch/commit pin for a plan-style project turn). + assert.equal(checkoutRef, 'main') + const record = [...pds.records.values()].find((r) => r.value.$type === COLLECTIONS.artifact).value + assert.deepEqual(record.project, PROJECT) + assert.equal(record.goal, undefined) + assert.equal(record.type, 'adr') + }) +}) + it('classifyTurnObservation: an observation with BOTH an artifact and a review is crashed (never a silent preference)', () => { const both = classifyTurnObservation({ artifact: { uri: 'at://a/x/1', cid: 'c1' }, -- knotmirror 0.0.1 From ec33aa905801a597c4014839cd052e1c74fb0eb3 Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 14:53:45 -0700 Subject: [PATCH 12/13] daemon: dispatch project-scoped requests + project-scoped review; registry/author fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extract the per-request dispatch gate into a target-agnostic helper and run it over index.projects as well as index.goals: registry types with scope 'project' (adr, architecture) and review requests whose subject is a project-scoped artifact now dispatch (integration item d), never computing implementation predecessors. The turn context anchor is built from request.goal OR request.project, and Dispatchable.goalView becomes target: GoalView | ProjectView. Also fold in two fixes on this file: - Registry Map is now first-wins on a duplicate type name, matching the materializer's earliest-wins typeByName (a plain Map was last-wins — daemon and core must agree). - The request-author gate accepts any active member, not only humans: the daemon writes auto-review requests under an agent identity and materializers don't police request authorship (design §3/§7), so agent-authored requests must not sit open forever. Awaiting-input gates now scan the space-global message set (mirrors the core fix) so a capture turn's source-goal-anchored question blocks redispatch of its project request. Tests: adr dispatch from the project loop, capture dispatch carrying the source goal, project-scoped review dispatch, agent-authored review dispatch, duplicate-name first-wins, and an E2E where a landed adr shows fulfilled + in currentSystemArtifacts and then rides in a subsequent goal turn's bundle (Phase 5 long-term-memory loop). Co-Authored-By: Claude Fable 5 --- packages/daemon/src/dispatch.ts | 359 ++++++++++++++----------- packages/daemon/test/dispatch.test.mjs | 242 ++++++++++++++++- 2 files changed, 437 insertions(+), 164 deletions(-) diff --git a/packages/daemon/src/dispatch.ts b/packages/daemon/src/dispatch.ts index 5652dd8..481228e 100644 --- a/packages/daemon/src/dispatch.ts +++ b/packages/daemon/src/dispatch.ts @@ -9,13 +9,14 @@ import { type IndexedRecord, type MaterializedIndex, type MessageRecord, + type ProjectView, type StrongRef, type TurnBundle, } from '@radial/core' import type { ActorRegistry, LoadedActor } from './actors.js' import { parseGitHubPullUrl, parseGitHubRepo, type ForgeAdapter } from './forge.js' import type { TurnLedger } from './ledger.js' -import { implBranchName, planArtifactRkey } from './turn-socket.js' +import { implBranchName, planArtifactRkey, type TurnRequestAnchor } from './turn-socket.js' import { IMPLEMENTATION_TYPE, REVIEW_TYPE, REVIEW_TYPE_NAME, turnContainerLabel, type TurnInput, type TurnResult } from './turn.js' /** A resolved v2 predecessor for an implementation request: the exact prior artifact plus its @@ -34,7 +35,9 @@ export interface ImplementationDispatch { } export interface Dispatchable { - goalView: GoalView + /** The owning view — a GoalView for a goal-scoped request, a ProjectView for a project-scoped + * (system-artifact) request. Discriminate by request.value.goal/project presence when needed. */ + target: GoalView | ProjectView request: IndexedRecord actor: LoadedActor artifactType: ArtifactTypeRecord @@ -118,14 +121,16 @@ function resolveImplementationDispatch( } /** - * The pure dispatch gate: which open goal-scoped requests are ready to hand to a container right now. - * Generalized from plan-only to any registry artifact type the actor produces: a request is selected - * iff its `type` resolves to a registered, goal-scoped, non-`review` artifact type; it is - * human-authored; it resolves to an actor that produces that type (its named assignee, or when - * unassigned any active agent member of the space producing the type, chosen deterministically by - * DID); it is not blocked on a question; and the ledger says it is eligible. Only the exact built-in - * type name `implementation` carries `implementation` predecessor data; every other type dispatches - * as a plan-style turn. Deterministically ordered by request uri. + * The pure dispatch gate: which open requests are ready to hand to a container right now. Generalized + * across scopes — goal-scoped requests iterate under goals, project-scoped (system-artifact) requests + * under projects — and across types: a request is selected iff its `type` resolves to a registered + * artifact type of the OWNING scope (or is a `review` whose subject resolves under the same target); + * it is authored by any active space member (design §3: materializers don't police request + * authorship — auto-review requests are agent-authored); it resolves to an actor that produces that + * type (its named assignee, or when unassigned any active agent member producing the type, chosen + * deterministically by DID); it is not blocked on a question; and the ledger says it is eligible. + * Only the exact built-in type name `implementation` (always goal-scoped) carries predecessor data; + * project-scoped types never compute implementation predecessors. Deterministically ordered by uri. */ export function selectDispatchable( index: MaterializedIndex, @@ -133,159 +138,201 @@ export function selectDispatchable( ledger: TurnLedger, now?: string, /** Diagnostic hook: called for each request that resolves to a dispatchable type but is filtered - * out, with the gate that rejected it. Requests whose type isn't a registered goal-scoped - * non-review type are skipped silently (never reported). */ + * out, with the gate that rejected it. Requests whose type isn't a registered type of the owning + * scope (nor a resolvable review) are skipped silently (never reported). */ onReject?: (requestUri: string, reason: string) => void, ): Dispatchable[] { - const registry = new Map(index.artifactTypes.map((type) => [type.value.name, type.value])) + // First-wins on a duplicate type name, matching the materializer's earliest-wins `typeByName` + // (index.artifactTypes is sorted by (createdAt, uri), so the FIRST entry is the earliest). A plain + // `new Map(entries)` would be last-wins — daemon and core must agree on which record a name binds. + const registry = new Map() + for (const type of index.artifactTypes) { + if (!registry.has(type.value.name)) registry.set(type.value.name, type.value) + } const allArtifacts: Array> = [ ...index.goals.flatMap((view) => view.artifacts), ...index.projects.flatMap((view) => view.artifacts), ] const artifactByRef = new Map(allArtifacts.map((artifact) => [refKey(artifact), artifact])) + // Awaiting-input is checked against the SPACE-GLOBAL trusted messages: a project-scoped capture + // turn's question is anchored to the source goal (a different view than the request's), so a + // per-view message scan would miss it and the request would be redispatched over the open question. + const allMessages: Array> = [ + ...index.goals.flatMap((view) => view.messages), + ...index.projects.flatMap((view) => view.messages), + ] - const results: Dispatchable[] = [] - for (const goalView of index.goals) { - // A closed or archived goal is set aside: agents never pick up its requests. (Closure is the - // author's own `closed` edit; archival is any member's reversible `archiveGoal` record.) - if (goalView.archived || goalView.target.value.closed) continue - for (const request of goalView.openRequests) { - const type = request.value.type - - // Resolve the artifact type this request dispatches with, and (for review requests) the - // subject under review. `review` is deliberately NOT registry data — it must never hit - // registry.get; it uses the synthetic built-in REVIEW_TYPE. A review request only materializes - // when its subject resolves under the same target (materializer.ts), so the subject resolution - // here always succeeds for a materialized review request; the guards are defensive. - let artifactType: ArtifactTypeRecord - let review: { subject: StrongRef; commit?: string } | undefined - if (type === REVIEW_TYPE_NAME) { - const subject = request.value.subject - if (!subject) continue - const subjectArtifact = artifactByRef.get(refKey(subject)) - if (!subjectArtifact) continue - artifactType = REVIEW_TYPE - review = { - subject, - ...(subjectArtifact.value.links?.commit ? { commit: subjectArtifact.value.links.commit } : {}), - } - } else { - const registered = registry.get(type) - // Silently skip anything that isn't a dispatchable goal-scoped artifact type: no such - // registered type, or a project-scoped type (dispatched elsewhere). - if (!registered || registered.scope !== 'goal') continue - artifactType = registered - } - - const author = index.members.find( - (member) => member.did === request.did && member.active && member.kind === 'human', - ) - if (!author) { - onReject?.(request.uri, `author ${request.did} is not an active human member of the space`) - continue + // The per-request gate, target-agnostic: it only reads .openRequests (caller-iterated), .messages + // (via allMessages), .awaitingInput and .target.uri — all present on both view types. `expectedScope` + // is the owning view's scope; the implementation-predecessor branch is gated to goal scope. + const evaluate = ( + view: GoalView | ProjectView, + request: IndexedRecord, + expectedScope: 'goal' | 'project', + ): Dispatchable | undefined => { + const type = request.value.type + + // Resolve the artifact type this request dispatches with, and (for review requests) the subject + // under review. `review` is deliberately NOT registry data — it never hits registry.get; it uses + // the synthetic built-in REVIEW_TYPE. A review request only materializes when its subject resolves + // under the same target (materializer.ts), so subject resolution here always succeeds for a + // materialized review request (the guards are defensive) — and a project-scoped subject makes the + // review dispatch from the project loop, no separate branch needed. + let artifactType: ArtifactTypeRecord + let review: { subject: StrongRef; commit?: string } | undefined + if (type === REVIEW_TYPE_NAME) { + const subject = request.value.subject + if (!subject) return undefined + const subjectArtifact = artifactByRef.get(refKey(subject)) + if (!subjectArtifact) return undefined + artifactType = REVIEW_TYPE + review = { + subject, + ...(subjectArtifact.value.links?.commit ? { commit: subjectArtifact.value.links.commit } : {}), } - - // Assigned → that agent handles it. Unassigned → open for any active agent member producing - // this type, chosen deterministically by DID (see the claims note; safe for one daemon). - const assignee = request.value.assignee - let actor: LoadedActor | undefined - if (assignee) { - const assigneeMember = index.members.find( - (member) => member.did === assignee && member.active && member.kind === 'agent', + } else { + const registered = registry.get(type) + // No such registered type → silent skip (not reported). A registered type whose scope does not + // match the owning view is a can't-happen (the materializer files a request only under a view of + // its type's scope); log it defensively if it ever occurs rather than dispatch it cross-scope. + if (!registered) return undefined + if (registered.scope !== expectedScope) { + onReject?.( + request.uri, + `type '${type}' is ${registered.scope}-scoped but the request is anchored to a ${expectedScope} — not dispatching`, ) - if (!assigneeMember) { - onReject?.(request.uri, `assignee ${assignee} is not an active agent member of the space`) - continue - } - if (!actors.byDid.has(assignee)) { - onReject?.(request.uri, `no loaded actor for assignee ${assignee} (profile not initialized in this config?)`) - continue - } - actor = actors.select(assignee, type) - if (!actor) { - onReject?.(request.uri, `loaded actor for ${assignee} does not produce '${type}' artifacts`) - continue - } - } else { - actor = [...index.members] - .filter((member) => member.active && member.kind === 'agent') - .sort((a, b) => a.did.localeCompare(b.did)) - .map((member) => actors.select(member.did, type)) - .find((candidate): candidate is LoadedActor => Boolean(candidate)) - if (!actor) { - onReject?.(request.uri, `unassigned request and no active agent member can produce a '${type}' artifact`) - continue - } + return undefined } + artifactType = registered + } - // Close the awaiting_input stale-index race: a ledger row can flip to `awaiting_input` (and - // become `eligible()`) before the next index snapshot has ingested the SELECTED actor's - // question. Match the question author against the selected actor's DID (NOT `assignee`, which - // is undefined for unassigned requests — the pre-existing bug this fixes: an unassigned - // request's answered question could never re-enable dispatch because the guard matched a - // question author of `undefined`). If the index hasn't ingested the actor's question yet, skip - // rather than redispatch ahead of it; the `awaitingInput` check below still blocks an ingested - // but unanswered question. - if (ledger.get(request.uri)?.state === 'awaiting_input') { - const questionInIndex = goalView.messages.some( - (m) => - m.did === actor.did && - m.value.re && - m.value.re.uri === request.uri && - m.value.re.cid === request.cid && - m.value.declines !== true, - ) - if (!questionInIndex) { - onReject?.(request.uri, 'awaiting_input: selected actor question not yet ingested into the index (stale index)') - continue - } + // Any active member may author a request (human or agent): design §3/§7 — the daemon writes + // auto-review requests under one of its agent identities, and materializers don't police request + // authorship. The human-initiation norm is a UI convention, not a dispatch gate. + const author = index.members.find((member) => member.did === request.did && member.active) + if (!author) { + onReject?.(request.uri, `author ${request.did} is not an active member of the space`) + return undefined + } + + // Assigned → that agent handles it. Unassigned → open for any active agent member producing this + // type, chosen deterministically by DID (see the claims note; safe for one daemon). + const assignee = request.value.assignee + let actor: LoadedActor | undefined + if (assignee) { + const assigneeMember = index.members.find( + (member) => member.did === assignee && member.active && member.kind === 'agent', + ) + if (!assigneeMember) { + onReject?.(request.uri, `assignee ${assignee} is not an active agent member of the space`) + return undefined } - if (goalView.awaitingInput.includes(request.uri)) { - onReject?.(request.uri, 'blocked awaiting human input (unanswered assignee question)') - continue + if (!actors.byDid.has(assignee)) { + onReject?.(request.uri, `no loaded actor for assignee ${assignee} (profile not initialized in this config?)`) + return undefined } - // `goalView.awaitingInput` only tracks ASSIGNED requests (materializer keys on `assignee`), so - // for an unassigned request the daemon must itself detect an unanswered question from the - // (deterministically) selected actor and hold off — otherwise it would redispatch on top of a - // pending question (finding 9). Redundant-but-harmless for assigned requests. - if (hasUnansweredQuestion(goalView.messages, request, actor.did)) { - onReject?.(request.uri, 'blocked awaiting human input (unanswered question from the selected actor)') - continue + actor = actors.select(assignee, type) + if (!actor) { + onReject?.(request.uri, `loaded actor for ${assignee} does not produce '${type}' artifacts`) + return undefined } - if (!ledger.eligible(request.uri, now)) { - onReject?.(request.uri, `ledger: not eligible (state ${ledger.get(request.uri)?.state ?? 'unknown'})`) - continue + } else { + actor = [...index.members] + .filter((member) => member.active && member.kind === 'agent') + .sort((a, b) => a.did.localeCompare(b.did)) + .map((member) => actors.select(member.did, type)) + .find((candidate): candidate is LoadedActor => Boolean(candidate)) + if (!actor) { + onReject?.(request.uri, `unassigned request and no active agent member can produce a '${type}' artifact`) + return undefined } + } - // Implementation-only: resolve the v2 predecessor from the direct basedOn. An unresolved - // basedOn ref is a stale-index skip (retry later), never a permanent reject. - let implementation: ImplementationDispatch | undefined - if (type === IMPLEMENTATION_TYPE) { - const { dispatch, hasUnresolvedBasedOn } = resolveImplementationDispatch(index, request, goalView.target.uri) - if (hasUnresolvedBasedOn && !dispatch.ambiguous) { - onReject?.(request.uri, 'implementation request has an unresolved basedOn ref (stale index)') - continue - } - implementation = dispatch + // Close the awaiting_input stale-index race: a ledger row can flip to `awaiting_input` (and become + // `eligible()`) before the next index snapshot has ingested the SELECTED actor's question. Match + // the question author against the selected actor's DID (NOT `assignee`, which is undefined for + // unassigned requests). Scanned over allMessages so a capture turn's source-goal-anchored question + // still counts. If the index hasn't ingested the actor's question yet, skip rather than redispatch + // ahead of it; the `awaitingInput` check below still blocks an ingested but unanswered question. + if (ledger.get(request.uri)?.state === 'awaiting_input') { + const questionInIndex = allMessages.some( + (m) => + m.did === actor.did && + m.value.re && + m.value.re.uri === request.uri && + m.value.re.cid === request.cid && + m.value.declines !== true, + ) + if (!questionInIndex) { + onReject?.(request.uri, 'awaiting_input: selected actor question not yet ingested into the index (stale index)') + return undefined } + } + if (view.awaitingInput.includes(request.uri)) { + onReject?.(request.uri, 'blocked awaiting human input (unanswered assignee question)') + return undefined + } + // `view.awaitingInput` only tracks ASSIGNED requests (materializer keys on `assignee`), so for an + // unassigned request the daemon must itself detect an unanswered question from the + // (deterministically) selected actor and hold off — otherwise it would redispatch on top of a + // pending question (finding 9). Redundant-but-harmless for assigned requests. + if (hasUnansweredQuestion(allMessages, request, actor.did)) { + onReject?.(request.uri, 'blocked awaiting human input (unanswered question from the selected actor)') + return undefined + } + if (!ledger.eligible(request.uri, now)) { + onReject?.(request.uri, `ledger: not eligible (state ${ledger.get(request.uri)?.state ?? 'unknown'})`) + return undefined + } - let bundle: TurnBundle - try { - bundle = buildTurnBundle(index, request.uri, request.cid) - } catch (error) { - onReject?.(request.uri, `failed to build turn bundle: ${error instanceof Error ? error.message : error}`) - continue + // Implementation-only (always goal-scoped): resolve the v2 predecessor from the direct basedOn. An + // unresolved basedOn ref is a stale-index skip (retry later), never a permanent reject. Project + // types never reach this branch. + let implementation: ImplementationDispatch | undefined + if (expectedScope === 'goal' && type === IMPLEMENTATION_TYPE) { + const { dispatch, hasUnresolvedBasedOn } = resolveImplementationDispatch(index, request, view.target.uri) + if (hasUnresolvedBasedOn && !dispatch.ambiguous) { + onReject?.(request.uri, 'implementation request has an unresolved basedOn ref (stale index)') + return undefined } + implementation = dispatch + } - results.push({ - goalView, - request, - actor, - artifactType, - bundle, - ...(implementation ? { implementation } : {}), - ...(review ? { review } : {}), - }) + let bundle: TurnBundle + try { + bundle = buildTurnBundle(index, request.uri, request.cid) + } catch (error) { + onReject?.(request.uri, `failed to build turn bundle: ${error instanceof Error ? error.message : error}`) + return undefined + } + + return { + target: view, + request, + actor, + artifactType, + bundle, + ...(implementation ? { implementation } : {}), + ...(review ? { review } : {}), + } + } + + const results: Dispatchable[] = [] + for (const goalView of index.goals) { + // A closed or archived goal is set aside: agents never pick up its requests. (Closure is the + // author's own `closed` edit; archival is any member's reversible `archiveGoal` record.) + if (goalView.archived || goalView.target.value.closed) continue + for (const request of goalView.openRequests) { + const dispatchable = evaluate(goalView, request, 'goal') + if (dispatchable) results.push(dispatchable) + } + } + // Project-scoped (system-artifact) requests: registry types with scope 'project' (adr, architecture) + // and review requests whose subject is a project-scoped artifact. Same gate; never implementation. + for (const projectView of index.projects) { + for (const request of projectView.openRequests) { + const dispatchable = evaluate(projectView, request, 'project') + if (dispatchable) results.push(dispatchable) } } return results.sort((a, b) => a.request.uri.localeCompare(b.request.uri)) @@ -369,14 +416,18 @@ export class TurnDispatcher { continue } - const goal = item.request.value.goal - if (!goal) continue // goal-scoped guard; defensive against a malformed record - const cid = item.request.cid - - // A human-error ambiguous implementation request: post an explanation on the request and give - // up (a `turn reset` re-enables it once fixed). No container runs. - if (item.implementation?.ambiguous) { + // Exactly one anchor (goal- or project-scoped), per the lexicon's exactOne(goal, project). + const goal = item.request.value.goal + const project = item.request.value.project + if (!goal && !project) continue // defensive against a malformed record + const anchor: TurnRequestAnchor = goal + ? { uri, cid, goal } + : { uri, cid, project: project as StrongRef } + + // A human-error ambiguous implementation request (always goal-scoped): post an explanation on + // the request and give up (a `turn reset` re-enables it once fixed). No container runs. + if (item.implementation?.ambiguous && goal) { const label = `radial.reject.${uri.slice(-16)}` const promise = this.#rejectAmbiguous(item, goal) .catch((error: unknown) => @@ -392,7 +443,7 @@ export class TurnDispatcher { this.#deps.ledger.markRunning(uri, cid, { containerLabel: label, checkoutPath: join(runDir, 'checkout') }) this.#deps.log?.(`dispatching turn ${uri} (label ${label})`) - const promise = this.#launch(item, { uri, cid, goal, runDir, label }) + const promise = this.#launch(item, { anchor, runDir, label }) .finally(() => this.#inFlight.delete(uri)) this.#inFlight.set(uri, { promise, label }) } @@ -401,9 +452,11 @@ export class TurnDispatcher { /** Prepare and run one turn, then settle the ledger. */ async #launch( item: Dispatchable, - ctx: { uri: string; cid: string; goal: StrongRef; runDir: string; label: string }, + ctx: { anchor: TurnRequestAnchor; runDir: string; label: string }, ): Promise { - const { uri, cid, goal, runDir, label } = ctx + const { anchor, runDir, label } = ctx + const uri = anchor.uri + const cid = anchor.cid const isImpl = item.artifactType.name === IMPLEMENTATION_TYPE let checkoutRef: string | undefined @@ -447,7 +500,7 @@ export class TurnDispatcher { const turnInput: TurnInput = { bundle: item.bundle, - request: { uri, cid, goal }, + request: anchor, artifactType: item.artifactType, requestRecord: item.request.value, actor: item.actor, diff --git a/packages/daemon/test/dispatch.test.mjs b/packages/daemon/test/dispatch.test.mjs index 5bc51ea..8235741 100644 --- a/packages/daemon/test/dispatch.test.mjs +++ b/packages/daemon/test/dispatch.test.mjs @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { it } from 'node:test' import { createSession, CredentialClient } from '../../atproto/dist/index.js' -import { COLLECTIONS, MemoryRecordStore, materialize } from '../../core/dist/index.js' +import { COLLECTIONS, MemoryRecordStore, buildTurnBundle, materialize } from '../../core/dist/index.js' import { LocalPds } from '../../atproto/test/local-pds.mjs' import { ClaudeCodeHarness, @@ -261,14 +261,16 @@ it('rejects an unassigned plan request when no active agent member can produce a ledger.close() }) -it('rejects an agent-authored plan request (author must be an active human member)', () => { - const { records } = buildScenario() - // Re-author the request as the agent itself. +it('dispatches an agent-authored request (materializers do not police request authorship, design §3)', () => { + const { records, request } = buildScenario() + // Re-author the request as the agent itself. The daemon writes auto-review requests under one of + // its agent identities (design §3/§7), so any active member — agent or human — may author a + // dispatchable request; the human-initiation norm is a UI convention, not a dispatch gate. const mutated = records.map((r) => (r.collection === COLLECTIONS.artifactRequest ? { ...r, did: AGENT } : r)) const index = materialize(store(mutated), { spaceUri: SPACE_URI }) const ledger = new TurnLedger() const actors = registryFor([actorFor(AGENT)]) - assert.deepEqual(selectDispatchable(index, actors, ledger), []) + assert.deepEqual(uris(selectDispatchable(index, actors, ledger)), [request.uri]) ledger.close() }) @@ -296,7 +298,7 @@ it('generalization: dispatches a goal-scoped NON-plan registered type when an ac // A valid review scenario: the base plan request is fulfilled by an artifact (so it drops out of the // work queue), and a review request pins that artifact as its subject. `review` is never registry // data — a review request materializes purely from its resolving same-target subject. -function withReviewRequest({ assignee = AGENT, subjectLinks = { commit: 'a'.repeat(40) } } = {}) { +function withReviewRequest({ assignee = AGENT, subjectLinks = { commit: 'a'.repeat(40) }, author = HUMAN } = {}) { const base = buildScenario() const artifact = mk(AGENT, COLLECTIONS.artifact, 'plan-art', 'cid-plan-art', { $type: COLLECTIONS.artifact, @@ -307,7 +309,7 @@ function withReviewRequest({ assignee = AGENT, subjectLinks = { commit: 'a'.repe links: subjectLinks, createdAt: '2026-01-01T00:04:00Z', }) - const reviewReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'review-req', 'cid-review-req', { + const reviewReq = mk(author, COLLECTIONS.artifactRequest, 'review-req', 'cid-review-req', { $type: COLLECTIONS.artifactRequest, goal: ref(base.goal), type: 'review', @@ -319,6 +321,62 @@ function withReviewRequest({ assignee = AGENT, subjectLinks = { commit: 'a'.repe return { ...base, artifact, reviewReq, records: [...base.records, artifact, reviewReq] } } +// A project-scoped CAPTURE request: the base plan request is fulfilled by a goal plan artifact, and a +// project-scoped `adr` request lists that artifact in basedOn (distil-from-goal-context, design §8). +function withCaptureRequest() { + const base = buildScenario() + const planArt = mk(AGENT, COLLECTIONS.artifact, 'plan-art', 'cid-plan-art', { + $type: COLLECTIONS.artifact, + request: ref(base.request), + goal: ref(base.goal), + type: 'plan', + body: 'the plan', + links: {}, + createdAt: '2026-01-01T00:04:00Z', + }) + const captureReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'capture-req', 'cid-capture-req', { + $type: COLLECTIONS.artifactRequest, + project: ref(base.project), + type: 'adr', + basedOn: [ref(planArt)], + assignee: AGENT, + createdAt: '2026-01-01T00:05:00Z', + }) + return { ...base, planArt, captureReq, records: [...base.records, planArt, captureReq] } +} + +// A project-scoped REVIEW request whose subject is a project-scoped `adr` artifact. +function withProjectReviewRequest({ subjectLinks = {} } = {}) { + const base = buildScenario() + const adrReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'adr-req', 'cid-adr-req', { + $type: COLLECTIONS.artifactRequest, + project: ref(base.project), + type: 'adr', + basedOn: [], + assignee: AGENT, + createdAt: '2026-01-01T00:03:30Z', + }) + const adrArt = mk(AGENT, COLLECTIONS.artifact, 'adr-art', 'cid-adr-art', { + $type: COLLECTIONS.artifact, + request: ref(adrReq), + project: ref(base.project), + type: 'adr', + body: 'the adr', + links: subjectLinks, + createdAt: '2026-01-01T00:04:00Z', + }) + const reviewReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'preview-req', 'cid-preview-req', { + $type: COLLECTIONS.artifactRequest, + project: ref(base.project), + type: 'review', + subject: ref(adrArt), + basedOn: [], + assignee: AGENT, + createdAt: '2026-01-01T00:05:00Z', + }) + return { ...base, adrReq, adrArt, reviewReq, records: [...base.records, adrReq, adrArt, reviewReq] } +} + it('dispatches a review-type request to a review-producing actor, pinning the checkout to the subject commit', () => { const { records, reviewReq } = withReviewRequest() const index = materialize(store(records), { spaceUri: SPACE_URI }) @@ -385,6 +443,75 @@ it('does not dispatch a review request to an actor that does not produce reviews ledger.close() }) +it('dispatches a project-scoped CAPTURE request; its bundle carries the source goal', () => { + const { records, captureReq, goal, project } = withCaptureRequest() + const index = materialize(store(records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT, ['plan', 'adr'])]) + const result = selectDispatchable(index, actors, ledger) + // The base plan request is fulfilled by its artifact; only the capture request dispatches. + assert.deepEqual(uris(result), [captureReq.uri]) + const cap = result[0] + assert.equal(cap.artifactType.name, 'adr') + assert.equal(cap.target.target.uri, project.uri) // the owning view is the ProjectView + assert.ok(cap.bundle.goal) + assert.equal(cap.bundle.goal.uri, goal.uri) // the capture source goal, reached through basedOn + assert.equal(cap.implementation, undefined) + ledger.close() +}) + +it('dispatches a project-scoped REVIEW request whose subject is a project-scoped artifact (integration item d)', () => { + const { records, reviewReq, adrArt, project } = withProjectReviewRequest() + const index = materialize(store(records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT, ['plan', 'adr', 'review'])]) + const result = selectDispatchable(index, actors, ledger) + const review = result.find((d) => d.request.uri === reviewReq.uri) + assert.ok(review, 'the project-scoped review request should dispatch') + assert.equal(review.artifactType.name, 'review') + assert.equal(review.target.target.uri, project.uri) // dispatched from the project loop + assert.deepEqual(review.review.subject, reviewReq.value.subject) + assert.ok(review.bundle.subject) + assert.equal(review.bundle.subject.uri, adrArt.uri) + assert.equal(review.bundle.goal, undefined) // a project-scoped review has no goal + ledger.close() +}) + +it('dispatches a review request authored by an agent-kind member with a valid assignee (auto-review is agent-authored, §3/§7)', () => { + const base = withReviewRequest({ author: AGENT }) + const index = materialize(store(base.records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT, ['plan', 'review'])]) + const result = selectDispatchable(index, actors, ledger) + assert.ok( + result.some((d) => d.request.uri === base.reviewReq.uri), + 'an agent-authored review request must not sit open forever', + ) + ledger.close() +}) + +it('registry is first-wins on a duplicate type name (agrees with the materializer earliest-wins)', () => { + // A LATER duplicate `plan` type record. The materializer resolves types earliest-wins; the daemon + // registry must too, or they disagree on what `plan` means. First-wins → the EARLIEST record wins. + const laterDuplicate = mk(ROOT, COLLECTIONS.artifactType, 'type-plan-dup', 'cid-type-plan-dup', { + $type: COLLECTIONS.artifactType, + space: { uri: SPACE_URI, cid: 'cid-space' }, + name: 'plan', + brief: 'LATER DUPLICATE — must not win.', + outputSpec: { format: 'markdown', description: 'dup' }, + scope: 'goal', + createdAt: '2026-06-01T00:00:00Z', // later than the base plan type (00:00:10 on 2026-01-01) + }) + const { records, request } = buildScenario({ extra: [laterDuplicate] }) + const index = materialize(store(records), { spaceUri: SPACE_URI }) + const ledger = new TurnLedger() + const actors = registryFor([actorFor(AGENT)]) + const result = selectDispatchable(index, actors, ledger) + assert.deepEqual(uris(result), [request.uri]) + assert.equal(result[0].artifactType.brief, 'Write a concrete plan.') // the earliest record won + ledger.close() +}) + it('skips a request whose type is not a registered artifact type', () => { const { records } = buildScenario({ requestOverrides: { type: 'nonesuch' } }) const index = materialize(store(records), { spaceUri: SPACE_URI }) @@ -394,8 +521,8 @@ it('skips a request whose type is not a registered artifact type', () => { ledger.close() }) -it('never considers a project-scoped request (selectDispatchable only walks goals)', () => { - const { records, project } = buildScenario() +it('dispatches a project-scoped request from the project loop (adr → project-view target, bundle built)', () => { + const { records, project, request } = buildScenario() const projectRequest = mk(HUMAN, COLLECTIONS.artifactRequest, 'request-adr', 'cid-request-adr', { $type: COLLECTIONS.artifactRequest, project: ref(project), @@ -407,8 +534,16 @@ it('never considers a project-scoped request (selectDispatchable only walks goal const index = materialize(store([...records, projectRequest]), { spaceUri: SPACE_URI }) const ledger = new TurnLedger() const actors = registryFor([actorFor(AGENT, ['plan', 'adr'])]) - // Only the goal-scoped plan request is selected; the project-scoped adr request never appears. - assert.deepEqual(uris(selectDispatchable(index, actors, ledger)), [records.find((r) => r.value.type === 'plan').uri]) + const result = selectDispatchable(index, actors, ledger) + // Both the goal-scoped plan and the project-scoped adr now dispatch (sorted by request uri). + assert.deepEqual(uris(result).sort(), [request.uri, projectRequest.uri].sort()) + const adr = result.find((d) => d.request.uri === projectRequest.uri) + assert.equal(adr.artifactType.name, 'adr') + assert.equal(adr.target.target.uri, project.uri) // the owning view is the ProjectView + assert.equal(adr.implementation, undefined) // project types never carry predecessor data + assert.ok(adr.bundle) + assert.equal(adr.bundle.goal, undefined) // a direct project request has no goal + assert.equal(adr.bundle.project.uri, project.uri) ledger.close() }) @@ -1189,3 +1324,88 @@ it('E2E: a review request drives a real review verdict and fulfills the request ledger.close() }) }) + +// --- Project-scoped (system artifact) turn end-to-end ------------------------ + +it('E2E: a project-scoped adr request lands a project-anchored artifact that a fresh materialize shows fulfilled and in currentSystemArtifacts, then rides in a subsequent goal turn bundle (§8 long-term memory loop)', async () => { + await withTempDir(async (runsDir) => { + const pds = new LocalPds(AGENT) + const session = await createSession(pds.service, pds.handle, 'pw', pds.fetch.bind(pds)) + const client = new CredentialClient(session, pds.fetch.bind(pds)) + const base = buildScenario() + // Fulfill the base plan request so only the project-scoped adr request is open to dispatch. + const planArt = mk(AGENT, COLLECTIONS.artifact, 'plan-done', 'cid-plan-done', { + $type: COLLECTIONS.artifact, + request: ref(base.request), + goal: ref(base.goal), + type: 'plan', + body: 'plan', + links: {}, + createdAt: '2026-01-01T00:03:30Z', + }) + const adrReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'adr-req', 'cid-adr-req', { + $type: COLLECTIONS.artifactRequest, + project: ref(base.project), + type: 'adr', + basedOn: [], + assignee: AGENT, + createdAt: '2026-01-01T00:04:00Z', + }) + const recordStore = store([...base.records, planArt, adrReq]) + const index = materialize(recordStore, { spaceUri: SPACE_URI }) + const actors = registryFor([{ ...actorFor(AGENT, ['plan', 'adr']), client }]) + const ledger = new TurnLedger() + + const { dispatcher } = makeDispatcher({ + ledger, + runsDir, + runnerFn: async (spec) => { + const response = await sendLine(hostSocketPath(spec), { + method: 'submitArtifact', + token: spec.env.RADIAL_TURN_TOKEN, + body: 'the ADR body', + }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }, + }) + + dispatcher.pump(index, actors) + assert.equal(dispatcher.inFlight, 1) // only the adr request is dispatchable + await dispatcher.drain() + + assert.equal(ledger.get(adrReq.uri).state, 'fulfilled') + const stored = [...pds.records.values()].filter((r) => r.value.$type === COLLECTIONS.artifact) + assert.equal(stored.length, 1) + const adr = stored[0] + assert.deepEqual(adr.value.project, ref(base.project)) // anchored to the project, not a goal + assert.equal(adr.value.goal, undefined) + assert.equal(adr.value.type, 'adr') + + // Ingest the written adr and re-materialize: the request is fulfilled and the adr is the project's + // current system artifact. + const arkey = adr.uri.slice(adr.uri.lastIndexOf('/') + 1) + recordStore.put({ did: AGENT, collection: COLLECTIONS.artifact, rkey: arkey, uri: adr.uri, cid: adr.cid, rev: '0000000000009', value: adr.value }) + const index2 = materialize(recordStore, { spaceUri: SPACE_URI }) + const projectView = index2.projects.find((v) => v.target.uri === base.project.uri) + assert.equal(projectView.currentSystemArtifacts.some((a) => a.uri === adr.uri), true) + assert.equal(projectView.openRequests.some((r) => r.uri === adrReq.uri), false) + + // A subsequent GOAL-scoped turn's bundle now carries that adr in currentSystemArtifacts — the + // agents' on-protocol long-term memory (Phase 5 exit criterion). + const freshPlanReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'plan-2', 'cid-plan-2', { + $type: COLLECTIONS.artifactRequest, + goal: ref(base.goal), + type: 'plan', + basedOn: [], + assignee: AGENT, + createdAt: '2026-01-01T00:06:00Z', + }) + recordStore.put(freshPlanReq) + const index3 = materialize(recordStore, { spaceUri: SPACE_URI }) + const bundle = buildTurnBundle(index3, freshPlanReq.uri, freshPlanReq.cid) + assert.ok(bundle.goal) + assert.equal(bundle.currentSystemArtifacts.some((a) => a.uri === adr.uri), true) + ledger.close() + }) +}) -- knotmirror 0.0.1 From deaa497b2b11725bc0cd51e060830d488d53558f Mon Sep 17 00:00:00 2001 From: Tim Disney Date: Thu, 23 Jul 2026 15:06:06 -0700 Subject: [PATCH 13/13] daemon: fix three review findings in project-scoped dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Capture turns could dispatch without their commissioned input. buildTurnBundle derives the source goal only from RESOLVED basedOn and records unresolved refs in missingRefs, but the project loop launched goal-less bundles regardless. Now a project-scoped NON-review artifact request whose bundle has non-empty missingRefs is held with a stale-index reject (retried next tick). Goal-scoped requests stay exempt (basedOn is never required there); review requests stay exempt (subject is guaranteed resolved, basedOn is provenance only). 2. The askQuestion anchor was computed from the expanded ancestry/subject closure, so a v2-based turn could anchor to v1 and a project review turn inherited its subject via the closure by accident. Now: REVIEW turns anchor explicitly to the subject under review; other project turns use the lowest-uri artifact among the request's DIRECT resolved basedOn only (never prev-ancestry, never seeded subjects); else reject. 3. submitArtifact retry adoption compared only the expected anchor, so a record carrying both project and a stray goal (which the materializer resolves to the goal) could be adopted — leaving the project request open forever while the ledger said fulfilled. Adoption now also requires the other anchor to be absent (defense in depth alongside getOwnRecord's read-side exactly-one-anchor validation, which is the first guard). Tests: capture held until source ingested then dispatched with source goal; question anchors to direct v2 not ancestry v1; project review question anchored to subject; dual-anchor record at the deterministic rkey → adoption refused. Co-Authored-By: Claude Fable 5 --- packages/daemon/src/dispatch.ts | 12 +++++ packages/daemon/src/turn-socket.ts | 8 +++- packages/daemon/src/turn.ts | 24 ++++++++-- packages/daemon/test/dispatch.test.mjs | 43 +++++++++++++++++ packages/daemon/test/turn-socket.test.mjs | 43 +++++++++++++++++ packages/daemon/test/turn.test.mjs | 58 +++++++++++++++++++++++ 6 files changed, 182 insertions(+), 6 deletions(-) diff --git a/packages/daemon/src/dispatch.ts b/packages/daemon/src/dispatch.ts index 481228e..cbe6db1 100644 --- a/packages/daemon/src/dispatch.ts +++ b/packages/daemon/src/dispatch.ts @@ -306,6 +306,18 @@ export function selectDispatchable( return undefined } + // A project-scoped (capture) artifact request is COMMISSIONED to distil from its basedOn source; + // dispatching before that source is ingested would launch a goal-less bundle that has lost its + // commissioned input (the source goal is derived only from RESOLVED basedOn, and unresolved refs + // are recorded in missingRefs). Skip until ingestion catches up — a stale-index skip, retried next + // tick, never a permanent reject. Goal-scoped requests are exempt: basedOn is never required there + // by design (the turn gets the goal's full context regardless). Review requests are exempt too: + // their subject is guaranteed resolved by the materializer, and basedOn is provenance only. + if (expectedScope === 'project' && type !== REVIEW_TYPE_NAME && bundle.missingRefs.length > 0) { + onReject?.(request.uri, 'project-scoped request has an unresolved basedOn ref (stale index)') + return undefined + } + return { target: view, request, diff --git a/packages/daemon/src/turn-socket.ts b/packages/daemon/src/turn-socket.ts index a74eaaa..5851f9a 100644 --- a/packages/daemon/src/turn-socket.ts +++ b/packages/daemon/src/turn-socket.ts @@ -475,8 +475,13 @@ export class TurnSocketServer { throw error } const current = existing.value as ArtifactRecord - // Compare against whichever anchor this request carries (goal- or project-scoped). + // Compare against whichever anchor this request carries (goal- or project-scoped). The + // expected anchor must match AND the OTHER anchor must be absent: a stray second anchor is a + // different record than we would write, and the materializer resolves a dual-anchor artifact + // to its goal (goal takes precedence) — adopting one for a project request would leave that + // request open forever while the ledger reported it fulfilled. const currentAnchor = request.goal ? current.goal : current.project + const strayAnchor = request.goal ? current.project : current.goal const expectedAnchor = request.goal ?? request.project if ( current.$type !== COLLECTIONS.artifact || @@ -485,6 +490,7 @@ export class TurnSocketServer { current.request.cid !== request.cid || currentAnchor?.uri !== expectedAnchor.uri || currentAnchor?.cid !== expectedAnchor.cid || + strayAnchor !== undefined || JSON.stringify(current.links) !== JSON.stringify(links) || JSON.stringify(current.prev) !== JSON.stringify(prev) || JSON.stringify(current.criteria ?? []) !== JSON.stringify(envelope.criteria ?? []) || diff --git a/packages/daemon/src/turn.ts b/packages/daemon/src/turn.ts index 756b18d..e3ca56f 100644 --- a/packages/daemon/src/turn.ts +++ b/packages/daemon/src/turn.ts @@ -368,15 +368,29 @@ export async function runTurn(input: TurnInput, deps: TurnDeps): Promise a.uri.localeCompare(b.uri))[0] + // DIRECT resolved basedOn = request.basedOn refs that resolved to an artifact in the bundle. + const resolvedRefs = new Set(input.bundle.basedOn.map((artifact) => `${artifact.uri}#${artifact.cid}`)) + const lowest = input.bundle.request.basedOn + .filter((reference) => resolvedRefs.has(`${reference.uri}#${reference.cid}`)) + .sort((a, b) => a.uri.localeCompare(b.uri))[0] if (lowest) questionAnchor = { artifact: { uri: lowest.uri, cid: lowest.cid } } } } diff --git a/packages/daemon/test/dispatch.test.mjs b/packages/daemon/test/dispatch.test.mjs index 8235741..ae0ca7c 100644 --- a/packages/daemon/test/dispatch.test.mjs +++ b/packages/daemon/test/dispatch.test.mjs @@ -460,6 +460,49 @@ it('dispatches a project-scoped CAPTURE request; its bundle carries the source g ledger.close() }) +it('holds a project-scoped capture request until its basedOn source is ingested (stale index), then dispatches with the source goal', () => { + const base = buildScenario() + const planSrc = mk(AGENT, COLLECTIONS.artifact, 'plan-src', 'cid-plan-src', { + $type: COLLECTIONS.artifact, + request: ref(base.request), + goal: ref(base.goal), + type: 'plan', + body: 'the plan', + links: {}, + createdAt: '2026-01-01T00:03:30Z', + }) + const captureReq = mk(HUMAN, COLLECTIONS.artifactRequest, 'capture-req', 'cid-capture-req', { + $type: COLLECTIONS.artifactRequest, + project: ref(base.project), + type: 'adr', + basedOn: [ref(planSrc)], + assignee: AGENT, + createdAt: '2026-01-01T00:05:00Z', + }) + const actors = registryFor([actorFor(AGENT, ['plan', 'adr'])]) + + // Source artifact NOT yet ingested: the capture request is held (stale index), never dispatched + // goal-less. (Its basedOn ref is unresolved, so the bundle records it in missingRefs.) + const stale = materialize(store([...base.records, captureReq]), { spaceUri: SPACE_URI }) + const ledgerA = new TurnLedger() + const reasons = [] + const held = selectDispatchable(stale, actors, ledgerA, undefined, (uri, reason) => { + if (uri === captureReq.uri) reasons.push(reason) + }) + assert.equal(held.some((d) => d.request.uri === captureReq.uri), false) + assert.match(reasons.join(' '), /unresolved basedOn/) + ledgerA.close() + + // Source now ingested: the capture request dispatches, and the bundle carries the source goal. + const ready = materialize(store([...base.records, planSrc, captureReq]), { spaceUri: SPACE_URI }) + const ledgerB = new TurnLedger() + const cap = selectDispatchable(ready, actors, ledgerB).find((d) => d.request.uri === captureReq.uri) + assert.ok(cap, 'the capture request should dispatch once its source resolves') + assert.ok(cap.bundle.goal) + assert.equal(cap.bundle.goal.uri, base.goal.uri) + ledgerB.close() +}) + it('dispatches a project-scoped REVIEW request whose subject is a project-scoped artifact (integration item d)', () => { const { records, reviewReq, adrArt, project } = withProjectReviewRequest() const index = materialize(store(records), { spaceUri: SPACE_URI }) diff --git a/packages/daemon/test/turn-socket.test.mjs b/packages/daemon/test/turn-socket.test.mjs index a976442..0ffbeff 100644 --- a/packages/daemon/test/turn-socket.test.mjs +++ b/packages/daemon/test/turn-socket.test.mjs @@ -658,6 +658,49 @@ it('project-scoped submitArtifact adopts on retry, comparing the project anchor' }) }) +it('project-scoped submitArtifact refuses to adopt an existing record carrying a stray second anchor', async () => { + await withTempDir(async (directory) => { + const pds = new LocalPds('did:plc:agent-dual-anchor') + const client = await makeClient(pds) + const rkey = planArtifactRkey(PROJECT_REQUEST.uri, PROJECT_REQUEST.cid) + // Pre-seed a record at the deterministic rkey that carries BOTH project AND a stray goal — the + // materializer would resolve it to the goal (goal takes precedence), so adopting it for a project + // request would leave that request open forever while the ledger reported it fulfilled. Injected + // straight into the store (client.create validates exactly-one-anchor and would reject it). + const seededUri = `at://${pds.did}/${COLLECTIONS.artifact}/${rkey}` + pds.records.set(seededUri, { + uri: seededUri, + cid: 'seed-dual-anchor-cid', + value: { + $type: COLLECTIONS.artifact, + request: { uri: PROJECT_REQUEST.uri, cid: PROJECT_REQUEST.cid }, + project: PROJECT, + goal: { uri: 'at://did:plc:human/com.disnetdev.radial.goal/stray', cid: 'straycid' }, + type: 'adr', + body: 'the adr', + links: {}, + createdAt: NOW, + }, + }) + const { server, socketPath } = await startServer(directory, client, { + context: { request: PROJECT_REQUEST, mode: { kind: 'artifact', type: 'adr' } }, + }) + try { + const response = await sendLine(socketPath, { method: 'submitArtifact', token: TOKEN, body: 'the adr' }) + // Adoption is refused. Two guards enforce this: getOwnRecord validates the fetched record + // (exactly-one anchor) and rejects a dual-anchor record on read, and #submitArtifact's adoption + // comparison additionally requires the stray anchor to be absent (defense in depth if read-side + // validation is ever relaxed). Either way the socket does not adopt and reports failure. + assert.equal(response.ok, false) + assert.match(response.error, /refusing to adopt tampered record|exactly one of goal or project/) + // The stray/seeded record was not handed back as an accepted artifact ref. + assert.equal(response.ref, undefined) + } finally { + await server.close() + } + }) +}) + it('project-scoped askQuestion precedence: capture source goal anchor', async () => { await withTempDir(async (directory) => { const pds = new LocalPds('did:plc:agent-adr-q1') diff --git a/packages/daemon/test/turn.test.mjs b/packages/daemon/test/turn.test.mjs index dcec8cc..cbcf99e 100644 --- a/packages/daemon/test/turn.test.mjs +++ b/packages/daemon/test/turn.test.mjs @@ -621,6 +621,64 @@ it('project-scoped turn: default-branch read-only checkout and a project-anchore }) }) +it('project-scoped question anchors to the DIRECT resolved basedOn (v2), never a prev-ancestry v1 in the closure', async () => { + const { pds, actor } = await makeActor('did:plc:agent-anchor-direct') + // v1 sorts BEFORE v2 by uri: the old (buggy) lowest-uri-over-the-closure pick would choose v1. + const V1_REF = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/a-v1', cid: 'v1cid' } + const V2_REF = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/z-v2', cid: 'v2cid' } + const bundle = { + ...ADR_BUNDLE, + request: { uri: BUNDLE.request.uri, cid: BUNDLE.request.cid, type: 'adr', basedOn: [V2_REF] }, // DIRECT = v2 only + basedOn: [ + { ...V1_REF, type: 'adr', body: 'v1', links: {}, createdAt: '2026-01-01T00:01:00Z' }, // v1 is ancestry + { ...V2_REF, type: 'adr', body: 'v2', links: {}, createdAt: '2026-01-01T00:02:00Z' }, + ], + } + const requestRecord = { ...ADR_REQUEST_RECORD, basedOn: [V2_REF] } + await withRunDir(async (runDir) => { + const runner = new FakeContainerRunner(async (spec) => { + const response = await sendLine(hostSocketPath(spec), { method: 'askQuestion', token: spec.env.RADIAL_TURN_TOKEN, body: 'which decision?' }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }) + const result = await runTurn( + baseInput(runDir, { actor, bundle, request: { uri: BUNDLE.request.uri, cid: BUNDLE.request.cid, project: PROJECT }, artifactType: ADR_ARTIFACT_TYPE, requestRecord }), + { runner, harness: new ClaudeCodeHarness(), checkout: noopCheckout }, + ) + assert.equal(result.outcome, 'awaiting_input') + const message = [...pds.records.values()].find((r) => r.value.$type === COLLECTIONS.message).value + assert.deepEqual(message.artifact, V2_REF) // the DIRECT basedOn, not the lower-uri ancestry v1 + assert.equal(message.goal, undefined) + }) +}) + +it('project-scoped REVIEW turn anchors its question to the SUBJECT (explicit branch, not the seeded closure)', async () => { + const { pds, actor } = await makeActor('did:plc:agent-anchor-review') + const SUBJECT_REF = { uri: 'at://did:plc:agent/com.disnetdev.radial.artifact/adr-subj', cid: 'subjcid' } + const bundle = { + ...ADR_BUNDLE, + request: { uri: BUNDLE.request.uri, cid: BUNDLE.request.cid, type: 'review', basedOn: [] }, + subject: { ...SUBJECT_REF, type: 'adr', body: 'the adr', links: {}, createdAt: '2026-01-01T00:02:00Z' }, + basedOn: [{ ...SUBJECT_REF, type: 'adr', body: 'the adr', links: {}, createdAt: '2026-01-01T00:02:00Z' }], // subject is seeded into the closure + } + const requestRecord = { $type: COLLECTIONS.artifactRequest, project: PROJECT, type: 'review', subject: SUBJECT_REF, basedOn: [], assignee: 'did:plc:agent', createdAt: '2026-01-01T00:03:00Z' } + await withRunDir(async (runDir) => { + const runner = new FakeContainerRunner(async (spec) => { + const response = await sendLine(hostSocketPath(spec), { method: 'askQuestion', token: spec.env.RADIAL_TURN_TOKEN, body: 'which standard?' }) + assert.equal(response.ok, true) + return { exitCode: 0, timedOut: false } + }) + const result = await runTurn( + baseInput(runDir, { actor, bundle, request: { uri: BUNDLE.request.uri, cid: BUNDLE.request.cid, project: PROJECT }, artifactType: REVIEW_TYPE, requestRecord }), + { runner, harness: new ClaudeCodeHarness(), checkout: noopCheckout }, + ) + assert.equal(result.outcome, 'awaiting_input') + const message = [...pds.records.values()].find((r) => r.value.$type === COLLECTIONS.message).value + assert.deepEqual(message.artifact, SUBJECT_REF) // anchored to the subject under review + assert.equal(message.goal, undefined) + }) +}) + it('classifyTurnObservation: an observation with BOTH an artifact and a review is crashed (never a silent preference)', () => { const both = classifyTurnObservation({ artifact: { uri: 'at://a/x/1', cid: 'c1' },