Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions docs/reviewer-attempt-evidence.md
Original file line number Diff line number Diff line change
@@ -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.
45 changes: 45 additions & 0 deletions scripts/reviewer-attempt-evidence.mjs
Original file line number Diff line number Diff line change
@@ -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;
}
28 changes: 26 additions & 2 deletions scripts/reviewer-execution-receipt.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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];
Expand All @@ -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++) {
Expand Down
55 changes: 53 additions & 2 deletions scripts/reviewer-producer-run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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'
Expand All @@ -88,14 +104,15 @@ 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 {
const captured = await capture({ repository, pullRequest, expectedHead, expectedBase, outputPath: snapshotPath, readCandidate });
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';
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading