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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions bin/proofline.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down Expand Up @@ -66,8 +66,10 @@ const HELP = `proofline: independent V&V and delivery controller
--owner limits the lane; --base re-pins the base
brief <TASK> [--owner <name>] [--base <rev>] brief for a task, with the base verify will use
(refuses another owner's task)
verify <TASK> [--claims "line"] [--base <rev>] [--fresh] run every check independently; prints corrective prompt
gate <TASK>|--all [--claims ...] [--base <rev>] [--fresh] release decision PASS/FAIL/BLOCKED + report (.proofline/reports)
verify <TASK> [--claims "line"] [--base <rev>] [--fresh] [--isolated]
run every check independently; prints corrective prompt
gate <TASK>|--all [--claims ...] [--base <rev>] [--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
Expand All @@ -77,7 +79,7 @@ const HELP = `proofline: independent V&V and delivery controller
evidence record <type> --data '{..}' | evidence verify | evidence log
verify-receipt <envelope> [--keys <dir>] [--sigstore] [--recompute --base <sha>]
exit 0 verified, 1 failed or differs, 2 unknown key, 3 usage
receipt <TASK> [--role <name>] [--base <rev>] [--out <path>] [--vault]
receipt <TASK> [--role <name>] [--base <rev>] [--out <path>] [--vault] [--isolated]
contract receipt for a task; without <TASK>, 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
Expand All @@ -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: [],
Expand Down Expand Up @@ -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 })) },
Expand Down Expand Up @@ -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, {
Expand All @@ -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': {
Expand Down
11 changes: 7 additions & 4 deletions proofline.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion proofline.json.sig
Original file line number Diff line number Diff line change
@@ -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=="}]}
47 changes: 35 additions & 12 deletions src/checks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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')) {
Expand All @@ -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: [] }] });
Expand Down Expand Up @@ -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 = [];
Expand All @@ -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);
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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}`;
Expand Down
29 changes: 29 additions & 0 deletions src/engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading