Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(core): freeze policy and audit exact submissions [V4,V16,L3,M3]

Corey Olson1f951e5027e4
diff --git a/docs/formats.md b/docs/formats.md
index a1e90eb3..15d2d2b3 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -231,7 +231,7 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap
| `claim` | builder | `leaseUntil`, `digest` |
| `renew` | builder | `leaseUntil`, `digest` |
| `release` | builder | — |
-| `submit` | builder | `commit`, `tree` |
+| `submit` | builder | `commit`, `tree`, `policyCommit` |
| `reserve` | reviewer | `until` |
| `accept` | reviewer | `reason`, `commit` |
| `reject` | reviewer | `reason`, `commit` |
@@ -246,6 +246,8 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap
| `answer` | answerer | `shout`, `to`, `decision`, `request`, `answers`, `outcome` |
<!-- events:end -->
+New CLI claims include a `policy` object (`version: 1`, `commit`) in the frozen criterion. It pins the coordinator checkout’s committed configuration. Legacy claims use their recorded claim-base commit. A CLI `submit` records the pre-merge coordinator HEAD as optional `policyCommit`; historical doctor and acceptance checks use this snapshot when allowing unchanged foreign files brought in from MAIN. Verified dependencies may also contribute unchanged files in their own lanes before a MAIN merge; foreign deletion or replacement is not authorized by an unrelated dependency’s tree. The complete candidate diff against both claim base and frozen MAIN is checked with rename detection disabled, preserving deleted paths and whitespace in names. Frozen item checks run against the exact submitted commit in an isolated checkout when accepting and auditing; repairing a reviewer’s checkout cannot make a red submission green.
+
Migration preserves event rows and adds only schema objects that are missing.
The schema, trigger and parser tables in this guide are checked against live `openBoard(':memory:')` and `parseSpec` results by `docs/formats.test.js`.
diff --git a/docs/formats.test.js b/docs/formats.test.js
index 93b54f39..41c4b5c2 100644
--- a/docs/formats.test.js
+++ b/docs/formats.test.js
@@ -164,7 +164,7 @@ function recordEventContract() {
refreeze(board, first, { agentId: coordinator, freeze: freeze('second') });
claim(board, first, { agentId: builder, lane: 'docs', leaseMs: 60_000, freeze: freeze('unused') });
const acceptedCommit = 'a'.repeat(40);
- submit(board, first, { agentId: builder, commit: acceptedCommit, tree: 'b'.repeat(40), files: ['docs/formats.md'] });
+ submit(board, first, { agentId: builder, commit: acceptedCommit, tree: 'b'.repeat(40), files: ['docs/formats.md'], policyCommit: 'a'.repeat(40) });
reserveReview(board, first, { agentId: reviewer, leaseMs: 60_000, policy: 'agents' });
verify(board, first, { agentId: reviewer, decision: 'ACCEPT', reason: ACCEPT_REASON, note: 'checked the example', head: acceptedCommit, digest: 'second', policy: 'agents' });
merged(board, first, { agentId: coordinator, commit: 'c'.repeat(40) });
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index 118a9425..4881d336 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -43,15 +43,15 @@ Each move checks its guards in this order and refuses with the first one that do
| Move | From | To | Who | Guards, in order |
| --- | --- | --- | --- | --- |
-| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION) |
+| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG) |
| release | claimed | open | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS) |
| lapse | claimed | open | clock, when its lease runs out | none |
-| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT), gateConfigured (NO_GATE), gateGreen (GATE_RED), treeStillDuringGate (MOVED_DURING_GATE), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |
+| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG), gateConfigured (NO_GATE), gateGreen (GATE_RED), treeStillDuringGate (MOVED_DURING_GATE), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |
| reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD) |
-| accept | submitted | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), proofNoted (PROOF_REQUIRED) |
-| reject | submitted | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED) |
+| accept | submitted | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), itemCheckGreen (CHECK_RED), proofNoted (PROOF_REQUIRED) |
+| reject | submitted | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED) |
| escalate | open, claimed | open | agent, coordinator | joined (NOT_JOINED), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED) |
-| refreeze | open, claimed, submitted | open | coordinator | joined (NOT_JOINED), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION) |
+| refreeze | open, claimed, submitted | open | coordinator | joined (NOT_JOINED), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG) |
| withdraw | open, claimed, submitted | withdrawn | coordinator | joined (NOT_JOINED), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), inState (CLOSED) |
## Exit guards
@@ -88,16 +88,25 @@ Each move checks its guards in this order and refuses with the first one that do
| ONE_CLAIM | the caller holds no other live top-level claim, reworks of its own rejected items aside | submit or release the other item first; child items are free |
| UNKNOWN_SPEC | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | fix the spec, or the coordinator withdraws the item |
| A5_GRAMMAR_VERSION | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | upgrade Pullboard or use a file written for grammar 1 |
+| NO_POLICY | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | restore the committed coordinator policy |
+| BAD_CONFIG | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | repair and commit the coordinator configuration |
| CRITERIA_CHANGED | the criterion and the rows it cites read as they did at claim | the coordinator runs pullboard refreeze <id> |
| DIRTY | the worktree has no uncommitted changes | commit your changes, then submit |
| UNTRACKED | the worktree has no untracked files | commit or ignore them, then submit |
| NO_COMMIT | there is a commit to submit | commit your work, then submit |
| NO_GATE | the repo names a gate command | set "gate" in pullboard.json, e.g. "npm test" |
+| OUTSIDE_LANE | the full claimed diff respects committed coordinator ownership | restore foreign paths or shout their owner |
+| NO_POLICY | the full claimed diff respects committed coordinator ownership | restore the claim base or ask the coordinator to refreeze |
+| BAD_CONFIG | the full claimed diff respects committed coordinator ownership | restore the committed coordinator configuration |
+| CHECK_RED | the frozen item check passes at the exact submitted commit | reject the failing behavior; the builder fixes and resubmits |
| GATE_RED | the gate, which submit runs itself every time, is green at HEAD | fix what the digest names, commit, submit again |
| MOVED_DURING_GATE | when the gate ends, HEAD and every tracked file are as they were when it started | leave the worktree alone until the gate finishes, then submit again |
| CHILDREN_OPEN | every child item is verified or withdrawn | finish the child items, or the coordinator withdraws them |
| HEAD_NOT_NEW | a verifier has not already rejected this commit | commit the rework, then submit |
| NOT_AT_COMMIT | the caller's checkout contains the submitted commit | git switch --detach <commit> |
+| OUTSIDE_LANE | the caller's checkout contains the submitted commit | restore foreign paths before accepting |
+| NO_POLICY | the caller's checkout contains the submitted commit | restore the frozen policy objects |
+| BAD_CONFIG | the caller's checkout contains the submitted commit | repair the committed coordinator configuration |
| SELF_VERIFY | the caller did not build it | another agent verifies it: pullboard next --verify |
| COORDINATOR_VERIFIES | the repo's verify policy lets the caller verify this lane's work | the coordinator verifies it |
| O2_FAMILY_MATCH | the builder and verifier have known, different declared families, verify.family is require | ask the coordinator for a verifier from another declared family |
diff --git a/src/board.js b/src/board.js
index 0389731e..f990f47e 100644
--- a/src/board.js
+++ b/src/board.js
@@ -892,10 +892,10 @@ export function release(board, id, agentId) {
*
* @param {any} board
* @param {number} id
- * @param {{ agentId: string, commit: string, tree: string, files?: string[] }} at - `files`: what the
+ * @param {{ agentId: string, commit: string, tree: string, files?: string[], policyCommit?: string }} at - `files`: what the
* item's own commits changed since its claim; a rework adds to what the first attempt changed.
*/
-export function submit(board, id, { agentId, commit, tree, files = [] }) {
+export function submit(board, id, { agentId, commit, tree, files = [], policyCommit = null }) {
atomic(board, () => {
const notYours = () => new Refused('NOT_YOURS', `item #${id} is not claimed by you; claim it first`);
moveItem(board, id, 'submit', {
@@ -907,6 +907,7 @@ export function submit(board, id, { agentId, commit, tree, files = [] }) {
treeClean: null,
nothingUntracked: null,
hasCommit: null,
+ withinLane: null,
gateConfigured: null,
gateGreen: null,
treeStillDuringGate: null,
@@ -932,7 +933,7 @@ export function submit(board, id, { agentId, commit, tree, files = [] }) {
item_files: [...new Set([...(found.item_files ?? '').split('\n').filter(Boolean), ...files])].join('\n'),
}),
});
- logEvent(board, agentId, 'submit', id, { commit, tree });
+ logEvent(board, agentId, 'submit', id, { commit, tree, ...(policyCommit ? { policyCommit } : {}) });
});
}
@@ -1065,6 +1066,7 @@ export function verify(board, id, { agentId, decision, reason, note = '', head,
? null
: new Refused('CRITERIA_CHANGED', `the criterion for #${id} changed after it was claimed; the coordinator runs: pullboard refreeze ${id}`),
reasonIsMet: () => (reason && reason !== ACCEPT_REASON ? new Refused('BAD_REASON', `accept means ${ACCEPT_REASON}; a failed criterion is a reject`) : null),
+ itemCheckGreen: null,
proofNoted: () =>
note.trim()
? null
diff --git a/src/cli.js b/src/cli.js
index ffb6ccae..0fa81ff1 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -2,6 +2,7 @@
* The pullboard command line: every command, bound to who is asking (B3). The main checkout is the
* coordinator; every other worktree is the agent that joined from it.
*/
+import { createHash } from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
@@ -50,6 +51,7 @@ import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
import { exportView, serveView } from './serve.js';
import { serveApi } from './api.js';
import { doctorProblems } from './doctor.js';
+import { mainPolicy, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots } from './trusted-policy.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
import { loadMachineSettings, setGateSlots } from './settings.js';
@@ -424,7 +426,15 @@ function whoAmI(ctx, board) {
* @param {any} ctx
* @returns {(item: any) => { text: string, digest: string }}
*/
-const freezer = (ctx) => (item) => frozenCriterion(loadSpec(ctx.info.root, ctx.config), item);
+const freezer = (ctx) => (item) => {
+ const prior = item.item_frozen ? JSON.parse(item.item_frozen) : null;
+ const policy = prior?.policy ?? (!prior && !(ctx.info.isMain && !headCommit(ctx.info.root)) ? { version: 1, commit: mainPolicy(ctx.info.root).commit } : null);
+ const config = policy ? itemPolicy(ctx.info.root, { ...item, item_frozen: JSON.stringify({ policy }) }).config : ctx.config;
+ const frozen = frozenCriterion(loadSpec(ctx.info.root, config), item);
+ if (!policy) return frozen; // Legacy criteria retain their original digest and committed claim base.
+ const text = JSON.stringify({ ...JSON.parse(frozen.text), policy });
+ return { text, digest: createHash('sha256').update(text).digest('hex') };
+};
/**
* The evidence a shout carries, from its flags (B22). The commit is resolved here, in this repo,
@@ -1088,6 +1098,17 @@ function readCommands(io, { first, second, rest, values }) {
*/
async function submitHere(ctx, id) {
const { root } = ctx.info;
+ const held = withBoard(ctx, (board) => {
+ const me = whoAmI(ctx, board);
+ const item = store.getItem(board, id);
+ if (item.item_status !== 'claimed' || item.item_owner !== me.id) throw new Refused('NOT_YOURS', 'claim this item before submitting it');
+ return item;
+ });
+ const policy = itemPolicy(root, held);
+ const acceptedMain = mainPolicy(root);
+ ctx = { ...ctx, config: policy.config };
+ const dependencies = withBoard(ctx, board => dependencySnapshots(board.db, held));
+ submissionPaths(root, held, headCommit(root), { mainCommit: acceptedMain.commit, dependencies });
const { me, claimHead } = withBoard(ctx, (board) => {
const who = whoAmI(ctx, board);
const item = store.getItem(board, id);
@@ -1130,7 +1151,7 @@ async function submitHere(ctx, id) {
`when the gate ended, HEAD or a tracked file differed from ${commit.slice(0, 12)}, the commit it started on, so the gate did not end on what you would submit; leave the worktree alone until the gate finishes, then submit again`,
);
}
- withBoard(ctx, (board) => store.submit(board, id, { agentId: me.id, commit, tree: headTree(root) ?? '', files: filesSince(root, id, claimHead, commit) }));
+ withBoard(ctx, (board) => store.submit(board, id, { agentId: me.id, commit, tree: headTree(root) ?? '', files: filesSince(root, id, claimHead, commit), policyCommit: acceptedMain.commit }));
const pin = `refs/pullboard/items/${id}/${commit.slice(0, 12)}`;
git(root, ['update-ref', pin, commit]);
ctx.io.result?.({ id, commit, pin, gate: { green: gate.isGreen, report: gateReport(gate) } });
@@ -1160,6 +1181,8 @@ function verifyHere(ctx, id, { second, values }) {
if (item.item_status !== 'submitted') {
throw new Refused('NOT_SUBMITTED', `item #${id} is ${item.item_status}, not submitted`);
}
+ const policy = itemPolicy(root, item);
+ ctx = { ...ctx, config: policy.config };
const head = headCommit(root) ?? '';
const commit = resolveCommit(root, item.item_commit);
if (!commit || !contains(root, commit, head)) {
@@ -1171,6 +1194,12 @@ function verifyHere(ctx, id, { second, values }) {
} catch (error) {
if (!(error instanceof Refused) || error.code === 'A5_GRAMMAR_VERSION') throw error;
}
+ if (decision === 'ACCEPT') {
+ if (digest !== item.item_frozen_digest) throw new Refused('CRITERIA_CHANGED', 'the criterion changed; ask the coordinator to refreeze this item before checking it');
+ if (!checkAtCommit(root, item).green) throw new Refused('CHECK_RED', 'the frozen item check is red at the submitted commit; reject with the failing behavior or ask the builder to fix and resubmit');
+ const receipt = store.events(board, { itemId: id }).filter(event => event.event_kind === 'submit').map(event => JSON.parse(event.event_detail)).find(event => event.commit === commit);
+ submissionPaths(root, item, commit, { mainCommit: receipt?.policyCommit, dependencies: dependencySnapshots(board.db, item) });
+ }
return store.verify(board, id, {
agentId: me.id,
decision,
@@ -1404,10 +1433,13 @@ function workCommands(io, args) {
if (!held) throw new Refused('NOT_HOLDING', 'you hold no item; name one, pullboard check <id>, or run the project gate: pullboard gate');
return held;
});
- if (!item.item_check) throw new Refused('NO_CHECK', `#${item.item_id} has no check command; its proof is the project gate: pullboard gate`);
- const run = runShell(ctx.info.root, item.item_check);
- io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check: item.item_check, report: run.isGreen ? '' : digestOf(run.output) });
- io.say(`check ${run.isGreen ? 'green' : 'red'} in ${run.seconds}s: ${item.item_check}`);
+ const check = frozenCheck(item);
+ if (!check) throw new Refused('NO_CHECK', `#${item.item_id} has no check command; its proof is the project gate: pullboard gate`);
+ if (item.item_claim_head) itemPolicy(ctx.info.root, item);
+ else mainPolicy(ctx.info.root);
+ const run = runShell(ctx.info.root, check);
+ io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check, report: run.isGreen ? '' : digestOf(run.output) });
+ io.say(`check ${run.isGreen ? 'green' : 'red'} in ${run.seconds}s: ${check}`);
if (!run.isGreen) io.say(digestOf(run.output).replace(/^/gm, ' '));
return run.isGreen ? 0 : 1;
},
@@ -1816,7 +1848,7 @@ async function runCommand(argv, io) {
}
if (command === 'gate') {
const ctx = context(io);
- const gate = await runGate(ctx.info.root, ctx.config, { onWait: gateWaitReporter(io) });
+ const gate = await runGate(ctx.info.root, mainPolicy(ctx.info.root).config, { onWait: gateWaitReporter(io) });
io.result?.({ green: gate.isGreen, report: gateReport(gate) });
io.say(gateReport(gate));
return gate.isGreen ? 0 : 1;
diff --git a/src/config.js b/src/config.js
index d7ffa1f4..6b00548c 100644
--- a/src/config.js
+++ b/src/config.js
@@ -187,12 +187,14 @@ export function loadConfig(root) {
if (!existsSync(file)) {
throw new Refused('NO_CONFIG', `no ${CONFIG_FILE} in ${root}; run: pullboard init`);
}
+ return configFromSource(readFileSync(file, 'utf8'));
+}
+
+/** Parse committed coordinator settings with the same defaults and validation as local settings. */
+export function configFromSource(source) {
let raw;
- try {
- raw = JSON.parse(readFileSync(file, 'utf8'));
- } catch (error) {
- throw new Refused('BAD_CONFIG', `${CONFIG_FILE} is not valid JSON (${error.message})`);
- }
+ try { raw = JSON.parse(source); }
+ catch { throw new Refused('BAD_CONFIG', 'pullboard.json is not valid JSON; restore the coordinator configuration'); }
const config = merge(defaults(), raw);
const problems = configProblems(config);
if (problems.length) throw new Refused('BAD_CONFIG', `${CONFIG_FILE}: ${problems.join('; ')}`);
diff --git a/src/doctor.js b/src/doctor.js
index 1fd8730d..a96efca7 100644
--- a/src/doctor.js
+++ b/src/doctor.js
@@ -1,6 +1,7 @@
/** Read-only integrity checks for a pullboard board file (A6). */
import { existsSync } from 'node:fs';
import { DatabaseSync } from 'node:sqlite';
+import { checkAtCommit, submissionPaths, dependencySnapshots } from './trusted-policy.js';
import { BLANKS, STATES, storeTriggers } from './machine.js';
import { readEventLogVersion, SCHEMA_VERSION } from './board.js';
@@ -33,6 +34,7 @@ export function doctorProblems(file, root, tryGit) {
...(layout.itemFields ? itemProblems(db) : []),
...(layout.itemPins ? pinProblems(db, root, tryGit) : []),
...(layout.verdicts ? verdictProblems(db, root, tryGit) : []),
+ ...(layout.itemAudit ? submissionProblems(db, root) : []),
];
} finally {
db.close();
@@ -52,7 +54,7 @@ const finding = (code, message, next) => ({ code, message, next });
/** Inspect the layout before each row check, retaining trigger findings on an incomplete board. */
function layoutProblems(db) {
const required = {
- item: [...new Set(['item_id', 'item_status', 'item_commit', ...STATES.flatMap((state) => state.requires)])],
+ item: [...new Set(['item_id', 'item_status', 'item_commit', 'item_claim_head', 'item_lane', 'item_frozen', 'item_merged_commit', ...STATES.flatMap((state) => state.requires)])],
verdict: ['verdict_id', 'item_id', 'verdict_commit'],
};
const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((table) => table.name));
@@ -74,6 +76,7 @@ function layoutProblems(db) {
problems,
itemFields: has('item', ['item_id', 'item_status']),
itemPins: has('item', ['item_id', 'item_status', 'item_commit']),
+ itemAudit: has('item', ['item_id', 'item_status', 'item_commit', 'item_claim_head', 'item_lane', 'item_frozen', 'item_merged_commit']),
verdicts: has('verdict', required.verdict),
};
}
@@ -166,3 +169,20 @@ function verdictProblems(db, root, tryGit) {
return [finding('VERDICT_COMMIT_MISSING', `verdict #${verdict.verdict_id} for item #${verdict.item_id} names missing commit ${verdict.verdict_commit}`, `fetch the commit if needed, then run git update-ref ${pin} ${verdict.verdict_commit}`)];
});
}
+
+/** Audit the pinned submission, including its pre-merge policy proof, without changing the board or live checkout. */
+function submissionProblems(db, root) {
+ const problems = [];
+ const eventsExist = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='event'").get();
+ for (const item of db.prepare("SELECT * FROM item WHERE item_status='verified' OR item_merged_commit IS NOT NULL ORDER BY item_id").all()) {
+ try {
+ const events = eventsExist ? db.prepare("SELECT event_detail FROM event WHERE item_id=? AND event_kind='submit' ORDER BY event_id DESC").all(item.item_id) : [];
+ const proof = events.map(event => JSON.parse(event.event_detail)).find(event => event.commit === item.item_commit);
+ submissionPaths(root, item, item.item_commit, { mainCommit: proof?.policyCommit, dependencies: dependencySnapshots(db, item) });
+ } catch (error) {
+ problems.push(finding(error.code ?? 'SUBMISSION_POLICY', 'item #' + item.item_id + ': ' + (error.code === 'OUTSIDE_LANE' ? error.message : 'its committed submission policy or claim base cannot be checked'), 'ask the coordinator to restore the original policy and inspect this submission'));
+ }
+ if (!checkAtCommit(root, item).green) problems.push(finding('CHECK_RED', 'item #' + item.item_id + ' has a red frozen check at ' + item.item_commit, 'ask the coordinator to record and repair the failing submission'));
+ }
+ return problems;
+}
diff --git a/src/git.js b/src/git.js
index bbc75048..6b753ef0 100644
--- a/src/git.js
+++ b/src/git.js
@@ -7,7 +7,7 @@ import { existsSync, readdirSync, statSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { Refused } from './refused.js';
-const GIT_FLAGS = ['-c', 'core.quotepath=false'];
+const GIT_FLAGS = ['--no-replace-objects', '-c', 'core.quotepath=false'];
/**
* The environment for a gate or fixer: keep the user's settings, but remove Git's repository-local
@@ -20,6 +20,7 @@ const GIT_FLAGS = ['-c', 'core.quotepath=false'];
export function gitChildEnv(root) {
const env = { ...process.env };
for (const name of git(root, ['rev-parse', '--local-env-vars']).split('\n')) delete env[name];
+ env.GIT_NO_REPLACE_OBJECTS = '1'; // Exact-tree receipts must never resolve replacement refs.
return env;
}
diff --git a/src/machine.js b/src/machine.js
index be07b290..0aa9f8ee 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -105,17 +105,19 @@ export const GUARDS = [
{ id: 'notHeldByAnother', refuse: 'HELD', rule: 'no other agent holds it under a live lease', next: 'pullboard next', source: 'board' },
{ id: 'laneOpen', refuse: 'LANE_HELD', rule: 'nobody holds its lane', next: 'pullboard next --wait 9 (minutes)', source: 'board', when: 'unless the caller is renewing its own live claim' },
{ id: 'oneLiveClaim', refuse: 'ONE_CLAIM', rule: 'the caller holds no other live top-level claim, reworks of its own rejected items aside', next: 'submit or release the other item first; child items are free', source: 'board' },
- { id: 'rowsInForce', refuse: 'UNKNOWN_SPEC', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or use a file written for grammar 1' }], rule: 'every row the item cites exists and is in force', next: 'fix the spec, or the coordinator withdraws the item', source: 'board', when: 'only where the criterion freezes: claiming an item with no frozen criterion, and refreeze' },
+ { id: 'rowsInForce', refuse: 'UNKNOWN_SPEC', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or use a file written for grammar 1' }, { code: 'NO_POLICY', next: 'restore the committed coordinator policy' }, { code: 'BAD_CONFIG', next: 'repair and commit the coordinator configuration' }], rule: 'every row the item cites exists and is in force', next: 'fix the spec, or the coordinator withdraws the item', source: 'board', when: 'only where the criterion freezes: claiming an item with no frozen criterion, and refreeze' },
{ id: 'criterionUnchanged', refuse: 'CRITERIA_CHANGED', rule: 'the criterion and the rows it cites read as they did at claim', next: 'the coordinator runs pullboard refreeze <id>', source: 'cli' },
{ id: 'treeClean', refuse: 'DIRTY', rule: 'the worktree has no uncommitted changes', next: 'commit your changes, then submit', source: 'cli' },
{ id: 'nothingUntracked', refuse: 'UNTRACKED', rule: 'the worktree has no untracked files', next: 'commit or ignore them, then submit', source: 'cli' },
{ id: 'hasCommit', refuse: 'NO_COMMIT', rule: 'there is a commit to submit', next: 'commit your work, then submit', source: 'cli' },
{ id: 'gateConfigured', refuse: 'NO_GATE', rule: 'the repo names a gate command', next: 'set "gate" in pullboard.json, e.g. "npm test"', source: 'cli' },
+ { id: 'withinLane', refuse: 'OUTSIDE_LANE', alsoRefuses: [{ code: 'NO_POLICY', next: 'restore the claim base or ask the coordinator to refreeze' }, { code: 'BAD_CONFIG', next: 'restore the committed coordinator configuration' }], rule: 'the full claimed diff respects committed coordinator ownership', next: 'restore foreign paths or shout their owner', source: 'cli' },
+ { id: 'itemCheckGreen', refuse: 'CHECK_RED', rule: 'the frozen item check passes at the exact submitted commit', next: 'reject the failing behavior; the builder fixes and resubmits', source: 'cli' },
{ id: 'gateGreen', refuse: 'GATE_RED', rule: 'the gate, which submit runs itself every time, is green at HEAD', next: 'fix what the digest names, commit, submit again', source: 'cli' },
{ id: 'treeStillDuringGate', refuse: 'MOVED_DURING_GATE', rule: 'when the gate ends, HEAD and every tracked file are as they were when it started', next: 'leave the worktree alone until the gate finishes, then submit again', source: 'cli' },
{ id: 'childrenDone', refuse: 'CHILDREN_OPEN', rule: 'every child item is verified or withdrawn', next: 'finish the child items, or the coordinator withdraws them', source: 'board' },
{ id: 'headIsNew', refuse: 'HEAD_NOT_NEW', rule: 'a verifier has not already rejected this commit', next: 'commit the rework, then submit', source: 'board' },
- { id: 'atSubmittedCommit', refuse: 'NOT_AT_COMMIT', rule: "the caller's checkout contains the submitted commit", next: 'git switch --detach <commit>', source: 'cli' },
+ { id: 'atSubmittedCommit', refuse: 'NOT_AT_COMMIT', alsoRefuses: [{ code: 'OUTSIDE_LANE', next: 'restore foreign paths before accepting' }, { code: 'NO_POLICY', next: 'restore the frozen policy objects' }, { code: 'BAD_CONFIG', next: 'repair the committed coordinator configuration' }], rule: "the caller's checkout contains the submitted commit", next: 'git switch --detach <commit>', source: 'cli' },
{ id: 'notBuilder', refuse: 'SELF_VERIFY', rule: 'the caller did not build it', next: 'another agent verifies it: pullboard next --verify', source: 'board' },
{ id: 'policyAllows', refuse: 'COORDINATOR_VERIFIES', rule: "the repo's verify policy lets the caller verify this lane's work", next: 'the coordinator verifies it', source: 'board' },
{ id: 'familyAllows', refuse: 'O2_FAMILY_MATCH', rule: 'the builder and verifier have known, different declared families', next: 'ask the coordinator for a verifier from another declared family', source: 'board', when: 'verify.family is require' },
@@ -140,7 +142,7 @@ export const MOVES = [
{ verb: 'lapse', from: ['claimed'], to: 'open', by: ['clock'], guards: [], when: 'its lease runs out' },
{
verb: 'submit', from: ['claimed'], to: 'submitted', by: ['agent', 'coordinator'], refuse: 'NOT_YOURS',
- guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],
+ guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],
sets: ['item_built_by', 'item_commit'], command: 'pullboard submit <id>',
},
{
@@ -150,7 +152,7 @@ export const MOVES = [
},
{
verb: 'accept', from: ['submitted'], to: 'verified', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED',
- guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonIsMet', 'proofNoted'],
+ guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonIsMet', 'itemCheckGreen', 'proofNoted'],
sets: ['item_verified_by'], command: 'pullboard verify <id> accept --note "..."',
},
{
diff --git a/src/trusted-policy.js b/src/trusted-policy.js
new file mode 100644
index 00000000..ebe36130
--- /dev/null
+++ b/src/trusted-policy.js
@@ -0,0 +1,114 @@
+/** Coordinator policy and immutable submission checks cannot come from a builder's candidate [V4,V16,L3,M3]. */
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { configFromSource } from './config.js';
+import { outOfLane } from './lanes.js';
+import { Refused } from './refused.js';
+
+/** Keep private checkouts independent of inherited Git repository and index bindings. */
+function cleanGitEnvironment() {
+ const env = { ...process.env };
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_PREFIX', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_NO_REPLACE_OBJECTS', 'GIT_REPLACE_REF_BASE', 'GIT_SHALLOW_FILE']) delete env[key];
+ for (const key of Object.keys(env)) if (/^GIT_CONFIG_(?:KEY|VALUE)_/.test(key)) delete env[key];
+ env.GIT_NO_REPLACE_OBJECTS = '1'; // A pin identifies the underlying object, never refs/replace fiction.
+ return env;
+}
+
+/** Read raw Git output, retaining NUL-delimited names without exposing Git diagnostics. */
+function policyGit(root, args) {
+ const result = spawnSync('git', ['-c', 'core.quotepath=false', ...args], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
+ if (result.status !== 0) throw new Refused('NO_POLICY', 'the committed coordinator policy or claim base is missing; restore its Git objects or ask the coordinator to refreeze the item');
+ return result.stdout;
+}
+
+/** Resolve the primary checkout's committed HEAD, independently of a linked or detached checkout. */
+export function mainPolicy(root) {
+ const common = policyGit(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();
+ const commit = policyGit(root, ['--git-dir', common, 'rev-parse', '--verify', 'HEAD^{commit}']).trim();
+ return policyAt(root, commit);
+}
+
+/** Re-read coordinator settings from a pinned Git object; never from the candidate filesystem. */
+export function policyAt(root, commit) {
+ if (!/^[0-9a-f]{40,64}$/.test(commit ?? '')) throw new Refused('NO_POLICY', 'this item has no recorded claim base; ask the coordinator to refreeze it and claim it again');
+ const config = configFromSource(policyGit(root, ['show', commit + ':pullboard.json']));
+ return { version: 1, commit, config };
+}
+
+/** Use new claims' frozen policy; legacy claims retain their committed claim-base settings. */
+export function itemPolicy(root, item) {
+ let frozen;
+ try { frozen = JSON.parse(item.item_frozen ?? 'null'); }
+ catch { throw new Refused('NO_POLICY', 'the frozen criterion is invalid; ask the coordinator to refreeze this item'); }
+ return policyAt(root, frozen?.policy?.commit ?? item.item_claim_head);
+}
+
+/** Compare a path's mode and object, including deletions, against an authenticated main snapshot. */
+function pathObject(root, commit, path) {
+ return policyGit(root, ['ls-tree', '-z', commit, '--', ':(literal)' + path]);
+}
+
+/** Enforce the complete claim-base diff; accepted-main merges may carry only identical foreign objects. */
+export function submissionPaths(root, item, commit, { config, mainCommit, dependencies = [] } = {}) {
+ const policy = itemPolicy(root, item);
+ const base = item.item_claim_head;
+ if (!/^[0-9a-f]{40,64}$/.test(base ?? '')) throw new Refused('NO_POLICY', 'this item has no claim base; ask the coordinator to refreeze it and claim again');
+ policyGit(root, ['rev-parse', '--verify', base + '^{commit}']);
+ const changed = [base, policy.commit].flatMap(start => policyGit(root, ['diff', '--no-renames', '--name-only', '-z', start, commit, '--']).split('\0').filter(Boolean));
+ const paths = [...new Set(changed)];
+ const ownership = config ?? policy.config;
+ const foreign = paths.filter(path => outOfLane(ownership, item.item_lane, [path]).length);
+ const snapshot = mainCommit ?? policy.commit;
+ policyAt(root, snapshot); // Reject a malformed historical proof before it can become a Git argument.
+ const accepted = dependencies.map(dependency => ({ ...dependency,
+ paths: new Set(policyGit(root, ['diff', '--no-renames', '--name-only', '-z', dependency.base, dependency.commit, '--']).split('\0').filter(Boolean)),
+ }));
+ const denied = foreign.filter(path => {
+ const object = pathObject(root, commit, path);
+ if (object === pathObject(root, snapshot, path)) return false;
+ return !accepted.some(dependency => dependency.paths.has(path)
+ && !outOfLane(ownership, dependency.lane, [path]).length
+ && object === pathObject(root, dependency.commit, path));
+ });
+ if (denied.length) throw new Refused('OUTSIDE_LANE', 'outside the ' + item.item_lane + ' lane: ' + outOfLane(ownership, item.item_lane, denied).join(', ') + '; shout the owner and restore these paths before submitting');
+ return paths;
+}
+
+/** Verified dependencies may contribute their own unchanged lane files before the coordinator merges them [N16]. */
+export function dependencySnapshots(db, item) {
+ const ids = String(item.item_after ?? '').split(',').map(Number).filter(id => Number.isSafeInteger(id) && id > 0);
+ return ids.flatMap(id => {
+ const row = db.prepare("SELECT item_lane, item_claim_head, item_commit FROM item WHERE item_id=? AND item_status='verified' AND EXISTS (SELECT 1 FROM verdict WHERE item_id=? AND verdict_decision='ACCEPT' AND verdict_commit=item.item_commit)").get(id, id);
+ return row?.item_claim_head && /^[0-9a-f]{40,64}$/.test(row.item_commit ?? '')
+ ? [{ lane: row.item_lane, base: row.item_claim_head, commit: row.item_commit }] : [];
+ });
+}
+
+/** Read the command frozen with the criterion, preventing a later edit from changing its proof. */
+export function frozenCheck(item) {
+ let frozen;
+ try { frozen = JSON.parse(item.item_frozen ?? 'null'); } catch { return ''; }
+ return frozen?.check ?? (item.item_frozen ? '' : item.item_check ?? '');
+}
+
+/** Run the frozen check at the exact submitted commit in a private clone, leaving live worktrees untouched. */
+export function checkAtCommit(root, item) {
+ const command = frozenCheck(item);
+ if (!command) return { green: true, checked: false };
+ const scratch = mkdtempSync(join(tmpdir(), 'pullboard-criterion-'));
+ const copy = join(scratch, 'repo');
+ const home = join(scratch, 'home');
+ mkdirSync(home, { mode: 0o700 });
+ const env = { ...cleanGitEnvironment(), HOME: home, PULLBOARD_HOME: join(home, '.pullboard'), PULLBOARD_MACHINE_HOME: join(home, 'machine'), GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
+ try {
+ const common = policyGit(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();
+ const clone = spawnSync('git', ['clone', '--quiet', '--shared', '--no-checkout', common, copy], { env, stdio: 'ignore' });
+ const checkout = clone.status === 0 && spawnSync('git', ['checkout', '--quiet', '--detach', item.item_commit], { cwd: copy, env, stdio: 'ignore' });
+ if (!checkout || checkout.status !== 0) return { green: false, checked: true };
+ const run = spawnSync('(\n' + command + '\n) 2>&1', { cwd: copy, env, shell: true, stdio: 'ignore', timeout: 300000 });
+ return { green: run.status === 0, checked: true };
+ } catch { return { green: false, checked: true }; }
+ finally { rmSync(scratch, { recursive: true, force: true }); }
+}
diff --git a/test/e2e.test.js b/test/e2e.test.js
index a6593677..ab2fbc4b 100644
--- a/test/e2e.test.js
+++ b/test/e2e.test.js
@@ -51,6 +51,7 @@ function sandbox() {
GIT_COMMITTER_NAME: 'Test Agent',
GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(dir, 'pullboard-home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
};
const git = (cwd, ...args) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
const tryGit = (cwd, ...args) => spawnSync('git', args, { cwd, env, encoding: 'utf8' });
@@ -1738,3 +1739,208 @@ test('doctrine init preserves legacy rules and outside guidance, refreshes label
assert.equal(removed.code, 1);
assert.match(removed.out, /ways.md: PB2 error:.*ids are permanent/, 'inherited PB2 cannot hide removal of a committed repo override');
});
+
+/** Build an adversarial Git object directly; submit must be safe even when no commit hook ran. */
+function attackCommit(box, cwd) {
+ box.git(cwd, 'add', '-A');
+ const tree = box.git(cwd, 'write-tree');
+ const commit = box.git(cwd, 'commit-tree', tree, '-p', 'HEAD', '-m', 'feat(web): adversarial fixture [G1]');
+ box.git(cwd, 'update-ref', 'HEAD', commit);
+ return commit;
+}
+
+test('the blind gate-bypass repro refuses submit and accept, and doctor audits pre-merge policy [V4,V16,L3,M3]', () => {
+ const box = project('true');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Append notes', '--specs', 'G1', '--criterion', 'append one note', '--check', 'test ! -f web/RED_CHECK').code, 0);
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ const original = JSON.parse(box.run(box.web, 'show', '1', '--json').out);
+ mkdirSync(join(box.web, 'web'));
+ writeFileSync(join(box.web, 'web/RED_CHECK'), 'red');
+ const config = JSON.parse(readFileSync(join(box.web, 'pullboard.json'), 'utf8'));
+ config.gate = 'true';
+ config.lanes.web.owns.push('pullboard.json');
+ writeFileSync(join(box.web, 'pullboard.json'), JSON.stringify(config));
+ const commit = attackCommit(box, box.web);
+ const submitted = box.run(box.web, 'submit', '1', '--json');
+ assert.equal(submitted.code, 1);
+ assert.equal(JSON.parse(submitted.out).error.code, 'OUTSIDE_LANE');
+ assert.equal(JSON.parse(submitted.out).error.message.includes('pullboard.json'), true);
+ assert.equal(box.run(box.web, 'check', '1').code, 1, 'the original item check stays red');
+
+ // Model a historical unchecked receipt using the low-level engine in this private fixture.
+ const board = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));
+ try { store.submit(board, 1, { agentId: 'web-1', commit, tree: box.git(box.web, 'rev-parse', 'HEAD^{tree}'), policyCommit: original.item_claim_head }); }
+ finally { store.closeBoard(board); }
+ box.git(box.repo, 'update-ref', 'refs/pullboard/items/1/' + commit.slice(0, 12), commit);
+ const review = join(box.dir, 'review');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);
+ assert.equal(box.run(review, 'join', 'api').code, 0);
+ const accepted = box.run(review, 'verify', '1', 'accept', '--note', 'private repro', '--json');
+ assert.equal(accepted.code, 1);
+ assert.equal(JSON.parse(accepted.out).error.code, 'CHECK_RED');
+ assert.equal(JSON.parse(box.run(review, 'show', '1', '--json').out).item_status, 'submitted');
+
+ const history = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));
+ try { store.verify(history, 1, { agentId: 'api-1', decision: 'ACCEPT', note: 'synthetic historical unchecked verdict', head: commit, digest: original.item_frozen_digest, policy: 'any' }); }
+ finally { store.closeBoard(history); }
+ box.git(box.repo, 'merge', '--ff-only', '-q', 'web/one');
+ assert.equal(box.run(box.repo, 'merged', '1', commit).code, 0);
+ const file = join(box.repo, '.git/pullboard/board.sqlite');
+ const before = readFileSync(file);
+ const doctor = box.run(box.repo, 'doctor', '--json');
+ assert.equal(doctor.code, 1);
+ const problems = JSON.parse(doctor.out).problems;
+ assert.equal(problems.some(problem => problem.code === 'OUTSIDE_LANE' && problem.message.includes('pullboard.json')), true,
+ 'post-merge HEAD cannot retrospectively authorize the malicious policy edit');
+ assert.equal(problems.some(problem => problem.code === 'CHECK_RED'), true);
+ assert.deepEqual(readFileSync(file), before, 'doctor keeps the historical evidence unchanged');
+});
+
+test('a shared config edit cannot replace the gate frozen from the coordinator [V4,V16]', () => {
+ const box = project('test ! -f web/RED');
+ const config = JSON.parse(readFileSync(join(box.repo, 'pullboard.json'), 'utf8'));
+ config.shared.push('pullboard.json');
+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify(config));
+ box.git(box.repo, 'add', 'pullboard.json');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: share fixture config');
+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Frozen gate', '--specs', 'G1', '--criterion', 'original gate passes').code, 0);
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ mkdirSync(join(box.web, 'web'));
+ writeFileSync(join(box.web, 'web/RED'), 'red');
+ config.gate = 'true';
+ writeFileSync(join(box.web, 'pullboard.json'), JSON.stringify(config));
+ box.git(box.web, 'add', '-A');
+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): fixture config change [G1]');
+ const refused = box.run(box.web, 'submit', '1', '--json');
+ assert.equal(refused.code, 1);
+ assert.equal(JSON.parse(refused.out).error.code, 'GATE_RED', 'the committed original gate executes even though the candidate says true');
+});
+
+test('accepted-main merges carry foreign files without granting permission to alter them [L3,V4]', () => {
+ const box = project('true');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Main merge', '--specs', 'G1', '--criterion', 'foreign main object preserved').code, 0);
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ writeFileSync(join(box.repo, 'coordinator.txt'), 'accepted main fixture');
+ box.git(box.repo, 'add', 'coordinator.txt');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: coordinator fixture');
+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');
+ mkdirSync(join(box.web, 'web'));
+ writeFileSync(join(box.web, 'web/index.html'), 'app fixture');
+ box.git(box.web, 'add', 'web/index.html');
+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): preserve main fixture [G1]');
+ assert.equal(box.run(box.web, 'submit', '1').code, 0, 'unchanged accepted-main foreign objects are allowed');
+ const commit = box.git(box.web, 'rev-parse', 'HEAD');
+ box.git(box.repo, 'merge', '-q', '--ff-only', 'web/one');
+ assert.equal(box.run(box.repo, 'verify', '1', 'accept', '--as', 'coordinator', '--note', 'private accepted-main fixture').code, 0);
+ assert.equal(box.run(box.repo, 'doctor').code, 0, 'the pre-merge main proof remains available for historical audit');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Alter foreign file', '--specs', 'G1', '--criterion', 'ownership remains enforced').code, 0);
+ assert.equal(box.run(box.web, 'claim', '2').code, 0);
+ writeFileSync(join(box.web, 'coordinator.txt'), 'unauthorized replacement');
+ attackCommit(box, box.web);
+ const refused = box.run(box.web, 'submit', '2', '--json');
+ assert.equal(refused.code, 1);
+ assert.equal(JSON.parse(refused.out).error.code, 'OUTSIDE_LANE');
+});
+
+test('foreign changes before claiming and cross-lane renames cannot hide from submit [L3,V4]', () => {
+ for (const mode of ['before-claim', 'rename', 'delete']) {
+ const box = project('true');
+ writeFileSync(join(box.repo, 'foreign file.txt'), 'coordinator-owned');
+ box.git(box.repo, 'add', '-A');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore: foreign fixture');
+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');
+ assert.equal(box.run(box.repo, 'add', 'web', mode, '--specs', 'G1').code, 0);
+ if (mode === 'before-claim') {
+ writeFileSync(join(box.web, 'foreign file.txt'), 'unauthorized pre-claim replacement');
+ attackCommit(box, box.web);
+ }
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ mkdirSync(join(box.web, 'web'));
+ if (mode === 'rename') box.git(box.web, 'mv', 'foreign file.txt', 'web/moved.txt');
+ else if (mode === 'delete') box.git(box.web, 'rm', 'foreign file.txt');
+ writeFileSync(join(box.web, 'web/index.html'), 'owned');
+ attackCommit(box, box.web);
+ const refused = box.run(box.web, 'submit', '1', '--json');
+ assert.equal(refused.code, 1, mode);
+ assert.equal(JSON.parse(refused.out).error.code, 'OUTSIDE_LANE', mode);
+ assert.equal(JSON.parse(refused.out).error.message.includes('foreign file.txt'), true, mode);
+ }
+});
+
+test('accept reruns the frozen check at the submission even when the reviewer repaired its HEAD [V4,M3]', () => {
+ const box = project('true');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Exact check', '--specs', 'G1', '--check', 'test ! -f web/RED_CHECK').code, 0);
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ mkdirSync(join(box.web, 'web'));
+ writeFileSync(join(box.web, 'web/RED_CHECK'), 'red');
+ const commit = attackCommit(box, box.web);
+ assert.equal(box.run(box.web, 'submit', '1').code, 0, 'the project gate passes while the separate item check is red');
+ const review = join(box.dir, 'exact-review');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);
+ assert.equal(box.run(review, 'join', 'api').code, 0);
+ box.git(review, 'rm', 'web/RED_CHECK');
+ attackCommit(box, review); // Model the adversarial repair without disabling its lane hook.
+ assert.equal(box.run(review, 'check', '1').code, 0, 'the reviewer HEAD alone is green');
+ const refused = box.run(review, 'verify', '1', 'accept', '--note', 'reviewer repair is not submission proof', '--json');
+ assert.equal(refused.code, 1);
+ assert.equal(JSON.parse(refused.out).error.code, 'CHECK_RED');
+ assert.equal(JSON.parse(box.run(review, 'show', '1', '--json').out).item_status, 'submitted');
+});
+
+test('accept independently refuses a historically unchecked foreign submission [L3,M3]', () => {
+ const box = project('true');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Foreign receipt', '--specs', 'G1', '--check', 'true').code, 0);
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ writeFileSync(join(box.web, 'coordinator.txt'), 'unauthorized');
+ const commit = attackCommit(box, box.web);
+ const board = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));
+ try { store.submit(board, 1, { agentId: 'web-1', commit, tree: box.git(box.web, 'rev-parse', 'HEAD^{tree}') }); }
+ finally { store.closeBoard(board); }
+ const review = join(box.dir, 'foreign-review');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);
+ assert.equal(box.run(review, 'join', 'api').code, 0);
+ const refused = box.run(review, 'verify', '1', 'accept', '--note', 'a green check cannot authorize this path', '--json');
+ assert.equal(refused.code, 1);
+ assert.equal(JSON.parse(refused.out).error.code, 'OUTSIDE_LANE');
+});
+
+test('replacement refs cannot conceal the real submitted foreign paths [L3,V4,M3]', () => {
+ const box = project('true');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Replacement probe', '--specs', 'G1', '--check', 'true').code, 0);
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ const base = box.git(box.web, 'rev-parse', 'HEAD');
+ writeFileSync(join(box.web, 'coordinator.txt'), 'underlying unauthorized object');
+ const commit = attackCommit(box, box.web);
+ box.git(box.web, 'replace', commit, base);
+ box.git(box.web, 'reset', '--hard', 'HEAD');
+ assert.equal(existsSync(join(box.web, 'coordinator.txt')), false, 'Git normally shows the replacement tree');
+ const submitted = box.run(box.web, 'submit', '1', '--json');
+ assert.equal(submitted.code, 1);
+ assert.equal(JSON.parse(submitted.out).error.code, 'OUTSIDE_LANE');
+ const board = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));
+ try { store.submit(board, 1, { agentId: 'web-1', commit, tree: 'synthetic unchecked tree' }); }
+ finally { store.closeBoard(board); }
+ const review = join(box.dir, 'replacement-review');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);
+ assert.equal(box.run(review, 'join', 'api').code, 0);
+ const accepted = box.run(review, 'verify', '1', 'accept', '--note', 'the replacement is not the pinned object', '--json');
+ assert.equal(accepted.code, 1);
+ assert.equal(JSON.parse(accepted.out).error.code, 'OUTSIDE_LANE');
+});
+
+test('replacement refs cannot turn a red committed owned tree into a clean green submission [V4,V16]', () => {
+ const box = project('test ! -f web/RED');
+ assert.equal(box.run(box.repo, 'add', 'web', 'Exact red tree', '--specs', 'G1').code, 0);
+ assert.equal(box.run(box.web, 'claim', '1').code, 0);
+ const base = box.git(box.web, 'rev-parse', 'HEAD');
+ mkdirSync(join(box.web, 'web'));
+ writeFileSync(join(box.web, 'web/RED'), 'committed red');
+ const commit = attackCommit(box, box.web);
+ box.git(box.web, 'replace', commit, base);
+ box.git(box.web, 'reset', '--hard', 'HEAD');
+ assert.equal(existsSync(join(box.web, 'web/RED')), false, 'ordinary Git hides the failing committed file');
+ const submitted = box.run(box.web, 'submit', '1', '--json');
+ assert.equal(submitted.code, 1);
+ assert.equal(JSON.parse(submitted.out).error.code, 'DIRTY', 'the underlying tree differs from the files the gate would execute');
+});
diff --git a/test/machine.test.js b/test/machine.test.js
index ef8534dc..6297c8dc 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -422,6 +422,10 @@ test('a broken copy of the declaration fails the check against the code, both wa
assert.deepEqual(codeProblems(noRows).sort(), [
'A5_GRAMMAR_VERSION is raised by claim but not declared there',
'A5_GRAMMAR_VERSION is raised by refreeze but not declared there',
+ 'BAD_CONFIG is raised by claim but not declared there',
+ 'BAD_CONFIG is raised by refreeze but not declared there',
+ 'NO_POLICY is raised by claim but not declared there',
+ 'NO_POLICY is raised by refreeze but not declared there',
'UNKNOWN_SPEC is raised by claim but not declared there',
'UNKNOWN_SPEC is raised by refreeze but not declared there',
]);
@@ -762,9 +766,9 @@ test('pullboard help lists each role\'s moves from the declaration, and pullboar
/** Guards the CLI checks before it asks the board: the board's own order starts after them. */
const CLI_CHECKED = {
claim: ['joined'],
- submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'gateConfigured', 'gateGreen', 'treeStillDuringGate'],
+ submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'gateConfigured', 'gateGreen', 'treeStillDuringGate'],
reserve: ['coordinatorSaysAs', 'joined'],
- accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit'],
+ accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'itemCheckGreen'],
reject: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit'],
};