diff --git a/docs/reviewer-attempt-evidence.md b/docs/reviewer-attempt-evidence.md new file mode 100644 index 0000000..d3c8709 --- /dev/null +++ b/docs/reviewer-attempt-evidence.md @@ -0,0 +1,104 @@ +# Dormant reviewer attempt composition + +The library in `scripts/reviewer-attempt-evidence.mjs` joins a validated frozen-input +producer bundle with independently acquired, attempt-specific GitHub execution +evidence. It does not enable a workflow, run a provider, post a review, authenticate +a local file by itself, or complete an attention round. All outputs retain +`provenance: unverified` and `roundCompletion: unknown`. + +## Host contract + +A trusted host may pass `attemptContext` to `runProducer`. It contains exactly +`repository`, `repositoryId`, `runId`, `runAttempt`, `checkRunId`, `workflowRef`, +`workflowSha`, and `producerRevision`. Run/attempt/check IDs are decimal strings; +repository ID is a positive safe integer. Workflow identity names the existing +owned reusable reviewer workflow; workflow and producer revision must match. +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: + +```js +await composeAttemptEvidence({ + directory: '/private/attempt-bundle', + outputPath: '/private/attempt-evidence.json', + readTrustedHandoff, // -> { attempt, envelopeSha256 } + get, // synchronous authenticated GitHub API acquisition +}); +``` + +These functions are trusted host capabilities, not bundle-defined callbacks or +untrusted extension points. `readTrustedHandoff` must acquire the exact attempt +identity and envelope digest from an independently protected host channel. The +host must capture that digest from its own completed producer invocation and +bind it to platform job context. Reading the same bundle to manufacture this +handoff violates the contract. There is deliberately no CLI accepting arbitrary +receipt JSON, no `trusted: true` field, and no fallback to self-reported hashes. + +`get` must perform authenticated GitHub API reads through host-owned credentials. +`collectSdkExecution` calls the exact run-attempt endpoint and all required job +pages. The actual run repository ID, run/attempt, owned workflow path and immutable +revision must match. GitHub's `@main` versus `@refs/heads/main` path spelling is +allowed only with the same immutable SHA. Job selection uses the exact platform +check-run URL, never job display names or head SHA. Incomplete/duplicate pages, +missing identities, or acquisition errors remain unknown. Error bodies are not +retained. + +The SDK producer has a distinct fixed step name: +`Frozen SDK PR review (execution receipt v1)`. The existing +`Claude PR review (execution receipt v1)` action is never reinterpreted as an SDK +execution. No existing workflow uses the new step in this change. + +## Result semantics + +The composer first verifies the independently supplied envelope digest, complete +attempt identity, snapshot/manifest/blob hashes, completion digest/session/report +and fixed filenames/bounds. It revalidates the explicit configured model against +requested/resolved/sole-usage model identities in the completion receipt and its +envelope summary; refreshing a local digest cannot bypass those checks. It repeats retained-byte validation after platform +acquisition, then atomically publishes a separate mode-0444 artifact without +replacement. Original bundle artifacts are not modified. + +`status: matched` requires the run attempt and selected job to be completed and +successful, the exact SDK execution step to have succeeded, and the separately +handed-off bundle passed validation. Failed, cancelled, skipped, nonterminal or +unavailable execution produces `status: unavailable`. `applicability` is retained +from the producer: a stale historical review stays stale even if execution +matches. Neither status grants review approval, provider admission, installation +identity, trusted policy, admission ordering, or round completion. Filesystem +owners can still alter files after this point; downstream use needs independent +acquisition and validation. + +## Offline validation and remaining adoption work + +`node --test scripts/reviewer-producer-run.test.mjs scripts/reviewer-execution-receipt.test.mjs` +exercises real local Git snapshot capture, deterministic completion fixtures, +exact attempt binding, immutable inputs, retry/sibling/legacy-step substitution, +workflow drift, partial pagination, terminal states, altered bundle bytes, +no-clobber output, and historical candidate movement. + +When the existing exact cached SDK 0.3.209 and Darwin ARM64 binary are available, +a separate test invokes the actual default producer driver in a child with a +closed environment and no model credential. It also invokes the actual pinned +driver and requires its precise missing-options rejection after SDK import. +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. + +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. +This slice intentionally does not install those capabilities. No successful +provider execution or externally authenticated hosted provenance is claimed. + +Verified after the prerequisite merges on 2026-10-17: all four reviewer suites +passed (147 tests, zero skips), including the cached SDK qualifier. The original +composition reader failed against the updated producer's model-bound receipt; +the compatible reader passes. Two causal mutants removing model-summary checks +or trusting the receipt's model instead of the configured model failed the new +composition assertions. The earlier eleven attempt/platform/digest/freshness +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. diff --git a/scripts/reviewer-attempt-evidence.mjs b/scripts/reviewer-attempt-evidence.mjs new file mode 100644 index 0000000..51a871b --- /dev/null +++ b/scripts/reviewer-attempt-evidence.mjs @@ -0,0 +1,45 @@ +import { closeSync, fsyncSync, linkSync, mkdtempSync, openSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { captureAttemptContext, readProducerBundle } from './reviewer-producer-run.mjs'; +import { collectSdkExecution } from './reviewer-execution-receipt.mjs'; + +const fail = code => { throw new Error(`Reviewer attempt evidence refused: ${code}`); }; +const equalAttempt = (a, b) => Object.keys(a).every(key => a[key] === b[key]); + +/** Dormant trusted-host API. Both ports must be supplied independently of the producer bundle. + * readTrustedHandoff acquires the protected host's exact attempt and envelope digest; + * get acquires GitHub API responses with host-owned credentials. Neither is an untrusted plugin. */ +export async function composeAttemptEvidence({ directory, outputPath, readTrustedHandoff, get }) { + if (typeof directory !== 'string' || typeof outputPath !== 'string' + || typeof readTrustedHandoff !== 'function' || typeof get !== 'function') fail('arguments'); + // Keep output separate even if a caller accidentally selects an existing producer artifact. + if (['envelope.json', 'snapshot.json', 'completion.json'].some(file => resolve(outputPath) === resolve(directory, file))) fail('output_path'); + const supplied = await readTrustedHandoff(); + if (!supplied || Object.keys(supplied).sort().join('|') !== 'attempt|envelopeSha256') fail('handoff'); + const attempt = captureAttemptContext(supplied.attempt); + const envelopeSha256 = supplied.envelopeSha256; + const bundle = readProducerBundle(directory, envelopeSha256); + if (!equalAttempt(attempt, bundle.attempt)) fail('attempt_mismatch'); + const execution = collectSdkExecution(get, { + repository: attempt.repository, repositoryId: attempt.repositoryId, runId: attempt.runId, runAttempt: attempt.runAttempt, + checkRunId: attempt.checkRunId, reviewWorkflowRef: attempt.workflowRef, collectorWorkflowRef: attempt.workflowRef, + reviewWorkflowSha: attempt.workflowSha, collectorWorkflowSha: attempt.workflowSha, producerRevision: attempt.producerRevision, + }); + // Acquisition ports may yield control internally; never retain a bundle that changed during acquisition. + readProducerBundle(directory, envelopeSha256); + const result = { + schema: 'knitli-reviewer-attempt-evidence:v1', provenance: 'unverified', roundCompletion: 'unknown', + status: execution.execution === 'succeeded' ? 'matched' : 'unavailable', + attempt, envelopeSha256, executionId: bundle.envelope.executionId, + applicability: bundle.envelope.applicability, execution, + }; + const bytes = Buffer.from(`${JSON.stringify(result, null, 2)}\n`); + if (bytes.length > 64 * 1024) fail('output_limit'); + const stage = mkdtempSync(join(dirname(outputPath), '.attempt-evidence-')); + try { + const file = join(stage, 'evidence.json'), fd = openSync(file, 'wx', 0o444); + try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); } + linkSync(file, outputPath); + } finally { rmSync(stage, { recursive: true, force: true }); } + return result; +} diff --git a/scripts/reviewer-execution-receipt.mjs b/scripts/reviewer-execution-receipt.mjs index 92a09ec..91e6d81 100644 --- a/scripts/reviewer-execution-receipt.mjs +++ b/scripts/reviewer-execution-receipt.mjs @@ -2,10 +2,11 @@ import { execFileSync } from 'node:child_process'; import { readFileSync, writeFileSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; +export const sdkStepName = 'Frozen SDK PR review (execution receipt v1)'; export const stepName = 'Claude PR review (execution receipt v1)'; const sha = value => typeof value === 'string' && /^[a-f0-9]{40}$/.test(value) ? value : null; -export function project(run, pages, event, current, expected) { +function projectStep(run, pages, event, current, expected, selectedStep) { const receipt = { schema: 'knitli-reviewer-execution:v1', repository: expected.repository, runId: expected.runId, runAttempt: expected.runAttempt, @@ -37,7 +38,7 @@ export function project(run, pages, event, current, expected) { receipt.reason = matches.length > 1 ? 'ambiguous-review-job' : 'missing-review-job'; if (matches.length !== 1) return receipt; const job = matches[0]; - const steps = Array.isArray(job.steps) ? job.steps.filter(s => s?.name === stepName) : []; + const steps = Array.isArray(job.steps) ? job.steps.filter(s => s?.name === selectedStep) : []; if (!steps.length) { receipt.reason = 'missing-review-step'; return receipt; } if (steps.length !== 1) { receipt.reason = 'ambiguous-review-step'; return receipt; } const step = steps[0]; @@ -52,6 +53,29 @@ export function project(run, pages, event, current, expected) { return receipt; } +export function project(run, pages, event, current, expected) { + return projectStep(run, pages, event, current, expected, stepName); +} + +/** get is a trusted authenticated GitHub acquisition port, never bundle-supplied data. */ +export function collectSdkExecution(get, expected) { + const fixed = Object.freeze({ ...expected }); + const empty = () => projectStep({}, [], {}, null, fixed, sdkStepName); + try { + const endpoint = `repos/${fixed.repository}/actions/runs/${fixed.runId}/attempts/${fixed.runAttempt}`; + const run = get(endpoint); + if (run.repository?.id !== fixed.repositoryId || run.status !== 'completed' || run.conclusion !== 'success') return empty(); + // GitHub may spell the same immutable workflow ref as @main or @refs/heads/main. + const refs = run.referenced_workflows?.filter(workflow => typeof workflow.path === 'string' + && workflow.path.split('@')[0] === fixed.reviewWorkflowRef?.split('@')[0]); + if (!refs || refs.length !== 1 || refs[0].sha !== fixed.producerRevision) return empty(); + const receipt = projectStep(run, collectPages(get, `${endpoint}/jobs`), {}, null, fixed, sdkStepName); + if (receipt.execution === 'succeeded' && receipt.job?.conclusion !== 'success') + return { ...receipt, execution: 'unknown', reason: 'review-job-unsuccessful' }; + return receipt; + } catch { return empty(); } +} + export function collectPages(get, endpoint) { const pages = []; for (let page = 1; page <= 100; page++) { diff --git a/scripts/reviewer-producer-run.mjs b/scripts/reviewer-producer-run.mjs index 2b72b0c..343aba3 100644 --- a/scripts/reviewer-producer-run.mjs +++ b/scripts/reviewer-producer-run.mjs @@ -16,6 +16,20 @@ const exact = (value, keys) => value && typeof value === 'object' && !Array.isAr const safeText = value => typeof value === 'string' && !value.includes('\0') && Buffer.from(value).toString('utf8') === value; export const PRODUCER_LIMITS = Object.freeze({ snapshotBytes: 32 * 1024 * 1024, completionBytes: 256 * 1024, envelopeBytes: 64 * 1024 }); +/** Host context binds data; it does not authenticate itself. */ +export function captureAttemptContext(value) { + const keys = ['repository', 'repositoryId', 'runId', 'runAttempt', 'checkRunId', 'workflowRef', 'workflowSha', 'producerRevision']; + if (!exact(value, keys)) fail('attempt_context'); + const result = Object.freeze(Object.fromEntries(keys.map(key => [key, value[key]]))); + if (typeof result.repository !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(result.repository) + || result.repository.split('/').some(part => part === '.' || part === '..') + || !Number.isSafeInteger(result.repositoryId) || result.repositoryId < 1 + || ['runId', 'runAttempt', 'checkRunId'].some(key => typeof result[key] !== 'string' || !/^[1-9][0-9]{0,19}$/.test(result[key])) + || typeof result.workflowRef !== 'string' || !/^knitli\/\.github\/\.github\/workflows\/claude-pr-reviewer\.yml@[^\s]{1,256}$/.test(result.workflowRef) + || !hex(result.workflowSha) || result.workflowSha !== result.producerRevision) fail('attempt_context'); + return result; +} + function boundedFile(path, maximum) { const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); try { @@ -77,7 +91,9 @@ 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 } = {}) { + capture = captureSnapshot, runDriver = driverMain, sdkDirectory, claudeBinary, model, attemptContext } = {}) { + const attempt = attemptContext === undefined ? null : captureAttemptContext(attemptContext); + if (attempt && attempt.repository !== repository) fail('attempt_context'); 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' @@ -88,7 +104,7 @@ export async function runProducer({ repository, pullRequest, expectedHead, expec mkdirSync(outputDirectory, { mode: 0o700 }); const snapshotPath = join(outputDirectory, 'snapshot.json'), completionPath = join(outputDirectory, 'completion.json'); const envelope = { schema: 'knitli-reviewer-producer:v1', executionId: randomUUID(), provenance: 'unverified', roundCompletion: 'unknown', - status: 'failed', applicability: 'unknown', failure: null, + status: 'failed', applicability: 'unknown', failure: null, ...(attempt ? { attempt } : {}), configured: { repository, pullRequest, expectedHead, expectedBase, model }, snapshot: null, completion: null }; let stage = 'capture_failed'; try { @@ -96,6 +112,7 @@ export async function runProducer({ repository, pullRequest, expectedHead, expec const snapshotBytes = boundedFile(snapshotPath, PRODUCER_LIMITS.snapshotBytes); const snapshot = validateSnapshot(snapshotBytes, captured.artifactSha256); if (captured.artifactPath !== snapshotPath || snapshot.manifest.repository.fullName !== repository || snapshot.manifest.pullRequest !== pullRequest + || (attempt && snapshot.manifest.repository.id !== attempt.repositoryId) || snapshot.manifest.head.sha !== expectedHead || snapshot.manifest.base.sha !== expectedBase) fail('snapshot_binding'); envelope.snapshot = { file: 'snapshot.json', sha256: digest(snapshotBytes), bytes: snapshotBytes.length, manifestSha256: snapshot.manifestSha256 }; stage = 'candidate_unavailable'; @@ -138,6 +155,40 @@ export async function runProducer({ repository, pullRequest, expectedHead, expec return envelope; } +/** The caller must authenticate this envelope digest through a separate host channel. */ +export function readProducerBundle(directory, expectedEnvelopeSha256) { + const envelopeBytes = boundedFile(join(directory, 'envelope.json'), PRODUCER_LIMITS.envelopeBytes); + if (typeof expectedEnvelopeSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(expectedEnvelopeSha256) + || digest(envelopeBytes) !== expectedEnvelopeSha256) fail('envelope_digest'); + let envelope; + try { envelope = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(envelopeBytes)); } catch { fail('envelope_invalid'); } + if (!exact(envelope, ['schema', 'executionId', 'provenance', 'roundCompletion', 'status', 'applicability', 'failure', 'configured', 'snapshot', 'completion', 'attempt']) + || envelope.schema !== 'knitli-reviewer-producer:v1' || !uuid(envelope.executionId) + || envelope.provenance !== 'unverified' || envelope.roundCompletion !== 'unknown' + || envelope.status !== 'completed' || envelope.failure !== null + || !['unchanged-observed', 'stale', 'unknown'].includes(envelope.applicability)) fail('envelope_invalid'); + const attempt = captureAttemptContext(envelope.attempt); + const snapshotBytes = boundedFile(join(directory, 'snapshot.json'), PRODUCER_LIMITS.snapshotBytes); + const snapshot = validateSnapshot(snapshotBytes, envelope.snapshot?.sha256); + if (!exact(envelope.snapshot, ['file', 'sha256', 'bytes', 'manifestSha256']) || envelope.snapshot.file !== 'snapshot.json' + || envelope.snapshot.bytes !== snapshotBytes.length || envelope.snapshot.manifestSha256 !== snapshot.manifestSha256 + || attempt.repository !== snapshot.manifest.repository.fullName || attempt.repositoryId !== snapshot.manifest.repository.id + || !exact(envelope.configured, ['repository', 'pullRequest', 'expectedHead', 'expectedBase', 'model']) + || envelope.configured.repository !== attempt.repository || envelope.configured.pullRequest !== snapshot.manifest.pullRequest + || envelope.configured.expectedHead !== snapshot.manifest.head.sha || envelope.configured.expectedBase !== snapshot.manifest.base.sha + || typeof envelope.configured.model !== 'string' || !/^[A-Za-z0-9_.-]{1,100}$/.test(envelope.configured.model) + || !/^claude-[a-z0-9]+(?:-[a-z0-9]+)*-[0-9]+$/.test(envelope.configured.model)) fail('snapshot_binding'); + const completionBytes = boundedFile(join(directory, 'completion.json'), PRODUCER_LIMITS.completionBytes); + const completion = validateCompletion(completionBytes, envelope.snapshot.sha256, snapshot, envelope.configured.model); + if (!exact(envelope.completion, ['file', 'sha256', 'bytes', 'sessionId', 'terminalUuid', 'requestedModel', 'resolvedModel', 'usageModels']) || envelope.completion.file !== 'completion.json' + || envelope.completion.sha256 !== digest(completionBytes) || envelope.completion.bytes !== completionBytes.length + || envelope.completion.sessionId !== completion.sessionId || envelope.completion.terminalUuid !== completion.terminalUuid + || envelope.completion.requestedModel !== completion.requestedModel || envelope.completion.resolvedModel !== completion.resolvedModel + || !Array.isArray(envelope.completion.usageModels) || envelope.completion.usageModels.length !== 1 + || envelope.completion.usageModels[0] !== completion.resolvedModel) fail('completion_invalid'); + return { envelope, attempt }; +} + export async function main(args) { const flags = {}; for (let i = 0; i < args.length; i += 2) { diff --git a/scripts/reviewer-producer-run.test.mjs b/scripts/reviewer-producer-run.test.mjs index 41cb873..e66d1bb 100644 --- a/scripts/reviewer-producer-run.test.mjs +++ b/scripts/reviewer-producer-run.test.mjs @@ -361,3 +361,224 @@ test('rejects model aliases before capture', async () => { assert.equal(called, false); } }); + +import { createHash } from 'node:crypto'; +import { existsSync } from 'node:fs'; +import { composeAttemptEvidence } from './reviewer-attempt-evidence.mjs'; +import { sdkStepName, stepName } from './reviewer-execution-receipt.mjs'; +const attemptFixture = () => ({ repository: 'knitli/demo', repositoryId: 1, runId: '123', runAttempt: '2', checkRunId: '77', + workflowRef: 'knitli/.github/.github/workflows/claude-pr-reviewer.yml@refs/heads/main', workflowSha: 'e'.repeat(40), producerRevision: 'e'.repeat(40) }); +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 () => { + 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'))) }; + 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', + status: 'completed', conclusion: 'success', head_sha: candidate.head.sha, + steps: [{ name: sdkStepName, number: 4, status: 'completed', conclusion: 'success' }] }; + const page = { total_count: 1, jobs: [job] }; + const calls = []; + const composeOptions = { directory: input.outputDirectory, outputPath: join(root, `${randomUUID()}.evidence.json`), + readTrustedHandoff: async () => handoff, + get: endpoint => { + calls.push(endpoint); + if (endpoint === 'repos/knitli/demo/actions/runs/123/attempts/2') return run; + if (endpoint === 'repos/knitli/demo/actions/runs/123/attempts/2/jobs?per_page=100&page=1') return page; + throw new Error('unexpected authenticated endpoint'); + } }; + return { input, envelope, handoff, run, job, page, calls, composeOptions }; +} + +test('attempt composition binds independently acquired host digest to exact SDK job, never round completion', async () => { + const h = await evidenceFixture({ mutateContext: context => { context.runAttempt = '9'; } }); + assert.deepEqual(h.envelope.attempt, attemptFixture()); + assert.equal(Object.isFrozen(h.envelope.attempt), true); + const evidence = await composeAttemptEvidence(h.composeOptions); + assert.equal(evidence.status, 'matched'); + assert.equal(evidence.execution.execution, 'succeeded'); + assert.equal(evidence.provenance, 'unverified'); + assert.equal(evidence.roundCompletion, 'unknown'); + assert.equal(evidence.execution.reviewCompletion, 'unknown'); + assert.deepEqual(JSON.parse(await readFile(h.composeOptions.outputPath)), evidence); + assert.equal(h.calls.length, 2); + await assert.rejects(composeAttemptEvidence(h.composeOptions), /EEXIST/); +}); + +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' }, + { ...attemptFixture(), workflowSha: 'f'.repeat(40) }]) { + await assert.rejects(runProducer(options({ attemptContext: context, capture: () => { calls++; } })), /attempt_context/); + } + assert.equal(calls, 0); + const h = await evidenceFixture(); + await assert.rejects(composeAttemptEvidence({ ...h.composeOptions, readTrustedHandoff: undefined }), /arguments/); + await assert.rejects(composeAttemptEvidence({ ...h.composeOptions, readTrustedHandoff: async () => h.envelope }), /handoff/); + assert.equal(h.calls.length, 0); +}); + +test('same-head retry and sibling check-run handoffs cannot bind a different producer attempt', async () => { + 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); + await assert.rejects(composeAttemptEvidence(h.composeOptions), /attempt_mismatch/); + assert.equal(h.calls.length, 0); + } +}); + +test('authenticated platform retry, sibling, old action, incomplete pagination and workflow drift never match', async () => { + for (const mutate of [h => { h.run.run_attempt = 1; }, h => { h.job.check_run_url = 'https://api.github.com/repos/knitli/demo/check-runs/99'; }, + h => { h.job.steps[0].name = stepName; }, h => { h.page.total_count = 2; }, + h => { h.page.jobs.push({ ...h.job }); h.page.total_count = 2; }, + h => { h.run.referenced_workflows[0].sha = 'f'.repeat(40); }, h => { h.run.repository.id = 2; }]) { + const h = await evidenceFixture(); mutate(h); + const evidence = await composeAttemptEvidence(h.composeOptions); + assert.equal(evidence.status, 'unavailable'); + assert.equal(evidence.execution.execution, 'unknown'); + assert.equal(evidence.roundCompletion, 'unknown'); + } +}); + +test('failed skipped cancelled nonterminal or unavailable execution never matches local successful completion', async () => { + for (const conclusion of ['failure', 'skipped', 'cancelled', 'timed_out', 'neutral']) { + const h = await evidenceFixture(); h.job.steps[0].conclusion = conclusion; + assert.equal((await composeAttemptEvidence(h.composeOptions)).status, 'unavailable'); + } + const h = await evidenceFixture(); h.job.status = 'in_progress'; + assert.equal((await composeAttemptEvidence(h.composeOptions)).status, 'unavailable'); + const other = await evidenceFixture(); other.composeOptions.get = () => { throw new Error('private token error'); }; + const evidence = await composeAttemptEvidence(other.composeOptions); + assert.equal(evidence.status, 'unavailable'); + assert.doesNotMatch(JSON.stringify(evidence), /private token/); +}); + +test('altered bundle or context cannot substitute for independent retained host digest', async () => { + for (const name of ['envelope.json', 'snapshot.json', 'completion.json']) { + const h = await evidenceFixture(); + const file = join(h.input.outputDirectory, name); + const { chmod } = await import('node:fs/promises'); await chmod(file, 0o600); + await writeFile(file, `${await readFile(file)} `); + await assert.rejects(composeAttemptEvidence(h.composeOptions)); + assert.equal(h.calls.length, 0); + } + const h = await evidenceFixture(); + h.handoff.envelopeSha256 = 'f'.repeat(64); + await assert.rejects(composeAttemptEvidence(h.composeOptions), /envelope_digest/); +}); + +test('final acquisition cannot replace retained producer bytes', async () => { + const h = await evidenceFixture(); + const original = h.composeOptions.get; + const { chmodSync, appendFileSync } = await import('node:fs'); + h.composeOptions.get = endpoint => { + const file = join(h.input.outputDirectory, 'envelope.json'); + chmodSync(file, 0o600); appendFileSync(file, ' '); + return original(endpoint); + }; + await assert.rejects(composeAttemptEvidence(h.composeOptions), /envelope_digest/); + await assert.rejects(access(h.composeOptions.outputPath)); +}); + +test('stale candidate stays historical even with exact successful execution evidence', async () => { + const h = await evidenceFixture({ stale: true }); + const evidence = await composeAttemptEvidence(h.composeOptions); + assert.equal(evidence.status, 'matched'); + assert.equal(evidence.applicability, 'stale'); + assert.equal(evidence.roundCompletion, 'unknown'); +}); + +const cachedSdk = '/private/tmp/reviewer-sdk-0.3.209-source/package'; +const cachedBinary = '/private/tmp/reviewer-sdk-native-0.3.209-source/package/claude'; +test('actual cached pinned SDK and default producer driver fail before query without a model credential', { + skip: !existsSync(join(cachedSdk, 'sdk.mjs')) || !existsSync(cachedBinary) || process.platform !== 'darwin' || process.arch !== 'arm64', +}, async () => { + const input = options({ sdkDirectory: cachedSdk, claudeBinary: cachedBinary }); + // A clean subprocess cannot inherit a model credential. The real default driver pins and imports + // the SDK, then rejects missing apiKey before constructing a query or spawning the native binary. + const script = `import { runProducer } from ${JSON.stringify(new URL('./reviewer-producer-run.mjs', import.meta.url).href)}; +import { captureSnapshot } from ${JSON.stringify(new URL('./reviewer-input-snapshot.mjs', import.meta.url).href)}; +import { main as driverMain } from ${JSON.stringify(new URL('./reviewer-completion-driver.mjs', import.meta.url).href)}; +const [input, candidate, repo] = JSON.parse(process.argv[1]); +const result = await runProducer({...input, readCandidate: async () => candidate, capture: options => captureSnapshot({...options, localRepository: repo})}); +let driverFailure; +try { await driverMain(['--snapshot', input.outputDirectory+'/snapshot.json', '--snapshot-sha256', result.snapshot.sha256, + '--sdk-directory', input.sdkDirectory, '--claude-binary', input.claudeBinary, '--model', input.model, + '--receipt', input.outputDirectory+'/probe-completion.json']); } catch (error) { driverFailure = error.message; } +if (driverFailure !== 'Reviewer completion refused: options') throw new Error('Actual pinned SDK import/options boundary was not reached'); +console.log(JSON.stringify(result));`; + const serializable = { repository: input.repository, pullRequest: input.pullRequest, expectedHead: input.expectedHead, + expectedBase: input.expectedBase, outputDirectory: input.outputDirectory, sdkDirectory: cachedSdk, claudeBinary: cachedBinary, model: input.model }; + const output = execFileSync(process.execPath, ['--input-type=module', '-e', script, JSON.stringify([serializable, candidate, repo])], + { env: { PATH: '/usr/bin:/bin' }, encoding: 'utf8', timeout: 30_000, maxBuffer: 1024 * 1024 }); + const result = JSON.parse(output); + assert.equal(result.status, 'failed'); + assert.equal(result.failure, 'driver_failed'); + assert.ok(result.snapshot); + assert.equal(result.completion, null); + await assert.rejects(access(join(input.outputDirectory, 'completion.json'))); +}); + + +test('platform workflow ref aliases still require the exact immutable revision', async () => { + const h = await evidenceFixture(); + h.run.referenced_workflows[0].path = h.run.referenced_workflows[0].path.replace('@refs/heads/main', '@main'); + assert.equal((await composeAttemptEvidence(h.composeOptions)).status, 'matched'); +}); + + +test('successful SDK step cannot override failed job or unfinished/failed run attempt', async () => { + for (const mutate of [h => { h.job.conclusion = 'failure'; }, h => { h.job.conclusion = 'cancelled'; }, + h => { h.job.conclusion = 'skipped'; }, h => { h.run.status = 'in_progress'; }, + h => { h.run.conclusion = 'failure'; }, h => { h.run.conclusion = 'cancelled'; }]) { + const h = await evidenceFixture(); mutate(h); + const evidence = await composeAttemptEvidence(h.composeOptions); + assert.equal(evidence.status, 'unavailable'); + assert.equal(evidence.execution.execution, 'unknown'); + assert.equal(evidence.roundCompletion, 'unknown'); + } +}); + + +test('composition revalidates model summary and receipt against configured model', async t => { + const changes = { + summaryRequested: h => { h.envelope.completion.requestedModel = 'claude-opus-4-6'; }, + summaryResolved: h => { h.envelope.completion.resolvedModel = 'claude-opus-4-6'; }, + summaryUsage: h => { h.envelope.completion.usageModels = ['claude-opus-4-6']; }, + summaryAdditionalUsage: h => { h.envelope.completion.usageModels.push('claude-opus-4-6'); }, + configuredModel: h => { h.envelope.configured.model = 'claude-opus-4-6'; }, + configuredAlias: h => { h.envelope.configured.model = 'sonnet'; }, + receiptModel: async h => { + const file = join(h.input.outputDirectory, 'completion.json'); + const receipt = JSON.parse(await readFile(file)); + receipt.requestedModel = receipt.resolvedModel = 'claude-opus-4-6'; + receipt.usageModels = ['claude-opus-4-6']; + const bytes = Buffer.from(JSON.stringify(receipt)); + const { chmod } = await import('node:fs/promises'); await chmod(file, 0o600); + await writeFile(file, bytes); + Object.assign(h.envelope.completion, { sha256: hashBytes(bytes), bytes: bytes.length, + requestedModel: receipt.requestedModel, resolvedModel: receipt.resolvedModel, usageModels: receipt.usageModels }); + }, + }; + for (const [name, change] of Object.entries(changes)) await t.test(name, async () => { + const h = await evidenceFixture(); + await change(h); + const file = join(h.input.outputDirectory, 'envelope.json'); + 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); + await assert.rejects(composeAttemptEvidence(h.composeOptions), /completion_invalid|snapshot_binding/); + assert.equal(h.calls.length, 0); + await assert.rejects(access(h.composeOptions.outputPath)); + }); +});