diff --git a/docs/reviewer-attempt-evidence.md b/docs/reviewer-attempt-evidence.md index d3c8709..7e5c408 100644 --- a/docs/reviewer-attempt-evidence.md +++ b/docs/reviewer-attempt-evidence.md @@ -17,7 +17,32 @@ The producer freezes these primitives before acquisition and binds them into its no-clobber envelope. Snapshot repository ID/name must match. Existing unbound local producer calls remain available, but cannot be composed. -After the producer job has terminated, the host calls: +A trusted host can supply an optional `onPublished` callback to `runProducer`. +It requires a valid `attemptContext` before any artifacts are created. After a +completed envelope has been published successfully, the producer awaits +`onPublished({ attempt, envelopeSha256 })`. Both the handoff and its primitive-only +attempt object are frozen. The digest comes from the exact bytes used for +publication, not a later read of a potentially replaced bundle. Existing calls +without the callback and the returned envelope are unchanged. The CLI does not +accept a handoff or callback. + +The host must retain that callback value through its own protected channel, +separate from the provider and uploaded bundle. This callback is a trusted host +capability, not a provider callback or proof that arbitrary local JSON is trusted. +No protected storage, artifact upload or authenticated hosted handoff is installed +by this API. A failed producer or unsuccessful publication does not call it. +Completed historical or unknown-applicability evidence can be handed off, but +retains that applicability and cannot establish current completion. + +Publication and handoff are not transactional. If the callback rejects or throws, +`runProducer` rejects with the sanitized `handoff_failed` error; the published +bundle remains. The host may have retained the handoff before throwing. There is +no automatic callback retry, producer replay, rollback, or exactly-once claim. +Reusing the same output directory still fails. A process crash between publication +and handoff can leave a bundle without a protected handoff; do not reconstruct +trusted evidence by hashing that bundle afterward. + +After the entire source workflow run has terminated successfully, the host calls: ```js await composeAttemptEvidence({ @@ -86,6 +111,10 @@ This proves pin/import/failure cleanup, not successful model completion; it cannot reach query construction or native spawn. Missing caches or another platform skip this test honestly. No downloads or installation are performed. +The composer requires a completed successful source run, so a dependent job in +that same still-running workflow cannot qualify it. Future hosted composition +must execute after source-run termination; this gate is unchanged. + Still required for hosted adoption: a reviewed pinned workflow invoking the SDK producer, protected platform attempt-context and envelope-digest handoff, authenticated artifact/API acquisition, and qualification of that complete path. @@ -102,3 +131,9 @@ mutants remain historical evidence; they were not rerun for this compatibility change. Source was restored before the final green run. Node syntax checks, scoped Oxlint checks, and `git diff --check` passed. These are local offline results, not hosted provenance or successful provider qualification. + +Offline composition fixtures now consume the actual producer publication callback. +They cover frozen identity, exact published-byte digest, awaited callback ordering, +partial publication refusal and sanitized callback failure without replay, alongside +the existing sibling-attempt, digest-substitution, incomplete-acquisition and stale +candidate cases. These fixtures do not authenticate a hosted handoff. diff --git a/scripts/reviewer-producer-run.mjs b/scripts/reviewer-producer-run.mjs index 343aba3..d0dfab7 100644 --- a/scripts/reviewer-producer-run.mjs +++ b/scripts/reviewer-producer-run.mjs @@ -53,6 +53,7 @@ function publish(path, value) { try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); } linkSync(file, path); } finally { rmSync(stage, { recursive: true, force: true }); } + return digest(bytes); } function matches(candidate, manifest) { return candidate?.number === manifest.pullRequest && candidate.title === manifest.description.title @@ -91,9 +92,10 @@ function validateCompletion(bytes, snapshotDigest, snapshot, model) { /** Local host orchestration, not authenticated provider admission or cloud authority. */ export async function runProducer({ repository, pullRequest, expectedHead, expectedBase, outputDirectory, readCandidate, - capture = captureSnapshot, runDriver = driverMain, sdkDirectory, claudeBinary, model, attemptContext } = {}) { + capture = captureSnapshot, runDriver = driverMain, sdkDirectory, claudeBinary, model, attemptContext, onPublished } = {}) { const attempt = attemptContext === undefined ? null : captureAttemptContext(attemptContext); if (attempt && attempt.repository !== repository) fail('attempt_context'); + if (onPublished !== undefined && (typeof onPublished !== 'function' || !attempt)) fail('handoff_arguments'); if (typeof repository !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || repository.split('/').some(part => part === '.' || part === '..') || !Number.isSafeInteger(pullRequest) || pullRequest < 1 || !hex(expectedHead) || !hex(expectedBase) || typeof outputDirectory !== 'string' || !isAbsolute(outputDirectory) || typeof readCandidate !== 'function' @@ -151,7 +153,12 @@ export async function runProducer({ repository, pullRequest, expectedHead, expec } } for (const artifact of [envelope.snapshot, envelope.completion]) if (artifact) chmodSync(join(outputDirectory, artifact.file), 0o444); - publish(join(outputDirectory, 'envelope.json'), envelope); + const envelopeSha256 = publish(join(outputDirectory, 'envelope.json'), envelope); + if (envelope.status === 'completed' && onPublished !== undefined) { + // Publication precedes handoff; a failed host callback never rolls back or retries it. + try { await onPublished(Object.freeze({ attempt, envelopeSha256 })); } + catch { fail('handoff_failed'); } + } return envelope; } diff --git a/scripts/reviewer-producer-run.test.mjs b/scripts/reviewer-producer-run.test.mjs index e66d1bb..1c6797d 100644 --- a/scripts/reviewer-producer-run.test.mjs +++ b/scripts/reviewer-producer-run.test.mjs @@ -371,15 +371,15 @@ const attemptFixture = () => ({ repository: 'knitli/demo', repositoryId: 1, runI const hashBytes = bytes => createHash('sha256').update(bytes).digest('hex'); async function evidenceFixture({ mutateContext, stale = false } = {}) { const attempt = attemptFixture(); - let reads = 0; - const input = options({ attemptContext: attempt, readCandidate: async () => { + let reads = 0, handoff; + const input = options({ attemptContext: attempt, onPublished: value => { handoff = value; }, readCandidate: async () => { const value = structuredClone(candidate); if (stale && ++reads >= 4) value.head.sha = 'f'.repeat(40); mutateContext?.(attempt); return value; } }); const envelope = await runProducer(input); - const handoff = { attempt: attemptFixture(), envelopeSha256: hashBytes(await readFile(join(input.outputDirectory, 'envelope.json'))) }; + assert.ok(handoff, 'actual producer delivered the host handoff'); const run = { id: 123, run_attempt: 2, status: 'completed', conclusion: 'success', repository: { id: 1, full_name: 'knitli/demo' }, referenced_workflows: [{ path: handoff.attempt.workflowRef, sha: handoff.attempt.workflowSha }] }; const job = { id: 7, run_id: 123, check_run_url: 'https://api.github.com/repos/knitli/demo/check-runs/77', @@ -402,6 +402,11 @@ test('attempt composition binds independently acquired host digest to exact SDK const h = await evidenceFixture({ mutateContext: context => { context.runAttempt = '9'; } }); assert.deepEqual(h.envelope.attempt, attemptFixture()); assert.equal(Object.isFrozen(h.envelope.attempt), true); + assert.equal(Object.isFrozen(h.handoff), true); + assert.equal(Object.isFrozen(h.handoff.attempt), true); + assert.equal(h.handoff.envelopeSha256, hashBytes(await readFile(join(h.input.outputDirectory, 'envelope.json')))); + assert.throws(() => { h.handoff.envelopeSha256 = 'f'.repeat(64); }, TypeError); + assert.throws(() => { h.handoff.attempt.runAttempt = '9'; }, TypeError); const evidence = await composeAttemptEvidence(h.composeOptions); assert.equal(evidence.status, 'matched'); assert.equal(evidence.execution.execution, 'succeeded'); @@ -413,6 +418,86 @@ test('attempt composition binds independently acquired host digest to exact SDK await assert.rejects(composeAttemptEvidence(h.composeOptions), /EEXIST/); }); +test('publication handoff requires host callback and attempt identity before creating artifacts', async () => { + let calls = 0; + for (const extra of [{ onPublished: null, attemptContext: attemptFixture() }, + { onPublished: 'untrusted', attemptContext: attemptFixture() }, { onPublished: () => { calls++; } }]) { + const input = options({ ...extra, capture: () => { calls++; } }); + await assert.rejects(runProducer(input), /handoff_arguments/); + assert.equal(existsSync(input.outputDirectory), false); + } + assert.equal(calls, 0); +}); + +test('failed producer and incomplete envelope publication never deliver a handoff', async () => { + for (const collision of [false, true]) { + let callbacks = 0, drivers = 0; + const input = options({ attemptContext: attemptFixture(), onPublished: () => { callbacks++; }, + runDriver: async args => { + drivers++; + if (!collision) { + await writeFile(flagsOf(args)['--receipt'], '{partial'); + throw new Error('private driver failure'); + } + const result = await writeReceipt(args); + await writeFile(join(input.outputDirectory, 'envelope.json'), '{partial'); + return result; + } }); + if (collision) { + await assert.rejects(runProducer(input), /EEXIST/); + assert.equal(await readFile(join(input.outputDirectory, 'envelope.json'), 'utf8'), '{partial'); + } else { + const result = await runProducer(input); + assert.equal(result.status, 'failed'); + await committed(input, result); + await assert.rejects(access(join(input.outputDirectory, 'completion.json'))); + } + assert.equal(callbacks, 0); + assert.equal(drivers, 1); + } +}); + +test('publication precedes awaited host handoff and the producer returns its existing envelope', async () => { + let signalStarted, release, finished = false, captured; + const started = new Promise(resolve => { signalStarted = resolve; }); + const blocked = new Promise(resolve => { release = resolve; }); + const input = options({ attemptContext: attemptFixture(), onPublished: async handoff => { + captured = handoff; + signalStarted(); + await blocked; + } }); + const pending = runProducer(input).then(result => { finished = true; return result; }); + await Promise.race([started, pending.then(() => assert.fail('producer settled before host handoff'))]); + try { + const bytes = await readFile(join(input.outputDirectory, 'envelope.json')); + assert.equal(JSON.parse(bytes).status, 'completed'); + assert.equal(captured.envelopeSha256, hashBytes(bytes)); + assert.equal((await stat(join(input.outputDirectory, 'envelope.json'))).mode & 0o777, 0o444); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(finished, false); + } finally { release(); } + await committed(input, await pending); +}); + +test('host handoff failure is sanitized and never rolls back or replays published work', async () => { + let callbacks = 0, drivers = 0, captured; + const input = options({ attemptContext: attemptFixture(), runDriver: args => { drivers++; return writeReceipt(args); }, + onPublished: async handoff => { callbacks++; captured = handoff; throw new Error('private host token'); } }); + await assert.rejects(runProducer(input), error => { + assert.equal(error.code, 'handoff_failed'); + assert.equal(error.message, 'Reviewer producer refused: handoff_failed'); + assert.equal(error.cause, undefined); + return true; + }); + const bytes = await readFile(join(input.outputDirectory, 'envelope.json')); + assert.equal(hashBytes(bytes), captured.envelopeSha256); + assert.equal(JSON.parse(bytes).status, 'completed'); + await access(join(input.outputDirectory, 'completion.json')); + await assert.rejects(runProducer(input), /EEXIST/); + assert.equal(callbacks, 1); + assert.equal(drivers, 1); +}); + test('attempt context is complete and repository-bound before capture; no self-asserted handoff fallback', async () => { let calls = 0; for (const context of [{}, { ...attemptFixture(), runAttempt: 2 }, { ...attemptFixture(), repository: 'other/repo' }, @@ -430,7 +515,7 @@ test('same-head retry and sibling check-run handoffs cannot bind a different pro for (const changes of [{ runAttempt: '1' }, { checkRunId: '99' }, { repositoryId: 2 }, { workflowSha: 'f'.repeat(40), producerRevision: 'f'.repeat(40) }]) { const h = await evidenceFixture(); - Object.assign(h.handoff.attempt, changes); + h.composeOptions.readTrustedHandoff = async () => ({ ...h.handoff, attempt: { ...h.handoff.attempt, ...changes } }); await assert.rejects(composeAttemptEvidence(h.composeOptions), /attempt_mismatch/); assert.equal(h.calls.length, 0); } @@ -472,7 +557,7 @@ test('altered bundle or context cannot substitute for independent retained host assert.equal(h.calls.length, 0); } const h = await evidenceFixture(); - h.handoff.envelopeSha256 = 'f'.repeat(64); + h.composeOptions.readTrustedHandoff = async () => ({ ...h.handoff, envelopeSha256: 'f'.repeat(64) }); await assert.rejects(composeAttemptEvidence(h.composeOptions), /envelope_digest/); }); @@ -576,7 +661,7 @@ test('composition revalidates model summary and receipt against configured model const { chmod } = await import('node:fs/promises'); await chmod(file, 0o600); const bytes = Buffer.from(JSON.stringify(h.envelope)); await writeFile(file, bytes); - h.handoff.envelopeSha256 = hashBytes(bytes); + h.composeOptions.readTrustedHandoff = async () => ({ ...h.handoff, envelopeSha256: hashBytes(bytes) }); await assert.rejects(composeAttemptEvidence(h.composeOptions), /completion_invalid|snapshot_binding/); assert.equal(h.calls.length, 0); await assert.rejects(access(h.composeOptions.outputPath));