diff --git a/bin/proofline.mjs b/bin/proofline.mjs index ae5dda7..750f62d 100755 --- a/bin/proofline.mjs +++ b/bin/proofline.mjs @@ -13,7 +13,7 @@ import * as D from '../src/decompose.mjs'; const argv = process.argv.slice(2); const flags = {}; const pos = []; -const SWITCHES = ['fresh', 'check', 'lint-warn']; // never take a value: `verify --fresh T` keeps T as the task +const SWITCHES = ['fresh', 'check', 'lint-warn', 'isolated']; // never take a value: `verify --fresh T` keeps T as the task for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a.startsWith('--')) { const [k, v] = a.slice(2).split('='); if (v !== undefined) flags[k] = v; else if (!SWITCHES.includes(k) && argv[i + 1] && !argv[i + 1].startsWith('--')) flags[k] = argv[++i]; else flags[k] = true; } @@ -66,8 +66,10 @@ const HELP = `proofline: independent V&V and delivery controller --owner limits the lane; --base re-pins the base brief [--owner ] [--base ] brief for a task, with the base verify will use (refuses another owner's task) - verify [--claims "line"] [--base ] [--fresh] run every check independently; prints corrective prompt - gate |--all [--claims ...] [--base ] [--fresh] release decision PASS/FAIL/BLOCKED + report (.proofline/reports) + verify [--claims "line"] [--base ] [--fresh] [--isolated] + run every check independently; prints corrective prompt + gate |--all [--claims ...] [--base ] [--fresh] [--isolated] + release decision PASS/FAIL/BLOCKED + report (.proofline/reports) --base: the revision the task started from (needed in a fresh clone unless \`next\` pinned it or HEAD carries a Proofline-Base: trailer) --fresh: run every check again, ignoring PASS results reused under @@ -77,7 +79,7 @@ const HELP = `proofline: independent V&V and delivery controller evidence record --data '{..}' | evidence verify | evidence log verify-receipt [--keys ] [--sigstore] [--recompute --base ] exit 0 verified, 1 failed or differs, 2 unknown key, 3 usage - receipt [--role ] [--base ] [--out ] [--vault] + receipt [--role ] [--base ] [--out ] [--vault] [--isolated] contract receipt for a task; without , infer a zero-config receipt hook pre-commit|pre-push (used by git hooks) hook stop read a Stop hook payload on stdin; one receipt for new commits, or silence @@ -104,15 +106,15 @@ const ACCEPTED_FLAGS = { 'contract show': [], next: ['owner', 'base'], brief: ['owner', 'base'], - verify: ['claims', 'claims-file', 'base', 'fresh'], - gate: ['claims', 'claims-file', 'base', 'fresh', 'all', 'ci', 'skip-pushed'], + verify: ['claims', 'claims-file', 'base', 'fresh', 'isolated'], + gate: ['claims', 'claims-file', 'base', 'fresh', 'all', 'ci', 'skip-pushed', 'isolated'], report: [], status: ['owner'], 'evidence record': ['data'], 'evidence verify': [], 'evidence log': [], 'verify-receipt': ['keys', 'sigstore', 'recompute', 'base'], - receipt: ['base', 'role', 'task', 'out', 'vault'], + receipt: ['base', 'role', 'task', 'out', 'vault', 'isolated'], hook: [], watch: [], connect: [], @@ -243,7 +245,7 @@ try { } throw new Error('which task? (proofline next)'); } - const outs = ids.map((id) => P.E.gate(root, id, { claims: claims(), base: base(), fresh: flags.fresh === true, skipTypes: flags['skip-pushed'] || flags.ci ? ['pushed'] : [] })); + const outs = ids.map((id) => P.E.gate(root, id, { claims: claims(), base: base(), fresh: flags.fresh === true, isolated: flags.isolated === true, skipTypes: flags['skip-pushed'] || flags.ci ? ['pushed'] : [] })); const worst = outs.some((o) => o.decision === 'BLOCKED') ? 'BLOCKED' : outs.some((o) => o.decision === 'FAIL') ? 'FAIL' : 'PASS'; const note = settled ? `${settled.message}\n\n` : ''; print(outs.length === 1 ? outs[0] : { decision: worst, gates: outs.map((o) => ({ task: o.task, decision: o.decision, failing: o.failing, blocked: o.blocked })) }, @@ -271,6 +273,7 @@ try { break; } case 'receipt': { + if (!ownerGate(root)) break; if (flags.task === true || flags.role === true || flags.out === true || flags.base === true) throw new Error('receipt flags need values'); const task = typeof flags.task === 'string' ? flags.task : sub; const r = await buildReceipt(root, { @@ -279,9 +282,10 @@ try { task, out: flags.out === true ? undefined : flags.out, vault: flags.vault === true, + isolated: flags.isolated === true, }); print(r); - if (typeof task === 'string' && Number.isInteger(r.exitCode)) process.exitCode = r.exitCode; + if (Number.isInteger(r.exitCode)) process.exitCode = r.exitCode; break; } case 'hook': { diff --git a/proofline.json b/proofline.json index 1122ec1..b912556 100644 --- a/proofline.json +++ b/proofline.json @@ -25,7 +25,8 @@ "owners": [ "lane-a", "lane-b", - "lane-c" + "lane-c", + "lane-biz" ] }, "forbidden": { @@ -4030,9 +4031,11 @@ ] } , - {"id":"PL-SEED-01","title":"Validate Proofline's initial ICP","phase":"design","owner":"lane-c","depends_on":[],"requirements":[],"description":"Hypothesis: GitHub-first software teams already using coding agents experience material human validation burden on agent-authored pull requests. After approval, complete 15 consented interviews across at least 10 organizations within 30 days. Capture role, team size, agent use and agent-authored PR volume, validation time, review bottleneck, current controls and alternatives, buyer, budget owner, urgency, and purchase path. Anonymize notes, cite evidence for every claim, and include rejected ICPs. Business outcomes require owner attestation; an agent must not self-test or self-attest interview counts or buyer evidence.","scope":{"allow":["docs/seed/**"]},"criteria":[{"id":"PL-SEED-01-AC01","mandatory":true,"statement":"Interview protocol exists","verifier":{"type":"file_exists","path":"docs/seed/interview-protocol.md"}},{"id":"PL-SEED-01-AC02","mandatory":true,"statement":"Protocol records consent and anonymization rules","verifier":{"type":"grep","file":"docs/seed/interview-protocol.md","pattern":"consent","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC03","mandatory":true,"statement":"Protocol explains anonymization","verifier":{"type":"grep","file":"docs/seed/interview-protocol.md","pattern":"anonym","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC04","mandatory":true,"statement":"Evidence memo contains the interview counts table","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Organizations interviewed","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC05","mandatory":true,"statement":"Evidence memo distinguishes observed facts from hypotheses","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Observed facts","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC06","mandatory":true,"statement":"Evidence memo labels hypotheses separately","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Hypotheses","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC07","mandatory":true,"statement":"Evidence memo names rejected ICPs","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Rejected ICPs","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC08","mandatory":true,"statement":"Evidence memo records buyer and budget-owner findings","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Budget owner","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC09","mandatory":true,"statement":"The owner signs (owner key, verified against guard/owner.pub) the actual counts: at least 10 organizations, 6 current coding-agent users, and 5 with a quantified validation bottleneck and an accountable budget owner. An agent cannot produce this signature.","verifier":{"type":"command","cmd":"node --input-type=module -e \"import fs from \\\"node:fs\\\"; import { verifyDSSE } from \\\"@optitransfer/agentkey\\\"; try { const e = JSON.parse(fs.readFileSync(\\\"docs/seed/owner-attestation.dsse.json\\\", \\\"utf8\\\")); const r = verifyDSSE(e, [fs.readFileSync(\\\"guard/owner.pub\\\", \\\"utf8\\\")]); const s = JSON.parse(Buffer.from(r.payload).toString()); process.exit(r.ok && s.task === \\\"PL-SEED-01\\\" ? 0 : 1); } catch { process.exit(1); }\"","expect_exit":0,"timeout_s":60}},{"id":"PL-SEED-01-AC10","mandatory":true,"statement":"Claims ledger exists and links claims to sources or marks them as hypotheses","verifier":{"type":"file_exists","path":"docs/seed/claims-ledger.md"}},{"id":"PL-SEED-01-AC11","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-SEED-01-AC12","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not begin interviews until the owner approves this task.","Do not present hypotheses or a small interview sample as measured market facts or a representative market estimate.","If the stated interview thresholds are missed, report the actual count and evidence; do not lower the threshold."]}, - {"id":"PL-SEED-02","title":"Build the GitHub pull request check","phase":"implement","owner":"lane-c","depends_on":["PL-SEED-01"],"requirements":[],"description":"After the ICP is validated and this task is approved, build the first GitHub integration. Run the repository-selected Proofline task, expose the exact result and failure reason as a required PR check, and attach or link its evidence receipt. Prefer the pull_request event and a read-only contents permission; do not use pull_request_target, secrets in fork PR workflows, or privileged execution of untrusted code. The fixture repository must demonstrate both green and red checks, including a planted verifier fault that stays red. Document the permission and fork model. Obtain owner-attested confirmation from two ICP design partners that this check fits their merge workflow; that business outcome is not an agent-run test.","scope":{"allow":["src/**","bin/**","test/**","docs/integrations/**",".github/**","package.json"]},"criteria":[{"id":"PL-SEED-02-AC01","mandatory":true,"statement":"Fixture-repository tests show green for passing criteria and red for failing criteria; a planted verifier fault never produces a green check","verifier":{"type":"test_red_green","test_file":"test/github_check.test.mjs","cmd":"node --test {test}"}},{"id":"PL-SEED-02-AC02","mandatory":true,"statement":"Full suite exits 0","verifier":{"type":"command","cmd":"npm test","expect_exit":0}},{"id":"PL-SEED-02-AC03","mandatory":true,"statement":"GitHub pull-request workflow exists","verifier":{"type":"file_exists","path":".github/workflows/proofline.yml"}},{"id":"PL-SEED-02-AC04","mandatory":true,"statement":"GitHub workflow does not use pull_request_target","verifier":{"type":"command","cmd":"! grep -R -n pull_request_target .github/workflows","expect_exit":0}},{"id":"PL-SEED-02-AC05","mandatory":true,"statement":"Workflow uses the pull_request event","verifier":{"type":"grep","file":".github/workflows/proofline.yml","pattern":"pull_request:","must":"present"}},{"id":"PL-SEED-02-AC06","mandatory":true,"statement":"Integration guide documents least-privilege permissions","verifier":{"type":"grep","file":"docs/integrations/github-check.md","pattern":"permissions","flags":"i","must":"present"}},{"id":"PL-SEED-02-AC07","mandatory":true,"statement":"Integration guide documents read-only contents access and fork handling","verifier":{"type":"grep","file":"docs/integrations/github-check.md","pattern":"contents: read","flags":"i","must":"present"}},{"id":"PL-SEED-02-AC08","mandatory":true,"statement":"Integration guide explains fork-PR security and setup of the required check","verifier":{"type":"grep","file":"docs/integrations/github-check.md","pattern":"fork","flags":"i","must":"present"}},{"id":"PL-SEED-02-AC09","mandatory":true,"statement":"The owner signs (owner key, verified against guard/owner.pub) that two ICP design partners confirmed the check fits their merge workflow. An agent cannot produce this signature.","verifier":{"type":"command","cmd":"node --input-type=module -e \"import fs from \\\"node:fs\\\"; import { verifyDSSE } from \\\"@optitransfer/agentkey\\\"; try { const e = JSON.parse(fs.readFileSync(\\\"docs/integrations/design-partner-attestation.dsse.json\\\", \\\"utf8\\\")); const r = verifyDSSE(e, [fs.readFileSync(\\\"guard/owner.pub\\\", \\\"utf8\\\")]); const s = JSON.parse(Buffer.from(r.payload).toString()); process.exit(r.ok && s.task === \\\"PL-SEED-02\\\" ? 0 : 1); } catch { process.exit(1); }\"","expect_exit":0,"timeout_s":60}},{"id":"PL-SEED-02-AC10","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-SEED-02-AC11","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not implement until PL-SEED-01 is approved and complete and the owner approves this task.","Never execute untrusted pull-request code with elevated permissions or expose secrets to fork pull requests.","A failed verifier must never produce a passing required check; report any missing GitHub environment as blocked."]}, - {"id":"PL-SEED-03","title":"Prove willingness to pay with pilots","phase":"design","owner":"lane-c","depends_on":["PL-SEED-02"],"requirements":[],"description":"After the GitHub check is approved and validated and the owner approves this task, run a 30-day paid pilot. Pre-register baselines and measures for human validation minutes per agent-authored PR, missed acceptance criteria, false blocks, false verified results on seeded negatives, setup time, CI latency, usage, and willingness to pay. Targets are hypotheses until measured: three decision-maker-approved protocols, two paid commitments with price and start date, at least 20 percent lower median validation time, false-block rate below 5 percent, zero false verified seeded negatives, and under two minutes of added CI latency per PR. The owner, not the agent or its tests, attests protocol approvals, signed paid commitments, prices, dates, and actual commercial outcomes.","scope":{"allow":["docs/seed/**","docs/pilots/**"]},"criteria":[{"id":"PL-SEED-03-AC01","mandatory":true,"statement":"Pilot protocol documents informed consent, a baseline, data minimization, and retention limits","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"consent","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC02","mandatory":true,"statement":"Protocol explicitly documents anonymization and data minimization","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"anonym","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC03","mandatory":true,"statement":"Protocol documents data retention limits","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"retention","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC04","mandatory":true,"statement":"Protocol defines a baseline and post-integration measurements","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"baseline","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC05","mandatory":true,"statement":"Protocol pre-registers validation-time, false-block, false-verified, and CI-latency measures and targets","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"validation minutes","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC06","mandatory":true,"statement":"Pilot evidence ledger exists","verifier":{"type":"file_exists","path":"docs/pilots/evidence-ledger.md"}},{"id":"PL-SEED-03-AC07","mandatory":true,"statement":"Evidence ledger contains a pilot counts table","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Teams participating","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC08","mandatory":true,"statement":"Evidence ledger separates observed facts from hypotheses","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Observed facts","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC09","mandatory":true,"statement":"Evidence ledger labels hypotheses separately","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Hypotheses","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC10","mandatory":true,"statement":"Evidence ledger records methods, target comparisons, and limitations","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Limitations","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC11","mandatory":true,"statement":"Seed claims ledger exists and links every commercial claim to evidence or labels it as a hypothesis","verifier":{"type":"file_exists","path":"docs/seed/claims-ledger.md"}},{"id":"PL-SEED-03-AC12","mandatory":true,"statement":"The owner signs (owner key, verified against guard/owner.pub) at least three approved pilot protocols and at least two signed paid commitments with price and start date. An agent cannot produce this signature.","verifier":{"type":"command","cmd":"node --input-type=module -e \"import fs from \\\"node:fs\\\"; import { verifyDSSE } from \\\"@optitransfer/agentkey\\\"; try { const e = JSON.parse(fs.readFileSync(\\\"docs/pilots/owner-attestation.dsse.json\\\", \\\"utf8\\\")); const r = verifyDSSE(e, [fs.readFileSync(\\\"guard/owner.pub\\\", \\\"utf8\\\")]); const s = JSON.parse(Buffer.from(r.payload).toString()); process.exit(r.ok && s.task === \\\"PL-SEED-03\\\" ? 0 : 1); } catch { process.exit(1); }\"","expect_exit":0,"timeout_s":60}},{"id":"PL-SEED-03-AC13","mandatory":true,"statement":"Claims ledger cites sources and clearly labels measured outcomes versus hypotheses","verifier":{"type":"grep","file":"docs/seed/claims-ledger.md","pattern":"Hypothes","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC14","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-SEED-03-AC15","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not contact pilot customers, collect pilot data, or make commercial claims until PL-SEED-02 is approved and complete and the owner approves this task.","Do not retain customer source code or secrets; minimize and anonymize collected data.","Report measured outcomes, sample sizes, limitations, and misses; never pass a target by attestation or alter a target after measurement."]}], + {"id":"PL-SEED-01","title":"Validate Proofline's initial ICP","phase":"design","owner":"lane-biz","depends_on":[],"requirements":[],"description":"Hypothesis: GitHub-first software teams already using coding agents experience material human validation burden on agent-authored pull requests. After approval, complete 15 consented interviews across at least 10 organizations within 30 days. Capture role, team size, agent use and agent-authored PR volume, validation time, review bottleneck, current controls and alternatives, buyer, budget owner, urgency, and purchase path. Anonymize notes, cite evidence for every claim, and include rejected ICPs. Business outcomes require owner attestation; an agent must not self-test or self-attest interview counts or buyer evidence.","scope":{"allow":["docs/seed/**"]},"criteria":[{"id":"PL-SEED-01-AC01","mandatory":true,"statement":"Interview protocol exists","verifier":{"type":"file_exists","path":"docs/seed/interview-protocol.md"}},{"id":"PL-SEED-01-AC02","mandatory":true,"statement":"Protocol records consent and anonymization rules","verifier":{"type":"grep","file":"docs/seed/interview-protocol.md","pattern":"consent","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC03","mandatory":true,"statement":"Protocol explains anonymization","verifier":{"type":"grep","file":"docs/seed/interview-protocol.md","pattern":"anonym","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC04","mandatory":true,"statement":"Evidence memo contains the interview counts table","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Organizations interviewed","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC05","mandatory":true,"statement":"Evidence memo distinguishes observed facts from hypotheses","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Observed facts","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC06","mandatory":true,"statement":"Evidence memo labels hypotheses separately","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Hypotheses","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC07","mandatory":true,"statement":"Evidence memo names rejected ICPs","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Rejected ICPs","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC08","mandatory":true,"statement":"Evidence memo records buyer and budget-owner findings","verifier":{"type":"grep","file":"docs/seed/icp-evidence.md","pattern":"Budget owner","flags":"i","must":"present"}},{"id":"PL-SEED-01-AC09","mandatory":true,"statement":"The owner signs (owner key, verified against guard/owner.pub) the actual counts: at least 10 organizations, 6 current coding-agent users, and 5 with a quantified validation bottleneck and an accountable budget owner. An agent cannot produce this signature.","verifier":{"type":"command","cmd":"node --input-type=module -e \"import fs from \\\"node:fs\\\"; import { verifyDSSE } from \\\"@optitransfer/agentkey\\\"; try { const e = JSON.parse(fs.readFileSync(\\\"docs/seed/owner-attestation.dsse.json\\\", \\\"utf8\\\")); const r = verifyDSSE(e, [fs.readFileSync(\\\"guard/owner.pub\\\", \\\"utf8\\\")]); const s = JSON.parse(Buffer.from(r.payload).toString()); process.exit(r.ok && s.task === \\\"PL-SEED-01\\\" ? 0 : 1); } catch { process.exit(1); }\"","expect_exit":0,"timeout_s":60}},{"id":"PL-SEED-01-AC10","mandatory":true,"statement":"Claims ledger exists and links claims to sources or marks them as hypotheses","verifier":{"type":"file_exists","path":"docs/seed/claims-ledger.md"}},{"id":"PL-SEED-01-AC11","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-SEED-01-AC12","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not begin interviews until the owner approves this task.","Do not present hypotheses or a small interview sample as measured market facts or a representative market estimate.","If the stated interview thresholds are missed, report the actual count and evidence; do not lower the threshold."]}, + {"id":"PL-SEED-02","title":"Build the GitHub pull request check","phase":"implement","owner":"lane-biz","depends_on":["PL-SEED-01"],"requirements":[],"description":"After the ICP is validated and this task is approved, build the first GitHub integration. Run the repository-selected Proofline task, expose the exact result and failure reason as a required PR check, and attach or link its evidence receipt. Prefer the pull_request event and a read-only contents permission; do not use pull_request_target, secrets in fork PR workflows, or privileged execution of untrusted code. The fixture repository must demonstrate both green and red checks, including a planted verifier fault that stays red. Document the permission and fork model. Obtain owner-attested confirmation from two ICP design partners that this check fits their merge workflow; that business outcome is not an agent-run test.","scope":{"allow":["src/**","bin/**","test/**","docs/integrations/**",".github/**","package.json"]},"criteria":[{"id":"PL-SEED-02-AC01","mandatory":true,"statement":"Fixture-repository tests show green for passing criteria and red for failing criteria; a planted verifier fault never produces a green check","verifier":{"type":"test_red_green","test_file":"test/github_check.test.mjs","cmd":"node --test {test}"}},{"id":"PL-SEED-02-AC02","mandatory":true,"statement":"Full suite exits 0","verifier":{"type":"command","cmd":"npm test","expect_exit":0}},{"id":"PL-SEED-02-AC03","mandatory":true,"statement":"GitHub pull-request workflow exists","verifier":{"type":"file_exists","path":".github/workflows/proofline.yml"}},{"id":"PL-SEED-02-AC04","mandatory":true,"statement":"GitHub workflow does not use pull_request_target","verifier":{"type":"command","cmd":"! grep -R -n pull_request_target .github/workflows","expect_exit":0}},{"id":"PL-SEED-02-AC05","mandatory":true,"statement":"Workflow uses the pull_request event","verifier":{"type":"grep","file":".github/workflows/proofline.yml","pattern":"pull_request:","must":"present"}},{"id":"PL-SEED-02-AC06","mandatory":true,"statement":"Integration guide documents least-privilege permissions","verifier":{"type":"grep","file":"docs/integrations/github-check.md","pattern":"permissions","flags":"i","must":"present"}},{"id":"PL-SEED-02-AC07","mandatory":true,"statement":"Integration guide documents read-only contents access and fork handling","verifier":{"type":"grep","file":"docs/integrations/github-check.md","pattern":"contents: read","flags":"i","must":"present"}},{"id":"PL-SEED-02-AC08","mandatory":true,"statement":"Integration guide explains fork-PR security and setup of the required check","verifier":{"type":"grep","file":"docs/integrations/github-check.md","pattern":"fork","flags":"i","must":"present"}},{"id":"PL-SEED-02-AC09","mandatory":true,"statement":"The owner signs (owner key, verified against guard/owner.pub) that two ICP design partners confirmed the check fits their merge workflow. An agent cannot produce this signature.","verifier":{"type":"command","cmd":"node --input-type=module -e \"import fs from \\\"node:fs\\\"; import { verifyDSSE } from \\\"@optitransfer/agentkey\\\"; try { const e = JSON.parse(fs.readFileSync(\\\"docs/integrations/design-partner-attestation.dsse.json\\\", \\\"utf8\\\")); const r = verifyDSSE(e, [fs.readFileSync(\\\"guard/owner.pub\\\", \\\"utf8\\\")]); const s = JSON.parse(Buffer.from(r.payload).toString()); process.exit(r.ok && s.task === \\\"PL-SEED-02\\\" ? 0 : 1); } catch { process.exit(1); }\"","expect_exit":0,"timeout_s":60}},{"id":"PL-SEED-02-AC10","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-SEED-02-AC11","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not implement until PL-SEED-01 is approved and complete and the owner approves this task.","Never execute untrusted pull-request code with elevated permissions or expose secrets to fork pull requests.","A failed verifier must never produce a passing required check; report any missing GitHub environment as blocked."]}, + {"id":"PL-SEED-03","title":"Prove willingness to pay with pilots","phase":"design","owner":"lane-biz","depends_on":["PL-SEED-02"],"requirements":[],"description":"After the GitHub check is approved and validated and the owner approves this task, run a 30-day paid pilot. Pre-register baselines and measures for human validation minutes per agent-authored PR, missed acceptance criteria, false blocks, false verified results on seeded negatives, setup time, CI latency, usage, and willingness to pay. Targets are hypotheses until measured: three decision-maker-approved protocols, two paid commitments with price and start date, at least 20 percent lower median validation time, false-block rate below 5 percent, zero false verified seeded negatives, and under two minutes of added CI latency per PR. The owner, not the agent or its tests, attests protocol approvals, signed paid commitments, prices, dates, and actual commercial outcomes.","scope":{"allow":["docs/seed/**","docs/pilots/**"]},"criteria":[{"id":"PL-SEED-03-AC01","mandatory":true,"statement":"Pilot protocol documents informed consent, a baseline, data minimization, and retention limits","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"consent","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC02","mandatory":true,"statement":"Protocol explicitly documents anonymization and data minimization","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"anonym","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC03","mandatory":true,"statement":"Protocol documents data retention limits","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"retention","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC04","mandatory":true,"statement":"Protocol defines a baseline and post-integration measurements","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"baseline","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC05","mandatory":true,"statement":"Protocol pre-registers validation-time, false-block, false-verified, and CI-latency measures and targets","verifier":{"type":"grep","file":"docs/pilots/protocol.md","pattern":"validation minutes","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC06","mandatory":true,"statement":"Pilot evidence ledger exists","verifier":{"type":"file_exists","path":"docs/pilots/evidence-ledger.md"}},{"id":"PL-SEED-03-AC07","mandatory":true,"statement":"Evidence ledger contains a pilot counts table","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Teams participating","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC08","mandatory":true,"statement":"Evidence ledger separates observed facts from hypotheses","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Observed facts","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC09","mandatory":true,"statement":"Evidence ledger labels hypotheses separately","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Hypotheses","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC10","mandatory":true,"statement":"Evidence ledger records methods, target comparisons, and limitations","verifier":{"type":"grep","file":"docs/pilots/evidence-ledger.md","pattern":"Limitations","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC11","mandatory":true,"statement":"Seed claims ledger exists and links every commercial claim to evidence or labels it as a hypothesis","verifier":{"type":"file_exists","path":"docs/seed/claims-ledger.md"}},{"id":"PL-SEED-03-AC12","mandatory":true,"statement":"The owner signs (owner key, verified against guard/owner.pub) at least three approved pilot protocols and at least two signed paid commitments with price and start date. An agent cannot produce this signature.","verifier":{"type":"command","cmd":"node --input-type=module -e \"import fs from \\\"node:fs\\\"; import { verifyDSSE } from \\\"@optitransfer/agentkey\\\"; try { const e = JSON.parse(fs.readFileSync(\\\"docs/pilots/owner-attestation.dsse.json\\\", \\\"utf8\\\")); const r = verifyDSSE(e, [fs.readFileSync(\\\"guard/owner.pub\\\", \\\"utf8\\\")]); const s = JSON.parse(Buffer.from(r.payload).toString()); process.exit(r.ok && s.task === \\\"PL-SEED-03\\\" ? 0 : 1); } catch { process.exit(1); }\"","expect_exit":0,"timeout_s":60}},{"id":"PL-SEED-03-AC13","mandatory":true,"statement":"Claims ledger cites sources and clearly labels measured outcomes versus hypotheses","verifier":{"type":"grep","file":"docs/seed/claims-ledger.md","pattern":"Hypothes","flags":"i","must":"present"}},{"id":"PL-SEED-03-AC14","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-SEED-03-AC15","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not contact pilot customers, collect pilot data, or make commercial claims until PL-SEED-02 is approved and complete and the owner approves this task.","Do not retain customer source code or secrets; minimize and anonymize collected data.","Report measured outcomes, sample sizes, limitations, and misses; never pass a target by attestation or alter a target after measurement."]}, + {"id":"PL-PROD-01","title":"Make the verifier and clean install production safe","phase":"implement","owner":"lane-c","depends_on":["PL-02"],"requirements":[],"description":"Close the confirmed release blockers before broad promotion. Fail closed on command timeouts, failed metric processes, base setup failures/timeouts, diff errors, mixed named/unnamed push stacks, and out-of-scope renames. Enforce owner-signature policy before every MCP/CLI execution path. Prevent self-declared L2 receipts, bind receipt signer identity, reject repository snapshot drift, constrain MCP receipt output paths, preserve zero-config exit codes, expose the documented CLI isolation flag, serialize evidence writes, and regenerate the production lockfile. Make the documented first-run path match the actual CLI and add clean-install and guided end-to-end coverage.","scope":{"allow":["src/**","bin/**","test/**","docs/**","README.md","CHANGELOG.md","CONTRIBUTING.md","package.json","package-lock.json"]},"criteria":[{"id":"PL-PROD-01-AC01","mandatory":true,"statement":"Verifier regression tests prove timeouts, failed metrics, base setup failures, diff failures, mixed push stacks, and outside-to-inside renames never produce PASS","verifier":{"type":"test_red_green","test_file":"test/verifier_fail_closed.test.mjs","cmd":"node --test {test}"}},{"id":"PL-PROD-01-AC02","mandatory":true,"statement":"Trust-boundary regression tests prove MCP/CLI signature parity before execution, reject self-declared L2 and signer mismatches, block snapshot drift, and confine MCP output paths","verifier":{"type":"test_red_green","test_file":"test/trust_boundary.test.mjs","cmd":"node --test {test}"}},{"id":"PL-PROD-01-AC03","mandatory":true,"statement":"CLI regression tests prove zero-config exit propagation, documented isolation forwarding, and consistent boolean/global flag arity","verifier":{"type":"test_red_green","test_file":"test/cli_contract.test.mjs","cmd":"node --test {test}"}},{"id":"PL-PROD-01-AC04","mandatory":true,"statement":"Concurrent evidence writers preserve an intact hash chain and latest-report writes are atomic","verifier":{"type":"test_red_green","test_file":"test/evidence_concurrent.test.mjs","cmd":"node --test {test}"}},{"id":"PL-PROD-01-AC05","mandatory":true,"statement":"A clean production install retains the runtime signing dependency and the packed tarball completes the documented first-run path","verifier":{"type":"test_red_green","test_file":"test/release_install.test.mjs","cmd":"node --test {test}"}},{"id":"PL-PROD-01-AC06","mandatory":true,"statement":"README and current documentation distinguish implemented behavior from future design and no longer advertise unavailable flags or zero runtime dependencies","verifier":{"type":"grep","file":"README.md","pattern":"Current capabilities","must":"present"}},{"id":"PL-PROD-01-AC07","mandatory":true,"statement":"Full suite exits 0","verifier":{"type":"command","cmd":"npm test","expect_exit":0,"timeout_s":1800}},{"id":"PL-PROD-01-AC08","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-PROD-01-AC09","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not weaken, skip, or remove an existing test or assertion, and do not bypass hooks or owner-signature checks.","Do not claim production readiness, marketplace publication, customers, or adoption until the corresponding evidence exists.","If a required external permission or publication account is unavailable, report BLOCKED with the exact missing item."]}, + {"id":"PL-DIST-01","title":"Publish a safe reusable GitHub pull request check","phase":"implement","owner":"lane-c","depends_on":["PL-PROD-01"],"requirements":[],"description":"Package the validated PR check as one reusable public GitHub Action with exactly one root action metadata file. A consumer adds one workflow step and receives a required PASS/FAIL/BLOCKED result, the first actionable failure, exact base/head revisions, and sanitized report/receipt links. Use the job status for fork PRs, never pull_request_target, no secrets by default, no telemetry by default, and no unsolicited PR comments. Include a public seeded-failure demo, stable versioned usage, Marketplace metadata and release checklist, and a truthful directory-submission ledger. Marketplace publication requires the owner's Developer Agreement, release, and 2FA; directory submissions are recorded only with their actual status.","scope":{"allow":["action.yml","src/**","bin/**","test/**","docs/integrations/**","docs/distribution/**",".github/**","README.md","CHANGELOG.md","package.json","package-lock.json"]},"criteria":[{"id":"PL-DIST-01-AC01","mandatory":true,"statement":"A parser test proves exactly one root action metadata file declares a unique name, description, inputs, outputs, runs, and branding","verifier":{"type":"test_red_green","test_file":"test/action_metadata.test.mjs","cmd":"node --test {test}"}},{"id":"PL-DIST-01-AC02","mandatory":true,"statement":"Consumer fixture tests demonstrate green, red, blocked, fork-safe, and planted-verifier-fault outcomes with a Proofline-linked summary and exact revisions","verifier":{"type":"test_red_green","test_file":"test/github_action.test.mjs","cmd":"node --test {test}"}},{"id":"PL-DIST-01-AC03","mandatory":true,"statement":"A parser test proves no workflow uses pull_request_target and every non-local uses entry ends at @ followed by exactly 40 lowercase hex characters","verifier":{"type":"test_red_green","test_file":"test/action_pins.test.mjs","cmd":"node --test {test}"}},{"id":"PL-DIST-01-AC04","mandatory":true,"statement":"Integration guide contains least-privilege permissions, fork behavior, sanitized artifacts, required-check installation, and a stable versioned example without @next","verifier":{"type":"grep","file":"docs/integrations/github.md","pattern":"Permissions[\\s\\S]*Fork pull requests[\\s\\S]*Sanitized artifacts[\\s\\S]*Required check","must":"present"}},{"id":"PL-DIST-01-AC05","mandatory":true,"statement":"Distribution ledger records real channel URLs, submission status, evidence, and dates without claiming unverified listings or adoption","verifier":{"type":"grep","file":"docs/distribution/channels.md","pattern":"Channel[\\s\\S]*Status[\\s\\S]*Evidence[\\s\\S]*Date","must":"present"}},{"id":"PL-DIST-01-AC06","mandatory":true,"statement":"The owner signs the actual Marketplace agreement, tagged release, 2FA, and publication state with the owner key; an agent cannot produce this signature","verifier":{"type":"command","cmd":"node --input-type=module -e \"import fs from \\\"node:fs\\\"; import { verifyDSSE } from \\\"@optitransfer/agentkey\\\"; try { const e = JSON.parse(fs.readFileSync(\\\"docs/distribution/owner-attestation.dsse.json\\\", \\\"utf8\\\")); const r = verifyDSSE(e, [fs.readFileSync(\\\"guard/owner.pub\\\", \\\"utf8\\\")]); const s = JSON.parse(Buffer.from(r.payload).toString()); process.exit(r.ok && s.task === \\\"PL-DIST-01\\\" ? 0 : 1); } catch { process.exit(1); }\"","expect_exit":0}},{"id":"PL-DIST-01-AC07","mandatory":true,"statement":"Full suite exits 0","verifier":{"type":"command","cmd":"npm test","expect_exit":0,"timeout_s":1800}},{"id":"PL-DIST-01-AC08","mandatory":true,"statement":"Changes stay in scope","verifier":{"type":"scope"}},{"id":"PL-DIST-01-AC09","mandatory":true,"statement":"Committed and pushed to main","verifier":{"type":"pushed"}}],"stop_rules":["Do not weaken, skip, or remove an existing test or assertion, and do not bypass hooks or owner-signature checks.","Do not claim production readiness, marketplace publication, customers, or adoption until the corresponding evidence exists.","If a required external permission or publication account is unavailable, report BLOCKED with the exact missing item."]}], "notes": "Each task carries the requirement ids it covers; next --owner hands out the tasks of one owner. Cross-repository needs are written into task text as an external dependency and reported BLOCKED when absent. PL-SELF stays: proofline verifies itself with its own contract. | 2026-10-17: 15 review tasks appended (COVERAGE.md maps every finding and open issue). Scope criterion added to PL-SELF, DG-PL so the contract passes its own validator. | 2026-10-17: PL-SETUP01 (setup pins the owner key) and PL-NEXT1 (0.2.0-next.1 carries the bin) appended. | 2026-10-20: PL-CRIT01 (crit: claims for tasks proved by a command; leading (?i)/(?s) grep flags) and PL-NEXT2 (0.2.0-next.2) appended.", "ci": { "tasks": [ diff --git a/proofline.json.sig b/proofline.json.sig index 611474a..2a39237 100644 --- a/proofline.json.sig +++ b/proofline.json.sig @@ -1 +1 @@ -{"payloadType":"application/vnd.proofline.contract-sha256","payload":"YzI2YTJhMzcxZjc1OTdjMjdlNmNmYmVkMzA2MGRiM2QyNzViNWJmN2M0Y2VkYjg1YWFiYmE1MzNlYmM1Zjg5Mw==","signatures":[{"keyid":"kb71a7ce9e7b76859","sig":"mhMJiYkyOgLN8CEuU/zZnAeF48dLppmdPrHrzuLOHusj6zUmNwAosFn6BLqsCHEy1cWohuqcLZpuwi7SQxd2Aw=="}]} +{"payloadType":"application/vnd.proofline.contract-sha256","payload":"NjhkN2IwMmU3YWQwOWRhOGNkZGM1ODdkOWEyNTE4NmMxMmZjZjY0YTIzOTVhOWI2MmEzODgwMTVjZWY3ODY4Nw==","signatures":[{"keyid":"kb71a7ce9e7b76859","sig":"CwL/gN0V4Z8Ejss9NtUFUWUUFfr1cai4huMu0x0QHn/PQSjUqtfJfOmlai5g27U9mfhCKMaA8Tq0eYGd11IvCA=="}]} diff --git a/src/checks.mjs b/src/checks.mjs index 003b645..daf210c 100644 --- a/src/checks.mjs +++ b/src/checks.mjs @@ -23,22 +23,39 @@ export function resolveBase(root, ref) { return r.ok ? r.out : null; } -/** Changed files between base and the working tree (tracked + untracked). */ +function requiredGit(r, label) { + if (!r.ok) throw new Error(`${label} failed${r.err ? `: ${r.err}` : ''}`); + return r; +} + +function nulPaths(raw, label) { + const fields = raw.split('\0'); + if (fields.at(-1) === '') fields.pop(); + if (fields.some((f) => !f)) throw new Error(`${label} failed: malformed or truncated NUL-delimited output`); + return fields; +} + +/** Changed files between base and the working tree (tracked + untracked). Renames and copies retain both paths. */ export function changedFiles(root, base) { const out = new Map(); - const d = git(['diff', '--name-status', '-M', base, '--'], root); - for (const l of d.out.split('\n').filter(Boolean)) { - const [st, a, b] = l.split('\t'); - out.set(b || a, st[0]); + const d = requiredGit(git(['diff', '--name-status', '-M', '-C', '--find-copies-harder', '-z', base, '--'], root), 'git diff --name-status'); + const fields = nulPaths(d.raw, 'git diff --name-status'); + for (let i = 0; i < fields.length;) { + const st = fields[i++]; + const count = /^[RC]/.test(st) ? 2 : 1; + if (i + count > fields.length) throw new Error('git diff --name-status failed: truncated rename/copy record'); + const paths = fields.slice(i, i + count); i += count; + for (const f of paths) out.set(f, st[0]); } - for (const f of git(['ls-files', '--others', '--exclude-standard'], root).out.split('\n').filter(Boolean)) out.set(f, 'A'); + const untracked = requiredGit(git(['ls-files', '--others', '--exclude-standard', '-z'], root), 'git ls-files'); + for (const f of nulPaths(untracked.raw, 'git ls-files')) out.set(f, 'A'); for (const f of [...out.keys()]) if (f.startsWith('.proofline/')) out.delete(f); return out; } /** Parse a unified diff (-U0) into per-file hunks of added/removed lines. */ export function diffHunks(root, base) { - const d = git(['diff', '-U0', base, '--'], root).out; + const d = requiredGit(git(['diff', '-U0', base, '--'], root), 'git diff -U0').raw; const files = []; let cur = null, hunk = null; for (const l of d.split('\n')) { @@ -50,7 +67,8 @@ export function diffHunks(root, base) { if (l[0] === '+') hunk.add.push(l.slice(1)); else if (l[0] === '-') hunk.del.push(l.slice(1)); } // untracked files count as fully added - for (const f of git(['ls-files', '--others', '--exclude-standard'], root).out.split('\n').filter(Boolean)) { + const untracked = requiredGit(git(['ls-files', '--others', '--exclude-standard', '-z'], root), 'git ls-files'); + for (const f of nulPaths(untracked.raw, 'git ls-files')) { if (f.startsWith('.proofline/')) continue; let txt = ''; try { txt = fs.readFileSync(path.join(root, f), 'utf8'); } catch {} files.push({ file: f, hunks: [{ add: txt.split('\n'), del: [] }] }); @@ -107,6 +125,7 @@ export const verifiers = { const expect = v.expect_exit ?? 0; let r = runCounted(v.cmd, ctx.root, v, ctx); const first = ev(r), firstExit = r.exit; + if (r.timedOut) return { status: 'fail', detail: `command timed out after ${v.timeout_s || 900}s; a timeout is never a pass, including when expect_exit is 124`, evidence: first }; if (r.exit === 127) return { status: 'error', detail: `command not found: ${v.cmd}`, evidence: first }; const tooMany = (r2) => { const c = r2.counts; const p = []; @@ -120,6 +139,7 @@ export const verifiers = { // Both runs keep their failing names: on a flaky result the first run's list is the tests that flapped. for (let i = 0; i < (ctx.flakyReruns ?? 1); i++) { r = runCounted(v.cmd, ctx.root, v, ctx); + if (r.timedOut) return { status: 'fail', detail: `command timed out on re-run ${i + 1}; a timeout is never a pass`, evidence: { first, rerun: ev(r) } }; if (r.exit === expect && !tooMany(r).length) return { status: 'flaky', detail: `failed (exit ${firstExit}${named(first) ? `; ${named(first)}` : ''}) then passed on re-run ${i + 1}: flaky, not a pass. Root-cause the non-determinism.`, evidence: { first, rerun: ev(r) } }; } const rerun = ev(r), n = named(rerun.failing.length ? rerun : first); @@ -150,11 +170,13 @@ export const verifiers = { fs.mkdirSync(path.dirname(path.join(wt, f)), { recursive: true }); fs.copyFileSync(path.join(ctx.root, f), path.join(wt, f)); } - if (v.setup) run(v.setup, { cwd: wt, timeoutS: 900 }); + const setup = v.setup ? run(v.setup, { cwd: wt, timeoutS: 900 }) : null; + if (setup && (setup.timedOut || setup.exit !== 0)) return { status: 'error', detail: `base setup ${setup.timedOut ? 'timed out' : `failed (exit ${setup.exit})`}; red-green is inconclusive`, evidence: { base: ctx.base, setup: ev(setup) } }; const cmd = sub(v.cmd, { test: v.test_file, name: v.test_name || '' }); const red = runCounted(cmd, wt, v, ctx); const green = runCounted(cmd, ctx.root, v, ctx); - const evd = { base: ctx.base, red: ev(red), green: ev(green) }; + const evd = { base: ctx.base, ...(setup ? { setup: ev(setup) } : {}), red: ev(red), green: ev(green) }; + if (red.timedOut) return { status: 'error', detail: 'base test command timed out; red-green is inconclusive', evidence: evd }; if (red.exit === 127 || green.exit === 127) return { status: 'error', detail: 'test command not found', evidence: evd }; if (red.exit === 0) return { status: 'fail', detail: `test PASSES on base ${ctx.base.slice(0, 8)} without the change: it does not prove the change (tests how, not what?)`, evidence: evd }; if (green.exit !== 0) return { status: 'fail', detail: `test fails on the current tree (exit ${green.exit})`, evidence: evd }; @@ -183,11 +205,12 @@ export const verifiers = { })(); const on = `load ${machine.load1.toFixed(2)} / ${machine.cpus} CPUs, node ${machine.node || 'not found'}`; if (!r) return { status: 'blocked', detail: `machine busy: load ${machine.load1.toFixed(2)} over ${machine.cpus} CPUs = ${machine.load_per_cpu.toFixed(2)} per CPU > max_load_per_cpu ${max}; the bench was not run. Re-run when the machine is idle.`, evidence: { cmd: v.cmd, machine } }; + const e = { cmd: v.cmd, exit: r.exit, ms: r.ms, timedOut: r.timedOut, machine, out_tail: tail(r.stdout + r.stderr, 800) }; + if (r.exit === 127) return { status: 'error', detail: `bench command not found: ${v.cmd} (is the bench rig committed in the repo?)`, evidence: e }; + if (r.exit !== 0) return { status: 'error', detail: `bench command failed (exit ${r.exit}${r.timedOut ? ', timed out' : ''}); its metric output is not evidence`, evidence: e }; let data; if (v.output_file) { try { data = JSON.parse(fs.readFileSync(path.resolve(ctx.root, sub(v.output_file, process.env)), 'utf8')); } catch {} } else data = lastJson(r.stdout); - const e = { cmd: v.cmd, exit: r.exit, ms: r.ms, machine, out_tail: tail(r.stdout + r.stderr, 800) }; - if (r.exit === 127) return { status: 'error', detail: `bench command not found: ${v.cmd} (is the bench rig committed in the repo?)`, evidence: e }; if (data === undefined) return { status: 'error', detail: `no JSON output from bench (exit ${r.exit})`, evidence: e }; const val = pick(data, v.key); e.key = v.key; e.measured = val; e.threshold = `${v.op} ${v.value}`; diff --git a/src/engine.mjs b/src/engine.mjs index 16d0843..1de1317 100644 --- a/src/engine.mjs +++ b/src/engine.mjs @@ -9,6 +9,7 @@ import { parseClaims, checkClaim } from './claims.mjs'; import { record, readLog, verifyChain } from './evidence.mjs'; import * as RC from './cache.mjs'; import { resolveIsolation, COVERAGE_LIMITS } from './isolate.mjs'; +import { verifyContractSignature } from './signature.mjs'; export const KNOWN_LIMITS = [ 'Proofline runs on the same machine as the agent: an agent with shell access could edit .proofline/ or proofline.json. The hash chain makes edits detectable, contract weakening vs the base revision is flagged, and CI re-verifies from a clean checkout; protect proofline.json with CODEOWNERS/branch protection for a hard boundary.', @@ -97,6 +98,8 @@ export function unapprovedContractChange(root, explicit) { if (C.contractHash(baseContract) === C.contractHash(c)) return null; let raw; try { raw = fs.readFileSync(path.join(root, 'proofline.json')); } catch { return null; } + const signature = verifyContractSignature(root); + if (signature.armed && signature.ok) return null; if (approvalMarker(root, raw).approved) return null; const weak = C.weakenings(baseContract, c); return weak.length @@ -114,10 +117,30 @@ export function baseBrief(root, c, t, explicit) { return L.join('\n'); } +function ownerSignatureBlock(root, c, t, explicitBase) { + const signature = verifyContractSignature(root); + if (!signature.armed || signature.ok) return null; + const detail = `contract not owner-signed: ${signature.detail}`; + const results = t.criteria.map((a) => ({ + id: a.id, statement: a.statement, mandatory: a.mandatory !== false, + type: a.verifier.type, status: 'blocked', detail, + })); + return { + isolated: false, env_digest: null, heuristic: true, coverage_limits: COVERAGE_LIMITS, + pushed: false, task: t.id, title: t.title, phase: t.phase, decision: 'BLOCKED', + base: null, base_ref: explicitBase || t.base || C.defaultBase(c), base_source: 'owner signature guard', + ...headInfo(root), contract_hash: C.contractHash(c), results, reuse: 'off', reused: [], + forbidden: [], weakenings: [], contract_fields: [], contract_change: 'unknown', marker: null, + blocked: [detail], failing: [], measured: {}, claims: [], changed: [], ts: new Date().toISOString(), + }; +} + export function verifyTask(root, taskId, opts = {}) { const { claims, only, skipTypes = [], base: explicitBase, machine, fresh = false } = opts; const c = C.load(root); const t = taskById(c, taskId); + const ownerBlock = ownerSignatureBlock(root, c, t, explicitBase); + if (ownerBlock) return ownerBlock; const iso = resolveIsolation(c, opts); const errs = C.validate(c); // Base is pinned when the task starts, so pushing the work does not move the goalposts. @@ -160,6 +183,12 @@ export function verifyTask(root, taskId, opts = {}) { const hashChanged = contractChange === 'changed'; const approveChange = () => { if (!hashChanged) return false; + const signature = verifyContractSignature(root); + if (signature.armed && signature.ok) { + marker = 'guard/owner.pub'; + contractChange = 'approved'; + return true; + } let raw = null; try { raw = fs.readFileSync(path.join(root, 'proofline.json')); } catch { raw = null; } const mark = approvalMarker(root, raw); diff --git a/src/index.mjs b/src/index.mjs index 5647418..003a0f3 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -7,7 +7,7 @@ import * as E from './engine.mjs'; import { record, readLog, verifyChain } from './evidence.mjs'; import { scanForbidden } from './forbidden.mjs'; import { spawnSync } from 'node:child_process'; -import { git, readJson, approvalMarker } from './util.mjs'; +import { git, readJson, approvalMarker, run, tail } from './util.mjs'; import { resolveBase } from './checks.mjs'; export { C, E }; @@ -231,11 +231,13 @@ function commitsOnPushLine(root, line, pushUrl) { const listed = git(['rev-list', ...range], root); if (!listed.ok) return []; const all = listed.out ? listed.out.split('\n').filter(Boolean) : []; + const uncertainHistory = (commits) => Object.assign(commits, { uncertainHistory: true }); const server = serverDefaultHead(root, pushUrl); - if (!server.ok || !server.sha) return all; - if (!git(['cat-file', '-e', `${server.sha}^{commit}`], root).ok) return all; + if (!server.ok) return uncertainHistory(all); + if (!server.sha) return all; + if (!git(['cat-file', '-e', `${server.sha}^{commit}`], root).ok) return uncertainHistory(all); const filtered = git(['rev-list', ...range, '--not', server.sha], root); - if (!filtered.ok) return all; + if (!filtered.ok) return uncertainHistory(all); return filtered.out ? filtered.out.split('\n').filter(Boolean) : []; } @@ -337,6 +339,24 @@ function withoutGitEnv(fn) { } } +const GATE_BOOTSTRAP_TIMEOUT_S = 300; +const GATE_BOOTSTRAP_CMD = 'npm ci --ignore-scripts --no-audit --no-fund'; + +/** Install locked dependencies in the disposable gate worktree, never in the pushing checkout. */ +function bootstrapGateDependencies(root) { + if (!fs.existsSync(path.join(root, 'package.json'))) return null; + if (!['package-lock.json', 'npm-shrinkwrap.json'].some((f) => fs.existsSync(path.join(root, f)))) return null; + let pkg; + try { pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); } + catch (e) { return { ok: false, msg: `dependency bootstrap could not read package.json: ${e.message}` }; } + const needed = ['dependencies', 'devDependencies'].some((k) => pkg[k] && typeof pkg[k] === 'object' && Object.keys(pkg[k]).length > 0); + if (!needed) return null; + const r = run(GATE_BOOTSTRAP_CMD, { cwd: root, timeoutS: GATE_BOOTSTRAP_TIMEOUT_S }); + if (r.exit === 0 && !r.timedOut) return { ok: true }; + const output = tail((r.stderr || '') + (r.stdout ? `\n${r.stdout}` : ''), 1200).trim(); + return { ok: false, msg: `dependency bootstrap failed: ${GATE_BOOTSTRAP_CMD} ${r.timedOut ? `timed out after ${GATE_BOOTSTRAP_TIMEOUT_S}s` : `exited ${r.exit}`}${output ? `\n${output}` : ''}` }; +} + /** * Gate `id` at `sha` in a temporary worktree. The base is the most recent start pin in `root`, * otherwise the parent of `sha`. The refusal names that base. Stale evidence in `root` is not copied. @@ -360,10 +380,13 @@ function gateAtCommit(root, sha, id) { for (const f of ['proofline.json']) { if (!fs.existsSync(path.join(wt, f)) && fs.existsSync(path.join(root, f))) fs.copyFileSync(path.join(root, f), path.join(wt, f)); } + const bootstrap = bootstrapGateDependencies(wt); + if (bootstrap && !bootstrap.ok) return { ok: false, msg: `${id} at ${sha}: ${bootstrap.msg}\nbase ${baseRef}` }; let g; try { g = E.gate(wt, id, { skipTypes: ['pushed'], base: baseRef }); } catch (e) { return { ok: false, msg: `${id} at ${sha}: ${e.message}\nbase ${baseRef}` }; } const used = g.base || baseRef; + if (g.head !== sha) return { ok: false, msg: `${id} at ${sha}: final evidence head ${g.head || 'unknown'} does not match requested SHA ${sha}\nbase ${used}` }; if (g.decision !== 'PASS') return { ok: false, msg: `${id} at ${sha}: ${g.decision}\nbase ${used}\n${g.corrective_prompt}` }; return { ok: true, msg: `gated ${id} at ${sha}\nbase ${used}` }; } finally { @@ -396,17 +419,23 @@ export function hookPrePush(root, { lines, pushUrl } = {}) { const haveLines = Array.isArray(lines) && lines.some((l) => l.trim()); if (haveLines) { const known = new Set(c.tasks.map((t) => t.id)); - const commits = [...new Set(lines.flatMap((l) => commitsOnPushLine(root, l, pushUrl)))]; + const lists = lines.map((l) => commitsOnPushLine(root, l, pushUrl)); + const commits = [...new Set(lists.flat())]; + const uncertainHistory = new Set(lists.filter((l) => l.uncertainHistory).flat()); if (commits.length) { const active = activeTask(root); const activeLive = active && !landedWhy(root, active) ? active : null; const jobs = []; + const unlabeled = []; for (const sha of commits) { const body = git(['log', '-1', '--format=%B', sha], root).out || ''; const id = taskFromMessage(body, known); if (id) jobs.push({ sha, id }); else if (activeLive) jobs.push({ sha, id: activeLive }); + else unlabeled.push(sha); } + const unlabeledInPush = unlabeled.filter((sha) => !uncertainHistory.has(sha)); + if (jobs.length && unlabeledInPush.length) return { ok: false, msg: join(note, `${unlabeledInPush.length} unlabeled commit${unlabeledInPush.length === 1 ? '' : 's'} cannot be gated: no active task, while other commits name a task.\nNext step: proofline next`) }; if (!jobs.length) { const started = readLog(root).some((e) => e.type === 'task_started'); if (!started) return { ok: true, msg: join(note, 'No task has a start record. Next step: proofline next') }; diff --git a/src/infer.mjs b/src/infer.mjs index e8c3ea9..3417488 100644 --- a/src/infer.mjs +++ b/src/infer.mjs @@ -161,7 +161,7 @@ export function receiptZeroConfig(root, { base } = {}) { }); } if (!ran.some((s) => s.ran)) { - return { level: 'L0', exitCode: 0, reason: 'nothing ran', suites: ran, changed, findings }; + return { level: 'L0', exitCode: 2, reason: 'nothing ran', suites: ran, changed, findings }; } return { level: 'L1', diff --git a/src/isolate.mjs b/src/isolate.mjs index c15c5e2..e64d99e 100644 --- a/src/isolate.mjs +++ b/src/isolate.mjs @@ -58,11 +58,29 @@ function result(cmd, cwd, started, child) { }; } +function writableBinds(cwd, writable) { + if (!writable.length) return []; + if (!cwd) throw new Error('writable sandbox paths require a repository cwd'); + const root = path.resolve(cwd); + return writable.map((rel) => { + if (typeof rel !== 'string' || !rel || path.isAbsolute(rel)) throw new Error('writable sandbox paths must stay in the repository'); + const source = path.resolve(root, rel); + const relative = path.relative(root, source); + if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + throw new Error('writable sandbox paths must stay in the repository'); + } + return { source, target: path.posix.join('/work', relative.split(path.sep).join('/')) }; + }); +} + function bwrapArgs(cmd, cwd, extra, writable) { - const args = ['--unshare-net', '--die-with-parent', '--ro-bind', '/', '/', '--tmpfs', '/tmp', '--clearenv', '--setenv', 'HOME', '/tmp', '--setenv', 'PATH', '/usr/local/bin:/usr/bin:/bin']; + const args = ['--unshare-net', '--die-with-parent', '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', '--clearenv', '--setenv', 'HOME', '/tmp', '--setenv', 'PATH', '/usr/local/bin:/usr/bin:/bin']; + for (const dir of ['/usr', '/bin', '/sbin', '/lib', '/lib64']) { + if (fs.existsSync(dir)) args.push('--ro-bind', dir, dir); + } if (cwd) { args.push('--ro-bind', cwd, '/work', '--chdir', '/work'); - for (const rel of writable) args.push('--bind', path.resolve(cwd, rel), path.posix.join('/work', rel)); + for (const bind of writableBinds(cwd, writable)) args.push('--bind', bind.source, bind.target); } else { args.push('--chdir', '/tmp'); } diff --git a/src/mcp.mjs b/src/mcp.mjs index 6e729b3..b487301 100644 --- a/src/mcp.mjs +++ b/src/mcp.mjs @@ -3,6 +3,7 @@ import readline from 'node:readline'; import * as P from './index.mjs'; import { verifyReceipt } from './verify-receipt.mjs'; import { buildReceipt } from './receipt.mjs'; +import { verifyContractSignature } from './signature.mjs'; const BASE = { type: 'string', description: 'The revision the task started from. Needed in a fresh clone unless task_next pinned it or HEAD carries a Proofline-Base: trailer.' }; const FRESH = { type: 'boolean', description: 'Run every check again, ignoring results reused under defaults.reuse_results.' }; @@ -15,7 +16,7 @@ const TOOLS = [ { name: 'gate', description: 'Release decision PASS/FAIL/BLOCKED with Markdown+JSON evidence report.', inputSchema: { type: 'object', properties: { task: { type: 'string' }, claims: { type: 'string' }, base: BASE, fresh: FRESH }, required: ['task'] } }, { name: 'report', description: 'Latest gate report for a task (Markdown).', inputSchema: { type: 'object', properties: { task: { type: 'string' } }, required: ['task'] } }, { name: 'status', description: 'Task and phase status, evidence-chain integrity.', inputSchema: { type: 'object', properties: { owner: OWNER } } }, - { name: 'receipt', description: 'Build a signed contract receipt for task when task is supplied; without task, retain zero-config inference. Returns the same JSON the CLI prints with --json.', inputSchema: { type: 'object', properties: { task: { type: 'string' }, base: { type: 'string', description: 'The revision the task started from.' }, role: { type: 'string' }, out: { type: 'string' }, vault: { type: 'boolean', description: 'Attach a hivevault digest and write the note when the daemon answers.' } } } }, + { name: 'receipt', description: 'Build a signed contract receipt for task when task is supplied; without task, retain zero-config inference. Returns the same JSON the CLI prints with --json. Output always uses the default receipt path.', inputSchema: { type: 'object', properties: { task: { type: 'string' }, base: { type: 'string', description: 'The revision the task started from.' }, role: { type: 'string' }, vault: { type: 'boolean', description: 'Attach a hivevault digest and write the note when the daemon answers.' } } } }, { name: 'verify_receipt', description: 'Check a DSSE receipt envelope offline. Returns the same JSON verify-receipt prints with --json.', inputSchema: { type: 'object', properties: { path: { type: 'string' }, recompute: { type: 'boolean' }, base: BASE }, required: ['path'] } }, ]; @@ -33,13 +34,19 @@ export function handle(root, msg) { let r; switch (params.name) { case 'contract_create': r = P.contractCreate(root, a.task); break; - case 'task_next': r = P.taskNext(root, { owner: a.owner }); break; + case 'task_next': { + const signature = verifyContractSignature(root); + if (signature.armed && !signature.ok) throw new Error(`contract not owner-signed\n${signature.detail}`); + r = P.taskNext(root, { owner: a.owner }); + break; + } case 'evidence_record': r = P.evidenceRecord(root, a.type, a.data || {}); break; case 'verify': { const g = P.E.verifyTask(root, a.task, { claims: a.claims, base: a.base, fresh: a.fresh === true }); r = { ...g, corrective_prompt: P.E.steer(g, P.C.load(root)) }; break; } case 'gate': r = P.E.gate(root, a.task, { claims: a.claims, base: a.base, fresh: a.fresh === true }); break; case 'report': r = P.report(root, a.task); break; case 'status': r = P.status(root, { owner: a.owner }); break; case 'receipt': + if (Object.hasOwn(a, 'out')) throw new Error('receipt out is not available over MCP; the default receipt path is used'); return buildReceipt(root, a).then((got) => ok({ content: [{ type: 'text', text: JSON.stringify(got, null, 2) }], isError: false })).catch((e) => ok({ content: [{ type: 'text', text: `error: ${e.message}` }], isError: true })); case 'verify_receipt': return verifyReceipt(a.path, { root, recompute: a.recompute === true, base: a.base }).then((got) => ok({ content: [{ type: 'text', text: JSON.stringify(got, null, 2) }], isError: false })).catch((e) => ok({ content: [{ type: 'text', text: `error: ${e.message}` }], isError: true })); diff --git a/src/receipt.mjs b/src/receipt.mjs index 7eb6e05..f9637c1 100644 --- a/src/receipt.mjs +++ b/src/receipt.mjs @@ -10,6 +10,7 @@ import { attachMemory, probeDigest, receiptNote, writeReceiptNote } from './vaul import { git, sha256, writeJson } from './util.mjs'; import { COVERAGE_LIMITS } from './isolate.mjs'; import { receiptPredicateProblem } from './verify-receipt.mjs'; +import { verifyContractSignature } from './signature.mjs'; export const PREDICATE_TYPE = 'https://proofline.dev/receipt/v1'; const STATEMENT_TYPE = 'https://in-toto.io/Statement/v1'; @@ -54,6 +55,34 @@ function treeAt(root, ref) { return r.ok ? r.out : null; } +function revisionState(root) { + const commit = git(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], root); + const tree = commit.ok ? treeAt(root, 'HEAD') : null; + const diff = git(['diff', '--binary', 'HEAD', '--', '.', ':(exclude).proofline'], root); + const untracked = git(['ls-files', '--others', '--exclude-standard'], root); + const untrackedHashes = (untracked.ok ? untracked.out.split('\n').filter(Boolean) : []) + .filter((file) => !file.startsWith('.proofline/')) + .map((file) => { + const full = path.join(root, file); + try { + const stat = fs.lstatSync(full); + return [file, sha256(stat.isSymbolicLink() ? fs.readlinkSync(full) : fs.readFileSync(full))]; + } catch (e) { return [file, `unreadable: ${e.message}`]; } + }); + return { + commit: commit.ok ? commit.out : null, + tree, + dirty: changedPaths(root), + fingerprint: sha256(JSON.stringify({ commit: commit.out, tree, diff: diff.out, untracked: untrackedHashes })), + }; +} + +function refuseDrift(before, after, when) { + if (before.commit !== after.commit || before.tree !== after.tree || before.fingerprint !== after.fingerprint) { + throw new Error(`repository changed ${when}: HEAD, tree, or worktree drift; refusing receipt`); + } +} + function makeAttempts(results) { return results.filter((r) => r.type === 'test_red_green').map((r) => { const evidence = r.evidence || {}; @@ -195,17 +224,22 @@ async function legacyReceipt(root, a) { /** Build a contract-bound DSSE receipt, or retain zero-config inference when no task is supplied. */ export async function buildReceipt(root, a = {}) { + const signature = verifyContractSignature(root); + if (signature.armed && !signature.ok) throw new Error(`contract not owner-signed: ${signature.detail}`); if (typeof a.task !== 'string' || !a.task.trim()) return legacyReceipt(root, a); const contract = C.load(root); const task = contract.tasks.find((t) => t.id === a.task); if (!task) throw new Error(`unknown task ${a.task}`); - const headCommit = git(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], root); - const headTree = headCommit.ok ? treeAt(root, 'HEAD') : null; - if (!headCommit.ok || !headTree) throw new Error('receipt needs a committed HEAD and Git tree'); + const initial = revisionState(root); + if (!initial.commit || !initial.tree) throw new Error('receipt needs a committed HEAD and Git tree'); + const headCommit = { out: initial.commit }; + const headTree = initial.tree; const started = new Date().toISOString(); const verification = verifyTask(root, task.id, { base: a.base, claims: a.claims, fresh: true, isolated: a.isolated === true }); + const verified = revisionState(root); + refuseDrift(initial, verified, 'during receipt verification'); const baseCommit = verification.base; const base = { commit: baseCommit || null, tree: baseCommit ? treeAt(root, baseCommit) : null }; const repository = repositoryInfo(root, a); @@ -218,7 +252,7 @@ export async function buildReceipt(root, a = {}) { root, contract: { ...contract, package: JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')) }, task, verification, head: { gitCommit: headCommit.out, gitTree: headTree, ref: headCommit.out }, base, repository, started, role, }); - const dirty = changedPaths(root); + const dirty = verified.dirty; let reason = null; let signingKey = null; if (dirty.length) reason = `worktree is not clean: ${dirty.join(', ')}`; @@ -255,6 +289,7 @@ export async function buildReceipt(root, a = {}) { let envelope; if (signed) { const agentkey = await import('@optitransfer/agentkey'); + refuseDrift(verified, revisionState(root), 'before receipt signing'); envelope = agentkey.signDSSE(PAYLOAD_TYPE, payload, signingKey); } else { envelope = { payloadType: PAYLOAD_TYPE, payload: payload.toString('base64'), signatures: [] }; diff --git a/src/util.mjs b/src/util.mjs index bd5de6d..35fe703 100644 --- a/src/util.mjs +++ b/src/util.mjs @@ -42,7 +42,9 @@ export function run(cmd, { cwd, timeoutS = 600, env } = {}) { export function git(args, cwd) { const r = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20 }); - return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() }; + const out = r.stdout || ''; + const err = [(r.stderr || '').trim(), r.error ? String(r.error) : ''].filter(Boolean).join('\n'); + return { ok: r.status === 0 && !r.error, out: out.trim(), raw: out, err }; } /** Where commit `sha` stands against /. { ok: false, err } when the remote cannot be read; otherwise @@ -69,7 +71,7 @@ export function globRe(g) { let re = ''; for (let i = 0; i < g.length; i++) { const c = g[i]; - if (c === '*' && g[i + 1] === '*') { re += '.*'; i++; if (g[i + 1] === '/') i++; } + if (c === '*' && g[i + 1] === '*') { re += '[\\s\\S]*'; i++; if (g[i + 1] === '/') i++; } else if (c === '*') re += '[^/]*'; else if (c === '?') re += '[^/]'; else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&'); diff --git a/src/verify-receipt.mjs b/src/verify-receipt.mjs index 79a219a..5ebbbcd 100644 --- a/src/verify-receipt.mjs +++ b/src/verify-receipt.mjs @@ -5,6 +5,7 @@ import path from 'node:path'; import { receiptZeroConfig, changedTests } from './infer.mjs'; import { verifyTask } from './engine.mjs'; import { git } from './util.mjs'; +import { verifyContractSignature } from './signature.mjs'; const STATEMENT = 'https://in-toto.io/Statement/v1'; const PAYLOAD_TYPE = 'application/vnd.in-toto+json'; @@ -111,16 +112,17 @@ function verifySignatures(envelope, keys) { let verified = 0; let unknown = 0; let failed = 0; + const verifiedKeyids = []; for (const s of envelope.signatures) { const id = typeof s?.keyid === 'string' ? s.keyid : ''; const sig = fromB64(s?.sig || ''); const key = keys.get(id); if (!key || !sig) { unknown++; continue; } const ok = crypto.verify(null, data, key, sig); - if (ok) verified++; + if (ok) { verified++; verifiedKeyids.push(id); } else failed++; } - return { body, verified, unknown, failed }; + return { body, verified, unknown, failed, verifiedKeyids }; } /** @@ -133,6 +135,10 @@ export async function verifyReceipt(envelopePath, opts = {}) { try { raw = JSON.parse(fs.readFileSync(envelopePath, 'utf8')); } catch { return result(1, 'envelope is not JSON'); } if (opts.sigstore) return verifySigstore(raw); + if (opts.recompute && opts.root) { + const signature = verifyContractSignature(opts.root); + if (signature.armed && !signature.ok) return result(2, `contract not owner-signed: ${signature.detail}`); + } if (Array.isArray(raw?.signatures) && raw.signatures.length === 0) return result(2, 'unsigned L0 receipt; authenticity is not established', { level: 'L0' }); const keys = loadKeys(opts.keys || (process.env.AGENTKEY_HOME ? path.join(process.env.AGENTKEY_HOME, 'keys') : '')); const sig = verifySignatures(raw, keys); @@ -147,6 +153,10 @@ export async function verifyReceipt(envelopePath, opts = {}) { if (schema) return result(1, `schema: ${schema}`); const level = statement.predicate.level; const predicate = statement.predicate; + if (level === 'L2') return result(1, 'L2 requires a CI attestation; ordinary agentkey DSSE verification cannot establish it', { level }); + if (predicate.task !== undefined && !sig.verifiedKeyids.includes(predicate.agent.kid)) { + return result(1, 'predicate.agent.kid does not match a verified envelope keyid', { level }); + } const root = opts.root || process.cwd(); if (predicate.task !== undefined && opts.root) { const localHead = git(['rev-parse', '--verify', '--quiet', 'HEAD'], root); diff --git a/test/cli_contract.test.mjs b/test/cli_contract.test.mjs new file mode 100644 index 0000000..9c1c78d --- /dev/null +++ b/test/cli_contract.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { makeTask, skeleton } from '../src/contract.mjs'; + +const BIN = path.resolve(import.meta.dirname, '..', 'bin', 'proofline.mjs'); +const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim(); + +function cli(root, args) { + const env = { ...process.env }; + delete env.PROOFLINE_AGENT_ROLE; + return spawnSync(process.execPath, [BIN, ...args, '--root', root, '--json'], { cwd: root, env, encoding: 'utf8' }); +} + +function taskRepo() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-cli-contract-')); + git(root, ['init', '-q', '-b', 'main']); + git(root, ['config', 'user.email', 'cli@example.test']); + git(root, ['config', 'user.name', 'cli fixture']); + fs.writeFileSync(path.join(root, 'package.json'), '{ "type": "module" }\n'); + const contract = skeleton('cli-contract'); + contract.tasks = [makeTask({ + id: 'T', title: 'Isolation option', scope: ['**'], + criteria: [{ id: 'T-AC01', statement: 'command', verifier: { type: 'command', cmd: 'true', expect_exit: 0 } }], + })]; + fs.writeFileSync(path.join(root, 'proofline.json'), JSON.stringify(contract, null, 2) + '\n'); + git(root, ['add', '-A']); + git(root, ['commit', '-q', '-m', 'base']); + const base = git(root, ['rev-parse', 'HEAD']); + git(root, ['commit', '-q', '--allow-empty', '-m', 'work']); + return { root, base }; +} + +test('verify, gate, and receipt accept --isolated as a boolean switch and forward it', (t) => { + const fixture = taskRepo(); + t.after(() => fs.rmSync(fixture.root, { recursive: true, force: true })); + for (const command of ['verify', 'gate']) { + const run = cli(fixture.root, [command, '--isolated', 'T', '--base', fixture.base]); + assert.equal(run.status, 2, `${command}: ${run.stderr}`); + const output = JSON.parse(run.stdout); + assert.equal(output.decision, 'BLOCKED'); + assert.match(output.blocked.join('\n'), /env\.image/); + assert.equal(output.isolated, false); + } + const receipt = cli(fixture.root, ['receipt', '--isolated', 'T', '--base', fixture.base]); + assert.equal(receipt.status, 2, receipt.stderr); + const output = JSON.parse(receipt.stdout); + assert.equal(output.exitCode, 2); + assert.equal(output.predicate.decision, 'BLOCKED'); + assert.match(output.predicate.reason || '', /no agent role|isolated|env\.image/i); + assert.match(output.envelope.payload, /.+/); + const predicate = JSON.parse(Buffer.from(output.envelope.payload, 'base64')).predicate; + assert.match(predicate.isolation.env_digest || 'env.image is required for --isolated', /env\.image/); +}); + +test('zero-config receipt with every inferred suite blocked exits 2 without a task', (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-cli-zero-blocked-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + git(root, ['init', '-q', '-b', 'main']); + git(root, ['config', 'user.email', 'cli@example.test']); + git(root, ['config', 'user.name', 'cli fixture']); + fs.writeFileSync(path.join(root, 'build.gradle'), '// no inferred test command\n'); + git(root, ['add', 'build.gradle']); + git(root, ['commit', '-q', '-m', 'base']); + const base = git(root, ['rev-parse', 'HEAD']); + const run = cli(root, ['receipt', '--base', base]); + assert.equal(run.status, 2, run.stderr); + const output = JSON.parse(run.stdout); + assert.equal(output.level, 'L0'); + assert.equal(output.exitCode, 2); + assert.equal(output.reason, 'nothing ran'); + assert.ok(output.suites.length > 0); + assert.ok(output.suites.every((suite) => suite.status === 'blocked' && suite.ran === false)); +}); diff --git a/test/contract_sig.test.mjs b/test/contract_sig.test.mjs index 7088f49..06cce74 100644 --- a/test/contract_sig.test.mjs +++ b/test/contract_sig.test.mjs @@ -99,3 +99,37 @@ test('a pinned contract is refused until the owner signature matches, and the pu assert.equal(fs.readFileSync(path.join(box.ak, 'canary'), 'utf8'), 'do-not-read'); } }); + +test('a valid owner signature approves a contract change without a local approval marker', () => { + const box = agentEnv(); + const root = repo(); + try { + const init = spawnSync('agentkey', ['init', 'owner'], { encoding: 'utf8', env: box.env }); + assert.equal(init.status, 0, init.stderr); + const c = P.C.skeleton('signed-change'); + c.tasks.push(P.C.makeTask({ + id: 'T-01', title: 'original title', + criteria: [{ statement: 'true', verifier: { type: 'command', cmd: 'true' } }], + })); + P.C.save(root, c); + fs.mkdirSync(path.join(root, 'guard')); + fs.writeFileSync(path.join(root, 'guard', 'owner.pub'), pub(box.env)); + commitBeforeBase(root); + + c.tasks[0].title = 'owner approved title'; + P.C.save(root, c); + const signed = run(root, ['contract', 'sign'], box.env); + assert.equal(signed.status, 0, signed.stderr); + assert.equal(P.E.unapprovedContractChange(root), null); + const gate = P.E.verifyTask(root, 'T-01', { base: 'HEAD' }); + assert.equal(gate.decision, 'PASS', gate.blocked.join('; ')); + assert.equal(gate.contract_change, 'approved'); + assert.equal(gate.marker, 'guard/owner.pub'); + + c.tasks[0].title = 'altered without the owner'; + P.C.save(root, c); + assert.match(P.E.unapprovedContractChange(root), /contract .*changed|contract weakened/); + } finally { + fs.chmodSync(box.ak, 0o700); + } +}); diff --git a/test/trust_boundary.test.mjs b/test/trust_boundary.test.mjs new file mode 100644 index 0000000..fd31e6b --- /dev/null +++ b/test/trust_boundary.test.mjs @@ -0,0 +1,209 @@ +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { execFileSync } from 'node:child_process'; +import { buildReceipt } from '../src/receipt.mjs'; +import { gate, verifyTask } from '../src/engine.mjs'; +import { handle } from '../src/mcp.mjs'; +import { runInSandbox } from '../src/isolate.mjs'; +import { verifyReceipt } from '../src/verify-receipt.mjs'; +import { makeTask, skeleton } from '../src/contract.mjs'; + +const PAYLOAD_TYPE = 'application/vnd.in-toto+json'; +const git = (cwd, args) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim(); +const markerCommand = 'node -e "require(\'node:fs\').writeFileSync(\'executed\', \'yes\')"'; + +function repoWithCommand(command, { armed = false } = {}) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-trust-')); + git(root, ['init', '-q', '-b', 'main']); + git(root, ['config', 'user.email', 'trust@example.test']); + git(root, ['config', 'user.name', 'trust fixture']); + fs.writeFileSync(path.join(root, 'package.json'), '{ "type": "module" }\n'); + const contract = skeleton('trust-boundary'); + contract.tasks = [makeTask({ + id: 'T', title: 'Trust boundary', scope: ['**'], + criteria: [{ id: 'T-AC01', statement: 'command', verifier: { type: 'command', cmd: command, expect_exit: 0 } }], + })]; + fs.writeFileSync(path.join(root, 'proofline.json'), JSON.stringify(contract, null, 2) + '\n'); + if (armed) { + const { publicKey } = crypto.generateKeyPairSync('ed25519'); + fs.mkdirSync(path.join(root, 'guard')); + fs.writeFileSync(path.join(root, 'guard', 'owner.pub'), publicKey.export({ type: 'spki', format: 'pem' })); + } + git(root, ['add', '-A']); + git(root, ['commit', '-q', '-m', 'base']); + const base = git(root, ['rev-parse', 'HEAD']); + git(root, ['commit', '-q', '--allow-empty', '-m', 'work']); + return { root, base, head: git(root, ['rev-parse', 'HEAD']), marker: path.join(root, 'executed') }; +} + +function pae(payloadType, payload) { + const type = Buffer.from(payloadType); + const body = Buffer.from(payload); + return Buffer.concat([Buffer.from(`DSSEv1 ${type.length} `), type, Buffer.from(` ${body.length} `), body]); +} + +function contractStatement({ level = 'L1', kid = 'local', head = 'a'.repeat(40), base = 'b'.repeat(40) } = {}) { + const tree = 'c'.repeat(40); + return { + _type: 'https://in-toto.io/Statement/v1', + subject: [{ name: head, digest: { gitCommit: head, gitTree: tree } }], + predicateType: 'https://proofline.dev/receipt/v1', + predicate: { + level, + producer: 'trust-boundary-test', + decision: 'PASS', exitCode: 0, + base: { gitCommit: base, gitTree: tree, ref: base }, + head: { gitCommit: head, gitTree: tree, ref: head }, + task: { id: 'T', title: 'Trust boundary', phase: 'implement', contract_hash: 'd'.repeat(64) }, + tests: { + changed: [], + red_on_base: { ran: false, failed: null, output_sha256: null }, + green_on_head: { ran: false, passed: null, output_sha256: null }, + attempts: [], + }, + suite: { ran: false, command: null, exit: null, count: null, duration_ms: null, output_sha256: null, runs: [] }, + metrics: [], + scope: { ran: false, allowed: [], changed: [], pass: null }, + forbidden: { ran: true, findings: [], pass: true }, + claims: { ran: false, reported: [], reconciled: null }, + agent: { role: 'test', kid, run_id: null, model: null, trace: null }, + repository: { url: null, visibility: 'private' }, + timestamps: { started: '2026-01-01T00:00:00.000Z', finished: '2026-01-01T00:00:01.000Z' }, + heuristic: true, heuristic_ran: true, coverage_limits: [], + isolation: { ran: true, isolated: false, env_digest: null }, + }, + }; +} + +function signedEnvelope(statement, privateKey, keyid = 'local') { + const payload = Buffer.from(JSON.stringify(statement)); + const sig = crypto.sign(null, pae(PAYLOAD_TYPE, payload), privateKey); + return { payloadType: PAYLOAD_TYPE, payload: payload.toString('base64'), signatures: [{ keyid, sig: sig.toString('base64') }] }; +} + +function call(root, name, args = {}) { + return handle(root, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }); +} + +test('armed invalid owner contracts cannot execute through engine, MCP, or receipt paths', async (t) => { + const direct = repoWithCommand(markerCommand, { armed: true }); + t.after(() => fs.rmSync(direct.root, { recursive: true, force: true })); + const verified = verifyTask(direct.root, 'T', { base: direct.base }); + assert.equal(verified.decision, 'BLOCKED'); + assert.match(verified.blocked.join('\n'), /owner-signed/); + assert.equal(fs.existsSync(direct.marker), false); + assert.equal(gate(direct.root, 'T', { base: direct.base }).decision, 'BLOCKED'); + assert.equal(fs.existsSync(direct.marker), false); + await assert.rejects(buildReceipt(direct.root, { task: 'T', base: direct.base }), /owner-signed/); + assert.equal(fs.existsSync(direct.marker), false); + + const mcp = repoWithCommand(markerCommand, { armed: true }); + t.after(() => fs.rmSync(mcp.root, { recursive: true, force: true })); + const next = await call(mcp.root, 'task_next'); + assert.equal(next.result.isError, true); + assert.match(next.result.content[0].text, /owner-signed/); + assert.equal(fs.existsSync(path.join(mcp.root, '.proofline', 'active')), false); + for (const name of ['verify', 'gate']) { + const reply = await call(mcp.root, name, { task: 'T', base: mcp.base }); + assert.match(reply.result.content[0].text, /BLOCKED/); + assert.equal(fs.existsSync(mcp.marker), false, `${name} executed the armed invalid contract`); + } + const receipt = await call(mcp.root, 'receipt', { task: 'T', base: mcp.base }); + assert.equal(receipt.result.isError, true); + assert.match(receipt.result.content[0].text, /owner-signed/); + assert.equal(fs.existsSync(mcp.marker), false); +}); + +test('receipt recomputation enforces an armed owner signature before running commands', async (t) => { + const fixture = repoWithCommand(markerCommand, { armed: true }); + const keys = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-trust-keys-')); + t.after(() => { + fs.rmSync(fixture.root, { recursive: true, force: true }); + fs.rmSync(keys, { recursive: true, force: true }); + }); + const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519'); + fs.writeFileSync(path.join(keys, 'local.pem'), publicKey.export({ type: 'spki', format: 'pem' })); + const statement = contractStatement({ head: fixture.head, base: fixture.base }); + const envelope = path.join(keys, 'receipt.json'); + fs.writeFileSync(envelope, JSON.stringify(signedEnvelope(statement, privateKey))); + const got = await verifyReceipt(envelope, { root: fixture.root, keys, recompute: true, base: fixture.base }); + assert.notEqual(got.exitCode, 0); + assert.equal(fs.existsSync(fixture.marker), false); +}); + +test('ordinary DSSE verification rejects self-declared L2 and requires the predicate key id to be verified', async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-dsse-trust-')); + const keys = path.join(root, 'keys'); + fs.mkdirSync(keys); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519'); + fs.writeFileSync(path.join(keys, 'local.pem'), publicKey.export({ type: 'spki', format: 'pem' })); + const check = async (statement, name) => { + const file = path.join(root, `${name}.json`); + fs.writeFileSync(file, JSON.stringify(signedEnvelope(statement, privateKey))); + return verifyReceipt(file, { keys }); + }; + assert.equal((await check(contractStatement(), 'valid')).exitCode, 0); + const wrongKid = await check(contractStatement({ kid: 'self-declared-other-key' }), 'wrong-kid'); + assert.equal(wrongKid.exitCode, 1); + assert.match(wrongKid.message, /keyid|key id/i); + const l2 = await check(contractStatement({ level: 'L2' }), 'self-declared-l2'); + assert.equal(l2.exitCode, 1); + assert.match(l2.message, /L2/); +}); + +test('MCP receipt rejects caller-selected output paths', async (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-mcp-out-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const listed = handle(root, { jsonrpc: '2.0', id: 1, method: 'tools/list' }); + const schema = listed.result.tools.find((tool) => tool.name === 'receipt').inputSchema; + assert.equal(Object.hasOwn(schema.properties, 'out'), false); + const reply = await call(root, 'receipt', { out: path.join(root, 'escape.json') }); + assert.equal(reply.result.isError, true); + assert.match(reply.result.content[0].text, /out.*not.*MCP|MCP.*out/i); + assert.equal(fs.existsSync(path.join(root, 'escape.json')), false); +}); + +test('buildReceipt refuses worktree drift caused by verification', async (t) => { + const fixture = repoWithCommand('node -e "require(\'node:fs\').writeFileSync(\'drift.txt\', \'changed\')"'); + t.after(() => fs.rmSync(fixture.root, { recursive: true, force: true })); + await assert.rejects(buildReceipt(fixture.root, { task: 'T', base: fixture.base }), /drift|changed during|repository changed/i); +}); + +test('buildReceipt refuses HEAD and tree drift caused by verification', async (t) => { + const command = 'node -e "require(\'node:fs\').writeFileSync(\'drift.txt\', \'changed\')" && git add drift.txt && git commit -q -m drift'; + const fixture = repoWithCommand(command); + t.after(() => fs.rmSync(fixture.root, { recursive: true, force: true })); + await assert.rejects(buildReceipt(fixture.root, { task: 'T', base: fixture.base }), /drift|changed during|repository changed/i); + assert.notEqual(git(fixture.root, ['rev-parse', 'HEAD']), fixture.head); +}); + +test('bwrap does not mount host root and rejects writable paths outside the repository', (t) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-bwrap-root-')); + const bin = fs.mkdtempSync(path.join(os.tmpdir(), 'pl-bwrap-bin-')); + const capture = path.join(root, 'args.txt'); + t.after(() => { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(bin, { recursive: true, force: true }); + }); + fs.writeFileSync(path.join(bin, 'bwrap'), '#!/bin/sh\nprintf \'%s\\n\' "$@" > "$CAPTURE"\n', { mode: 0o755 }); + const oldPath = process.env.PATH; + const oldCapture = process.env.CAPTURE; + process.env.PATH = `${bin}${path.delimiter}${oldPath}`; + process.env.CAPTURE = capture; + try { + assert.throws(() => runInSandbox('true', { cwd: root, runtime: 'bwrap', writable: ['../outside'] }), /writable.*repo|outside.*repo/i); + const ran = runInSandbox('true', { cwd: root, runtime: 'bwrap' }); + assert.equal(ran.exit, 0, ran.stderr); + const args = fs.readFileSync(capture, 'utf8').trim().split('\n'); + assert.equal(args.some((arg, i) => arg === '--ro-bind' && args[i + 1] === '/' && args[i + 2] === '/'), false); + } finally { + process.env.PATH = oldPath; + if (oldCapture === undefined) delete process.env.CAPTURE; + else process.env.CAPTURE = oldCapture; + } +}); diff --git a/test/verifier_fail_closed.test.mjs b/test/verifier_fail_closed.test.mjs new file mode 100644 index 0000000..b7a827f --- /dev/null +++ b/test/verifier_fail_closed.test.mjs @@ -0,0 +1,158 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { changedFiles, diffHunks, verifiers } from '../src/checks.mjs'; +import { hookPrePush } from '../src/index.mjs'; +import { repo, write, addTask, commitBeforeBase, sh } from './helpers.mjs'; + +const completed = (overrides = {}) => ({ cmd: 'injected', exit: 0, stdout: '', stderr: '', ms: 1, timedOut: false, ...overrides }); + +test('command timeout fails closed even when expect_exit is 124', () => { + const result = verifiers.command({ cmd: 'injected', expect_exit: 124 }, { + root: process.cwd(), + sandbox: () => completed({ exit: 124, timedOut: true }), + }); + assert.equal(result.status, 'fail'); + assert.match(result.detail, /timed out/i); + assert.equal(result.evidence.timedOut, true); +}); + +test('metric rejects nonzero benchmark exit even when JSON meets the threshold', () => { + const measured = {}; + const result = verifiers.metric({ cmd: 'injected', key: 'latency', op: '<', value: 10 }, { + root: process.cwd(), + measured, + machine: () => ({ load1: 0, cpus: 1 }), + sandbox: () => completed({ exit: 1, stdout: '{"latency":1}\n' }), + }); + assert.equal(result.status, 'error'); + assert.match(result.detail, /exit 1/); + assert.deepEqual(measured, {}); +}); + +function redGreenFixture() { + const r = repo({ files: { 'src/value': 'slow\n' } }); + const base = sh(r, 'rev-parse', 'HEAD'); + write(r, { + 'src/value': 'fast\n', + 'test/value.test.mjs': "import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs';\ntest('value is fast', () => assert.equal(fs.readFileSync('src/value', 'utf8').trim(), 'fast'));\n", + }); + return { r, base, test_file: 'test/value.test.mjs' }; +} + +test('red-green base setup failure is inconclusive rather than valid red', () => { + const { r, base, test_file } = redGreenFixture(); + const result = verifiers.test_red_green({ test_file, cmd: 'node --test {test}', setup: 'exit 9' }, { root: r, base }); + assert.equal(result.status, 'error'); + assert.match(result.detail, /setup.*exit 9/i); + assert.equal(result.evidence.setup.exit, 9); +}); + +test('red-green base command timeout is inconclusive rather than valid red', () => { + const { r, base, test_file } = redGreenFixture(); + const result = verifiers.test_red_green({ test_file, cmd: 'if grep -qx slow src/value; then sleep 1; fi', timeout_s: 0.05 }, { root: r, base }); + assert.equal(result.status, 'error'); + assert.match(result.detail, /base.*timed out/i); + assert.equal(result.evidence.red.timedOut, true); +}); + +test('rename scope checks old and new paths using NUL-delimited parsing', () => { + const oldPath = 'vendor/old\tname.mjs'; + const newPath = 'src/new\nname.mjs'; + const r = repo({ files: { [oldPath]: 'export const value = 1;\n' } }); + const base = sh(r, 'rev-parse', 'HEAD'); + fs.mkdirSync(path.join(r, 'src'), { recursive: true }); + sh(r, 'mv', '--', oldPath, newPath); + const changed = changedFiles(r, base); + assert.ok(changed.has(oldPath), 'old rename path is in scope evidence'); + assert.ok(changed.has(newPath), 'new rename path is in scope evidence'); + const result = verifiers.scope({}, { base, changed, task: { scope: { allow: ['src/**'] } } }); + assert.equal(result.status, 'fail'); + assert.deepEqual(result.evidence.outside, [oldPath]); +}); + +test('copy scope checks both source and destination paths', () => { + const source = 'vendor/source.mjs'; + const destination = 'src/copied.mjs'; + const r = repo({ files: { [source]: 'export const value = 1;\n' } }); + const base = sh(r, 'rev-parse', 'HEAD'); + fs.mkdirSync(path.join(r, 'src'), { recursive: true }); + fs.copyFileSync(path.join(r, source), path.join(r, destination)); + sh(r, 'add', '--', destination); + const changed = changedFiles(r, base); + assert.ok(changed.has(source), 'copy source is in scope evidence'); + assert.ok(changed.has(destination), 'copy destination is in scope evidence'); + const result = verifiers.scope({}, { base, changed, task: { scope: { allow: ['src/**'] } } }); + assert.equal(result.status, 'fail'); + assert.deepEqual(result.evidence.outside, [source]); +}); + +test('git diff failures do not become empty changed-file or diff-hunk results', () => { + const r = repo(); + assert.throws(() => changedFiles(r, 'not-a-real-base'), /git diff.*failed/i); + assert.throws(() => diffHunks(r, 'not-a-real-base'), /git diff.*failed/i); +}); + +test('mixed named and unlabeled push stack refuses unlabeled commits without an active task', () => { + const r = repo({ hooks: true }); + addTask(r, { id: 'T', title: 'task', criteria: [{ verifier: { type: 'command', cmd: 'true' } }] }); + commitBeforeBase(r); + write(r, { 'src/named.mjs': 'export const named = true;\n' }); + sh(r, 'add', '-A'); + sh(r, 'commit', '-q', '-m', 'named work (T)'); + write(r, { 'src/unlabeled.mjs': 'export const unlabeled = true;\n' }); + sh(r, 'add', '-A'); + sh(r, 'commit', '-q', '-m', 'unlabeled work'); + const pushed = spawnSync('git', ['push', 'origin', 'HEAD:main'], { cwd: r, encoding: 'utf8' }); + assert.notEqual(pushed.status, 0, pushed.stderr); + assert.match(pushed.stderr, /unlabeled commit/i); + assert.match(pushed.stderr, /proofline next/); +}); + +test('pre-push rejects a passing gate whose final evidence head differs from the requested SHA', () => { + const r = repo(); + addTask(r, { id: 'T', title: 'task', criteria: [{ verifier: { type: 'command', cmd: "git commit --allow-empty -m 'moved during gate'" } }] }); + commitBeforeBase(r); + write(r, { 'src/work.mjs': 'export const work = true;\n' }); + sh(r, 'add', '-A'); + sh(r, 'commit', '-q', '-m', 'work (T)'); + const local = sh(r, 'rev-parse', 'HEAD'); + const remote = sh(r, 'rev-parse', 'origin/main'); + const line = `refs/heads/main ${local} refs/heads/main ${remote}`; + const result = hookPrePush(r, { lines: [line], pushUrl: sh(r, 'remote', 'get-url', 'origin') }); + assert.equal(result.ok, false, result.msg); + assert.match(result.msg, /evidence head .*requested SHA/i); + assert.match(result.msg, new RegExp(local)); +}); + +test('pre-push installs locked local dependencies needed by a fresh gate worktree', () => { + const lock = { + name: 'gate-fixture', version: '1.0.0', lockfileVersion: 3, requires: true, + packages: { + '': { name: 'gate-fixture', version: '1.0.0', dependencies: { 'local-gate-dep': 'file:vendor/local-gate-dep' } }, + 'node_modules/local-gate-dep': { resolved: 'vendor/local-gate-dep', link: true }, + 'vendor/local-gate-dep': { name: 'local-gate-dep', version: '1.0.0' }, + }, + }; + const r = repo({ files: { + 'package.json': '{"name":"gate-fixture","version":"1.0.0","type":"module","dependencies":{"local-gate-dep":"file:vendor/local-gate-dep"}}\n', + 'package-lock.json': JSON.stringify(lock, null, 2) + '\n', + 'vendor/local-gate-dep/package.json': '{"name":"local-gate-dep","version":"1.0.0","type":"module","exports":"./index.mjs"}\n', + 'vendor/local-gate-dep/index.mjs': 'export const answer = 42;\n', + } }); + addTask(r, { id: 'T', title: 'task', criteria: [{ verifier: { type: 'command', cmd: "node --input-type=module -e \"import { answer } from 'local-gate-dep'; if (answer !== 42) process.exit(1)\"" } }] }); + commitBeforeBase(r); + write(r, { 'src/work.mjs': 'export const work = true;\n' }); + sh(r, 'add', '-A'); + sh(r, 'commit', '-q', '-m', 'work (T)'); + const local = sh(r, 'rev-parse', 'HEAD'); + const remote = sh(r, 'rev-parse', 'origin/main'); + const line = `refs/heads/main ${local} refs/heads/main ${remote}`; + assert.equal(fs.existsSync(path.join(r, 'node_modules')), false, 'fixture starts without installed dependencies'); + const result = hookPrePush(r, { lines: [line], pushUrl: sh(r, 'remote', 'get-url', 'origin') }); + assert.equal(result.ok, true, result.msg); + assert.match(result.msg, new RegExp(`gated T at ${local}`)); + assert.equal(fs.existsSync(path.join(r, 'node_modules')), false, 'installation is confined to the temporary gate worktree'); +});