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.

feat(cli): refuse unverified submission stacks [V1,V17]

Corey Olson1397ace31c8e
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index e14b9e4c..9e17a1f1 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -52,9 +52,9 @@ Each move checks its guards in this order and refuses with the first one that do
| 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), reviewReleaseExplained (NOTE_REQUIRED) |
| 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), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), gateConfigured (NO_GATE), gateGreen (GATE_RED or PIPEFAIL_UNAVAILABLE), 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 or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), gateConfigured (NO_GATE), gateGreen (GATE_RED or PIPEFAIL_UNAVAILABLE), 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), reviewCooldownElapsed (REVIEW_COOLDOWN), 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 or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), itemCheckGreen (CHECK_RED or CHECK_UNVERIFIED), proofNoted (PROOF_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 or GIT_GRAFTS), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), itemCheckGreen (CHECK_RED or CHECK_UNVERIFIED), 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 or GIT_GRAFTS), 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 or NO_POLICY or BAD_CONFIG) |
@@ -109,6 +109,7 @@ Each move checks its guards in this order and refuses with the first one that do
| MERGE_CHECK_FAILED | the candidate merges cleanly into the current primary branch without changing an index or worktree | use Git 2.38 or newer, restore its objects and retry |
| NO_POLICY | the candidate merges cleanly into the current primary branch without changing an index or worktree | restore the primary repository metadata |
| NO_TRUNK | the candidate merges cleanly into the current primary branch without changing an index or worktree | check out the trunk branch in the main checkout once and run pullboard inbox |
+| STACKED_ON_UNVERIFIED | the candidate range contains no other item's unverified submitted commit | wait for that item to be accepted, or rebuild without its commits |
| CHECK_RED | the frozen item check passes at the exact submitted commit | reject the failing behavior; the builder fixes and resubmits |
| CHECK_UNVERIFIED | the frozen item check passes at the exact submitted commit | restore the frozen install or check environment and retry |
| GATE_RED | the gate, which submit runs itself every time, is green at HEAD | fix what the digest names, commit, submit again |
diff --git a/src/board.js b/src/board.js
index 6a7738d8..2b2a6b0b 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1037,6 +1037,7 @@ export function submit(board, id, { agentId, commit, tree, files = [], policyCom
hasCommit: null,
withinLane: null,
trunkMergeClean: null,
+ noUnverifiedStack: null,
gateConfigured: null,
gateGreen: null,
treeStillDuringGate: null,
@@ -1287,6 +1288,7 @@ export function verify(board, id, { agentId, decision, reason, note = '', head,
: 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),
trunkMergeClean: null,
+ noUnverifiedStack: null,
itemCheckGreen: null,
proofNoted: () =>
note.trim()
@@ -1417,6 +1419,27 @@ export function listItems(board, { lane, all = false } = {}) {
return all ? items : items.filter((item) => !['verified', 'withdrawn'].includes(item.item_status));
}
+/** Return all recorded submitted heads of items still awaiting verification [V1,V17].
+ * Historical heads remain unreviewed after a rejection or resubmission; current pointers also
+ * cover legacy snapshots that retained the item but not its original submit event.
+ * @param {any} board
+ * @returns {{ item_id: number, item_title: string, item_commit: string }[]}
+ */
+export function unverifiedSubmissions(board) {
+ const submissions = new Map();
+ for (const item of listItems(board, { all: true })) {
+ if (item.item_status === 'verified') continue;
+ const commits = [item.item_commit, ...events(board, { itemId: item.item_id })
+ .filter(event => event.event_kind === 'submit')
+ .map(event => JSON.parse(event.event_detail).commit)];
+ for (const commit of commits) {
+ if (!/^[0-9a-f]{40,64}$/iu.test(commit ?? '')) continue;
+ submissions.set(`${item.item_id}:${commit}`, { item_id: item.item_id, item_title: item.item_title, item_commit: commit });
+ }
+ }
+ return [...submissions.values()];
+}
+
/**
* One item as a reader should see it.
*
diff --git a/src/cli.js b/src/cli.js
index e9c51ddd..fce6ce83 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -72,6 +72,7 @@ import { autoLinkProject, relayOnAll, revokeRelayDevice, unlinkedRelayProjects }
import { readRelayMachine } from './relay-machine.js';
import { relayJoin, relayPair } from './relay-pairing-client.js';
import { executePersonRequests } from './relay-request-execution.js';
+import { engineReceipt } from './engine.js';
const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
export const VERSION = PACKAGE.version;
@@ -942,6 +943,42 @@ function filesSince(root, id, from, to) {
return result.status === 0 ? [...new Set(result.stdout.split('\n').filter(Boolean))].sort() : [];
}
+/** Refuse a candidate containing another item's unverified submitted commit [V1].
+ *
+ * Trunk-reachable commits are already landed, including when the candidate is trunk itself.
+ * Inspect all remaining reachable commits, including merged topic parents.
+ *
+ * @param {string} root
+ * @param {any} board
+ * @param {any} item
+ * @param {string} commit
+ * @param {{ ref: string, commit: string } | null} trunk
+ * @returns {void}
+ */
+function refuseUnverifiedStack(root, board, item, commit, trunk) {
+ const trunkRange = trunk?.commit
+ ? tryGit(root, ['rev-list', `${trunk.commit}..${commit}`])
+ : { status: 1, stdout: '' };
+ if (trunkRange.status !== 0) {
+ throw new Refused('NO_POLICY', 'the current trunk range cannot be read; restore Git history and retry the submit or verification');
+ }
+ const commits = new Set(trunkRange.stdout.split('\n').filter(Boolean));
+ const stacked = store.unverifiedSubmissions(board)
+ .find((other) => other.item_id !== item.item_id && commits.has(other.item_commit));
+ if (stacked) {
+ throw new Refused(
+ 'STACKED_ON_UNVERIFIED',
+ `#${item.item_id} includes unverified item #${stacked.item_id} at ${stacked.item_commit}; wait for #${stacked.item_id} to be accepted or rebuild without its commits before continuing`,
+ );
+ }
+}
+
+/** Return the durable outcome only when a recovered move exactly matches its original receipt. */
+function recordedRecovery(board, move) {
+ const receipt = engineReceipt(board, move.id);
+ return receipt?.move === JSON.stringify(move) ? receipt : null;
+}
+
/**
* How long ago an ISO time was, or how long until it, in the board's clock: 45m, 3h, 2d.
*
@@ -1682,8 +1719,16 @@ async function submitHere(ctx, id) {
const { root } = ctx.info;
const recovered = relayRecovered(root);
if (recovered?.operation === 'submit' && recovered.args[0] === id) {
- const me = withBoard(ctx, (board) => whoAmI(ctx, board));
- if (recovered.args[1]?.agentId === me.id) {
+ const preflight = withBoard(ctx, (board) => {
+ const me = whoAmI(ctx, board);
+ if (recovered.args[1]?.agentId !== me.id) return null;
+ if (recordedRecovery(board, recovered)) return { me, recorded: true };
+ const item = store.getItem(board, id);
+ const trunk = requireTrunkMerge(root, recovered.args[1].commit);
+ refuseUnverifiedStack(root, board, item, recovered.args[1].commit, trunk);
+ return { me, recorded: false };
+ });
+ if (preflight) {
await withBoard(ctx, async (board) => await ordered(ctx, board, 'submit', recovered.args));
return reportSubmission(ctx, id, recovered.args[1].commit,
{ green: true, report: 'recovered the original submission; its gate ran before the original send' });
@@ -1731,7 +1776,8 @@ async function submitHere(ctx, id) {
if (stray.length) throw new Refused('UNTRACKED', `commit or ignore ${stray.length} untracked file(s), e.g. ${stray[0]}`);
const commit = headCommit(root);
if (!commit) throw new Refused('NO_COMMIT', 'nothing committed yet');
- requireTrunkMerge(root, commit);
+ const trunk = requireTrunkMerge(root, commit);
+ withBoard(ctx, (board) => refuseUnverifiedStack(root, board, held, commit, trunk));
// Every submit proves its frozen check and reachable tests anew on this exact commit (V4,V16).
// A full-gate stamp never substitutes for either proof; only an actual full fallback may stamp.
const gate = await runSubmitGate(root, ctx.config, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), onWait: gateWaitReporter(ctx.io) });
@@ -1742,8 +1788,11 @@ 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`,
);
}
- requireTrunkMerge(root, commit); // The trunk may have moved while the gate ran.
- await withBoard(ctx, async (board) => await ordered(ctx, board, 'submit', [id, { agentId: me.id, commit, tree: headTree(root) ?? '', files: filesSince(root, id, claimHead, commit), policyCommit: acceptedMain.commit }]));
+ const currentTrunk = requireTrunkMerge(root, commit); // The trunk may have moved while the gate ran.
+ await withBoard(ctx, async (board) => {
+ refuseUnverifiedStack(root, board, store.getItem(board, id), commit, currentTrunk);
+ return await ordered(ctx, board, 'submit', [id, { agentId: me.id, commit, tree: headTree(root) ?? '', files: filesSince(root, id, claimHead, commit), policyCommit: acceptedMain.commit }]);
+ });
return reportSubmission(ctx, id, commit, { green: gate.isGreen, report: submitGateReport(gate), files: gate.files, full: gate.full, reason: gate.reason, check: gate.check });
}
@@ -1780,6 +1829,13 @@ async function verifyHere(ctx, id, { second, values }) {
if (recovered?.operation === 'verify' && recovered.args[0] === id && previous?.agentId === me.id &&
previous.decision === decision && previous.reason === values.reason &&
previous.note === (textArg(ctx.io, values, 'note') ?? '')) {
+ if (decision === 'ACCEPT' && !recordedRecovery(board, recovered)) {
+ const item = store.getItem(board, id);
+ const commit = resolveCommit(root, item.item_commit);
+ if (!commit) throw new Refused('NOT_AT_COMMIT', `check out the submitted commit first: ${cdTo(root)} git switch --detach ${item.item_commit.slice(0, 12)}`);
+ const trunk = requireTrunkMerge(root, commit);
+ refuseUnverifiedStack(root, board, item, commit, trunk);
+ }
return await ordered(ctx, board, 'verify', recovered.args);
}
const item = store.getItem(board, id);
@@ -1802,7 +1858,8 @@ async function verifyHere(ctx, id, { second, values }) {
}
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');
- requireTrunkMerge(root, commit);
+ const trunk = requireTrunkMerge(root, commit);
+ refuseUnverifiedStack(root, board, item, commit, trunk);
check = await withGateSlot(root, () => checkAtCommit(root, item), { itemCheck: true, onWait: gateWaitReporter(ctx.io) });
const evidence = check.checked
? `\nlast output lines (up to 40):\n${(check.outputTail ?? '(no output)').split('\n').map((line) => ` ${line}`).join('\n')}\nfull output file: ${check.outputPath ?? `(unavailable${check.outputError ? `: ${check.outputError}` : ''})`}`
@@ -1811,7 +1868,8 @@ async function verifyHere(ctx, id, { second, values }) {
if (check.state === 'red') throw new Refused('CHECK_RED', `the frozen item check is red at the submitted commit (${check.stage}); check.install may be needed for dependencies; reject with the failing behavior or ask the builder to fix and resubmit; output digest:\n${check.report.replace(/^/gm, ' ')}${evidence}`);
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) });
- requireTrunkMerge(root, commit); // Re-read after the frozen check, before accepting.
+ const currentTrunk = requireTrunkMerge(root, commit); // Re-read after the frozen check, before accepting.
+ refuseUnverifiedStack(root, board, item, commit, currentTrunk);
}
return await ordered(ctx, board, 'verify', [id, {
agentId: me.id,
diff --git a/src/machine.js b/src/machine.js
index af8f5040..93fb6936 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -116,6 +116,7 @@ export const GUARDS = [
{ 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' }, { code: 'GIT_GRAFTS', next: 'ask the coordinator to remove the Git graft file before retrying' }], rule: 'the full claimed diff respects committed coordinator ownership', next: 'restore foreign paths or shout their owner', source: 'cli' },
{ id: 'trunkMergeClean', refuse: 'MERGE_CONFLICT', alsoRefuses: [{ code: 'MERGE_CHECK_FAILED', next: 'use Git 2.38 or newer, restore its objects and retry' }, { code: 'NO_POLICY', next: 'restore the primary repository metadata' }, { code: 'NO_TRUNK', next: 'check out the trunk branch in the main checkout once and run pullboard inbox' }], rule: 'the candidate merges cleanly into the current primary branch without changing an index or worktree', next: 'merge the trunk into your branch, resolve conflicts, commit and resubmit', source: 'cli' },
+ { id: 'noUnverifiedStack', refuse: 'STACKED_ON_UNVERIFIED', rule: "the candidate range contains no other item's unverified submitted commit", next: 'wait for that item to be accepted, or rebuild without its commits', source: 'cli' },
{ id: 'itemCheckGreen', refuse: 'CHECK_RED', alsoRefuses: [{ code: 'CHECK_UNVERIFIED', next: 'restore the frozen install or check environment and retry' }], 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', alsoRefuses: [{ code: 'PIPEFAIL_UNAVAILABLE', next: 'rewrite the gate without a pipe' }], rule: 'the gate, which submit runs itself every time, is green at HEAD', next: 'fix what the digest names, commit, submit again', source: 'cli' },
@@ -149,7 +150,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', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],
+ guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'noUnverifiedStack', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],
sets: ['item_built_by', 'item_commit'], command: 'pullboard submit <id>',
},
{
@@ -159,7 +160,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', 'trunkMergeClean', 'itemCheckGreen', 'proofNoted'],
+ guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonIsMet', 'trunkMergeClean', 'noUnverifiedStack', 'itemCheckGreen', 'proofNoted'],
sets: ['item_verified_by'], command: 'pullboard verify <id> accept --note "..."',
},
{
diff --git a/src/trusted-policy.js b/src/trusted-policy.js
index 404ffac3..28a52aca 100644
--- a/src/trusted-policy.js
+++ b/src/trusted-policy.js
@@ -42,7 +42,16 @@ export function trunkRef(root, branch) {
return branch;
}
-/** Refuse a candidate that conflicts with the current primary branch, without touching an index or worktree [B34,V6]. */
+/** Resolve the trunk snapshot and refuse a conflict without touching an index or worktree [B34,V6].
+ *
+ * Returning the exact ref and tip lets later candidate checks use the same snapshot this merge
+ * check validated.
+ *
+ * @param {string} root
+ * @param {string} commit
+ * @param {string} [retainedRef]
+ * @returns {{ ref: string, commit: string }}
+ */
export function requireTrunkMerge(root, commit, retainedRef = trunkRef(root)) {
const checkout = mainCheckout(root);
const branchRef = checkout?.branch ?? retainedRef;
@@ -52,7 +61,7 @@ export function requireTrunkMerge(root, commit, retainedRef = trunkRef(root)) {
const result = spawnSync('git', ['--no-replace-objects', '-c', 'core.quotepath=false', 'merge-tree', '--write-tree', '--name-only', '-z', tip.stdout.trim(), commit], {
cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,
});
- if (result.status === 0) return;
+ if (result.status === 0) return { ref: branchRef, commit: tip.stdout.trim() };
if (result.status !== 1) throw new Refused('MERGE_CHECK_FAILED', 'Git could not check the candidate against the trunk; use Git 2.38 or newer, restore its objects and retry');
const records = result.stdout.split('\0').slice(1);
const end = records.indexOf('');
diff --git a/test/machine.test.js b/test/machine.test.js
index 64a956a3..a4afcfae 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -783,9 +783,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', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate'],
+ submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'noUnverifiedStack'],
reserve: ['coordinatorSaysAs', 'joined'],
- accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'trunkMergeClean', 'itemCheckGreen'],
+ accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'trunkMergeClean', 'itemCheckGreen', 'noUnverifiedStack'],
reject: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit'],
};
diff --git a/test/relay-client.test.js b/test/relay-client.test.js
index f612c361..faf6e431 100644
--- a/test/relay-client.test.js
+++ b/test/relay-client.test.js
@@ -19,7 +19,7 @@ import { exportBoard, importBoard } from '../src/exchange.js';
import { checkpointSequence } from '../src/engine.js';
import { serveApi } from '../src/api.js';
import { main } from '../src/cli.js';
-import { appliedSequence, prepareEngineMove } from '../src/engine.js';
+import { appliedSequence, engineReceipt, prepareEngineMove } from '../src/engine.js';
import { storeBoardKey } from '../src/relay-key.js';
import { ENGINE_VERSION } from '../src/machine.js';
import { presentationShout } from '../src/relay-presentation.js';
@@ -377,7 +377,7 @@ test('[H1,H3,H7,H15,H16] relay on snapshots and orders ciphertext, refuses offli
'person deletion removes the relay journal and SQLite sidecars');
});
-test('[H3,H16] three cloned linked replicas order competing claims and recover lost replies once', { timeout: 240_000 }, async (t) => {
+test('[H3,H16,V1,V17] three cloned linked replicas order competing claims and recover lost replies once', { timeout: 240_000 }, async (t) => {
const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-clone-race-')));
const seed = join(scratch, 'seed');
const clones = [join(scratch, 'clone-a'), join(scratch, 'clone-b'), join(scratch, 'clone-c')];
@@ -751,6 +751,105 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover l
assert.equal(JSON.parse(readFileSync(join(commonDir(clones[2], envs[2]), 'pullboard', 'relay.json'), 'utf8')).recovered,
undefined, 'automatic success consumes its recovered outcome');
+ await Promise.all(worktrees.map((root, index) => cli(root, envs[index], 'status')));
+
+ // A lost submit reply is already an outcome, even if another item becomes stacked while this
+ // replica is behind. A third, receipt-missing recovered descriptor still takes the fresh guard.
+ const stackBrief = join(scratch, 'recovered-stack-brief.md');
+ writeFileSync(stackBrief, 'Files: web/\nTest: only an exact durable receipt bypasses the fresh stack guard.\n');
+ const stackedA = (await cli(clones[0], envs[0], 'add', 'web', 'Relay recovered stack A', '--route', 'light', '--brief-file', stackBrief, '--specs', 'G1', '--criterion', 'exact durable receipt preserves recovery and missing receipts enforce stacking', '--check', 'true')).item.item_id;
+ const stackedB = (await cli(clones[0], envs[0], 'add', 'web', 'Relay recovered stack B', '--route', 'light', '--brief-file', stackBrief, '--specs', 'G1', '--criterion', 'exact durable receipt preserves recovery and missing receipts enforce stacking', '--check', 'true')).item.item_id;
+ const freshB = (await cli(clones[0], envs[0], 'add', 'web', 'Receipt-missing recovered stack', '--route', 'light', '--brief-file', stackBrief, '--specs', 'G1', '--criterion', 'exact durable receipt preserves recovery and missing receipts enforce stacking', '--check', 'true')).item.item_id;
+ await cli(worktrees[0], envs[0], 'claim', String(stackedB));
+ await cli(worktrees[1], envs[1], 'claim', String(stackedA));
+ await cli(worktrees[2], envs[2], 'claim', String(freshB));
+
+ writeFileSync(join(worktrees[1], 'web', 'recovery-a.txt'), 'the first submitted commit\n');
+ gitAt(worktrees[1], envs[1], 'add', 'web/recovery-a.txt');
+ gitAt(worktrees[1], envs[1], 'commit', '-q', '-m', 'test: create first recovery commit [G1]');
+ const firstRecoveryCommit = gitAt(worktrees[1], envs[1], 'rev-parse', 'HEAD');
+ for (const candidate of [worktrees[0], worktrees[2]]) {
+ const env = candidate === worktrees[0] ? envs[0] : envs[2];
+ gitAt(candidate, env, 'fetch', '-q', worktrees[1], firstRecoveryCommit);
+ gitAt(candidate, env, 'merge', '--no-ff', '-m', 'test: merge first recovery candidate [G1]', firstRecoveryCommit);
+ }
+ for (const [candidate, env, file, body, title] of [
+ [worktrees[0], envs[0], 'web/recovery-b.txt', 'the lost-ack candidate\n', 'recovered B'],
+ [worktrees[2], envs[2], 'web/recovery-fresh.txt', 'the receipt-missing candidate\n', 'fresh B'],
+ ]) {
+ writeFileSync(join(candidate, file), body);
+ gitAt(candidate, env, 'add', file);
+ gitAt(candidate, env, 'commit', '-q', '-m', `test: create ${title} candidate [G1]`);
+ }
+ const recoveredStackCommit = gitAt(worktrees[0], envs[0], 'rev-parse', 'HEAD');
+ const freshStackCommit = gitAt(worktrees[2], envs[2], 'rev-parse', 'HEAD');
+
+ const beforeRecoveredStack = relay.uploads.length;
+ relay.dropNextReply({ offline: true });
+ const lostStackSubmit = await cliResult(worktrees[0], envs[0], 'submit', String(stackedB));
+ assert.equal(lostStackSubmit.status, 1);
+ assert.equal(lostStackSubmit.document.error.code, 'RELAY_UNAVAILABLE');
+ relay.failReads(false);
+ const laterA = await cliResult(worktrees[1], envs[1], 'submit', String(stackedA));
+ assert.equal(laterA.status, 0, laterA.stderr);
+ assert.equal(laterA.document.commit, firstRecoveryCommit);
+ await cli(clones[0], envs[0], 'status');
+
+ const recoveredLink = join(commonDir(clones[0], envs[0]), 'pullboard', 'relay.json');
+ const pendingOutcome = JSON.parse(readFileSync(recoveredLink, 'utf8')).recovered;
+ assert.equal(pendingOutcome.move.operation, 'submit');
+ assert.equal(pendingOutcome.move.args[0], stackedB);
+ assert.ok(pendingOutcome.move.args[1].commit === recoveredStackCommit);
+ const recoveredReceipt = receipts(replicaFiles[0]).find((receipt) => JSON.parse(receipt.move).id === pendingOutcome.move.id);
+ assert.deepEqual(JSON.parse(recoveredReceipt.move), pendingOutcome.move, 'the pending reply has the exact durable engine receipt');
+ const beforeOutcomeRetry = relay.uploads.length;
+ assert.equal(beforeOutcomeRetry, beforeRecoveredStack + 2, 'the relay applied B and then A once each');
+ const originalOutcome = await cli(worktrees[0], envs[0], 'submit', String(stackedB));
+ assert.equal(originalOutcome.commit, recoveredStackCommit);
+ assert.match(originalOutcome.gate.report, /recovered the original submission/u);
+ assert.equal(relay.uploads.length, beforeOutcomeRetry, 'reporting the durable outcome creates no new relay move');
+
+ await cli(clones[2], envs[2], 'status');
+ const freshLinkFile = join(commonDir(clones[2], envs[2]), 'pullboard', 'relay.json');
+ const freshLink = JSON.parse(readFileSync(freshLinkFile, 'utf8'));
+ const freshBoard = store.openBoard(replicaFiles[2]);
+ let fabricatedReceiptlessMove;
+ try {
+ const freshItem = store.getItem(freshBoard, freshB);
+ const args = [freshB, {
+ agentId: freshItem.item_owner,
+ commit: freshStackCommit,
+ tree: gitAt(worktrees[2], envs[2], 'rev-parse', 'HEAD^{tree}'),
+ files: ['web/recovery-a.txt', 'web/recovery-fresh.txt'],
+ policyCommit: gitAt(clones[2], envs[2], 'rev-parse', 'main'),
+ }];
+ fabricatedReceiptlessMove = prepareEngineMove(freshBoard, 'submit', args);
+ assert.equal(appliedSequence(freshBoard) > 0, true);
+ assert.equal(engineReceipt(freshBoard, fabricatedReceiptlessMove.id), null,
+ 'the recovery descriptor has no durable engine receipt');
+ } finally { store.closeBoard(freshBoard); }
+ const freshSequence = freshLink.sequence + 1;
+ const freshSealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(fabricatedReceiptlessMove)), {
+ boardId, kind: 'move', sequence: freshSequence,
+ })).toString('base64url');
+ freshLink.recovered = {
+ move: fabricatedReceiptlessMove,
+ intent: JSON.stringify({ operation: 'submit', args: fabricatedReceiptlessMove.args }),
+ sequence: freshSequence,
+ sealed: freshSealed,
+ };
+ writeFileSync(freshLinkFile, JSON.stringify(freshLink) + '\n', { mode: 0o600 });
+ const beforeFreshRefusal = relay.uploads.length;
+ const freshRefusal = await cliResult(worktrees[2], envs[2], 'submit', String(freshB));
+ assert.equal(freshRefusal.status, 1);
+ assert.equal(freshRefusal.document.error.code, 'STACKED_ON_UNVERIFIED');
+ assert.match(freshRefusal.document.error.message, new RegExp(`#${stackedA}\\b`, 'u'));
+ assert.ok(freshRefusal.document.error.message.includes(firstRecoveryCommit));
+ assert.equal(relay.uploads.length, beforeFreshRefusal, 'a receipt-missing recovered descriptor is refused before relay upload');
+ const freshAfter = store.openBoard(replicaFiles[2]);
+ try { assert.equal(store.getItem(freshAfter, freshB).item_status, 'claimed'); }
+ finally { store.closeBoard(freshAfter); }
+
await Promise.all(worktrees.map((root, index) => cli(root, envs[index], 'status')));
const updated = store.openBoard(replicaFiles[0]);
let future;
diff --git a/test/stacked-history.test.js b/test/stacked-history.test.js
new file mode 100644
index 00000000..328bc3b6
--- /dev/null
+++ b/test/stacked-history.test.js
@@ -0,0 +1,103 @@
+/** Historical submitted heads cannot bypass review after a sibling resubmission [V17,V1]. */
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { after, test } from 'node:test';
+import { createE2eHelpers } from './e2e-helpers.js';
+
+const e2e = createE2eHelpers();
+after(e2e.cleanup);
+
+/** Add a real board item through the coordinator CLI. */
+function add(box, title) {
+ const result = box.run(box.repo, 'add', 'web', title, '--specs', 'G1', '--criterion', title, '--json');
+ assert.equal(result.code, 0, result.out + result.err);
+ return Number(JSON.parse(result.out).item.item_id);
+}
+
+/** Create and commit one distinct path in the supplied real worktree. */
+function commitFile(box, cwd, path, contents) {
+ mkdirSync(join(cwd, path, '..'), { recursive: true });
+ writeFileSync(join(cwd, path), contents);
+ box.git(cwd, 'add', path);
+ box.git(cwd, 'commit', '-q', '-m', `feat(web): ${contents.trim().toLowerCase()} [G1]`);
+ return box.git(cwd, 'rev-parse', 'HEAD');
+}
+
+/** Require the real submit command to identify the historical rejected submission. */
+function assertBlockedByHistoricalHead(result, itemId, oldHead) {
+ assert.equal(result.code, 1, result.out + result.err);
+ const refusal = JSON.parse(result.out).error;
+ assert.equal(refusal.code, 'STACKED_ON_UNVERIFIED');
+ assert.match(refusal.message, new RegExp(`#${itemId}\\b`, 'u'));
+ assert.ok(refusal.message.includes(oldHead), refusal.message);
+ assert.match(refusal.message, /wait .*accepted/iu);
+ assert.match(refusal.message, /rebuild without/iu);
+}
+
+/**
+ * Make A's old submission, B's candidate based on that old head, then A's sibling resubmission.
+ * B and A-retry use separate real worktrees so A's newer submission cannot enter B's history.
+ */
+function submittedSiblingHistory() {
+ const box = e2e.project('true');
+ const itemA = add(box, 'A old submitted head');
+ assert.equal(box.run(box.web, 'claim', String(itemA)).code, 0);
+ const oldHead = commitFile(box, box.web, 'web/a-old.txt', 'A old submitted head');
+ assert.equal(box.run(box.web, 'submit', String(itemA)).code, 0);
+
+ const itemB = add(box, 'B based on A old head');
+ const bWorktree = join(box.dir, 'web-b-from-old-a');
+ box.git(box.repo, 'worktree', 'add', '-q', '-b', 'web/b-candidate', bWorktree, oldHead);
+ assert.match(box.run(bWorktree, 'join', 'web').out, /joined as web-/u);
+ assert.equal(box.run(bWorktree, 'claim', String(itemB)).code, 0);
+ const bHead = commitFile(box, bWorktree, 'web/b-candidate.txt', 'B candidate based on old A');
+
+ const oldReview = join(box.dir, 'review-old-a');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', oldReview, oldHead);
+ assert.match(box.run(oldReview, 'join', 'api').out, /joined as api-/u);
+ const rejected = box.run(oldReview, 'verify', String(itemA), 'reject', '--reason', 'TEST_FAILURE', '--note', 'revise A before acceptance', '--json');
+ assert.equal(rejected.code, 0, rejected.out + rejected.err);
+
+ const base = box.git(box.repo, 'rev-parse', `${oldHead}^`);
+ const retryWorktree = join(box.dir, 'web-a-sibling-retry');
+ box.git(box.repo, 'worktree', 'add', '-q', '-b', 'web/a-retry', retryWorktree, base);
+ assert.match(box.run(retryWorktree, 'join', 'web').out, /joined as web-/u);
+ assert.equal(box.run(retryWorktree, 'claim', String(itemA)).code, 0);
+ const latestAHead = commitFile(box, retryWorktree, 'web/a-new.txt', 'A newer sibling submission');
+ assert.notEqual(latestAHead, oldHead);
+ assert.equal(box.tryGit(box.repo, 'merge-base', '--is-ancestor', oldHead, latestAHead).status, 1,
+ 'A newer resubmission is a sibling, not a descendant of A old head');
+ assert.equal(box.tryGit(box.repo, 'merge-base', '--is-ancestor', latestAHead, bHead).status, 1,
+ 'B does not contain A newer head');
+ assert.equal(box.tryGit(box.repo, 'merge-base', '--is-ancestor', oldHead, 'main').status, 1,
+ 'the historical A submission is not reachable from the trunk exemption');
+ assert.equal(box.run(retryWorktree, 'submit', String(itemA)).code, 0);
+
+ return { box, itemA, itemB, oldHead, latestAHead, bHead, bWorktree };
+}
+
+test('[V17,V1] an old submitted head remains stacked on another item after a sibling resubmission', () => {
+ const { box, itemA, itemB, oldHead, latestAHead, bHead, bWorktree } = submittedSiblingHistory();
+ assert.equal(box.git(bWorktree, 'rev-parse', 'HEAD'), bHead);
+ assertBlockedByHistoricalHead(box.run(bWorktree, 'submit', String(itemB), '--json'), itemA, oldHead);
+ const a = JSON.parse(box.run(bWorktree, 'show', String(itemA), '--json').out);
+ assert.equal(a.item_status, 'submitted');
+ assert.equal(a.item_commit, latestAHead);
+ assert.equal(JSON.parse(box.run(bWorktree, 'show', String(itemB), '--json').out).item_status, 'claimed');
+});
+
+test('[V17,V1] accepting the latest sibling submission clears every historical stack blocker', () => {
+ const { box, itemA, itemB, oldHead, latestAHead, bHead, bWorktree } = submittedSiblingHistory();
+ const latestReview = join(box.dir, 'review-latest-a');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', latestReview, latestAHead);
+ assert.match(box.run(latestReview, 'join', 'api').out, /joined as api-/u);
+ const accepted = box.run(latestReview, 'verify', String(itemA), 'accept', '--note', 'accepted A latest sibling head', '--json');
+ assert.equal(accepted.code, 0, accepted.out + accepted.err);
+
+ assert.equal(box.git(bWorktree, 'rev-parse', 'HEAD'), bHead);
+ const submitted = box.run(bWorktree, 'submit', String(itemB), '--json');
+ assert.equal(submitted.code, 0, submitted.out + submitted.err);
+ assert.equal(JSON.parse(box.run(bWorktree, 'show', String(itemB), '--json').out).item_commit, bHead);
+ assert.notEqual(oldHead, latestAHead);
+});
diff --git a/test/stacked-submit.test.js b/test/stacked-submit.test.js
new file mode 100644
index 00000000..513d49ae
--- /dev/null
+++ b/test/stacked-submit.test.js
@@ -0,0 +1,157 @@
+/** A candidate cannot carry another item's unverified submission through submit or accept [V17]. */
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { after, test } from 'node:test';
+import * as store from '../src/board.js';
+import { createE2eHelpers } from './e2e-helpers.js';
+
+const e2e = createE2eHelpers();
+after(e2e.cleanup);
+
+/** Add a work item through the fixture's real CLI. */
+function add(box, lane, title) {
+ const result = box.run(box.repo, 'add', lane, title, '--specs', lane === 'web' ? 'G1' : 'G2', '--criterion', title);
+ assert.equal(result.code, 0, result.out + result.err);
+ return Number(result.out.match(/#(\d+)/u)?.[1]);
+}
+
+/** Commit one owned file in a fixture worktree and return its real Git commit. */
+function commitFile(box, worktree, name, contents) {
+ mkdirSync(join(worktree, name.includes('/') ? name.slice(0, name.lastIndexOf('/')) : '.'), { recursive: true });
+ writeFileSync(join(worktree, name), contents);
+ box.git(worktree, 'add', name);
+ box.git(worktree, 'commit', '-q', '-m', `feat(web): ${contents.trim()} [G1]`);
+ return box.git(worktree, 'rev-parse', 'HEAD');
+}
+
+/** Assert a real CLI refusal names the stacked item and its submitted commit. */
+function assertStackRefusal(result, itemId, commit) {
+ assert.equal(result.code, 1, result.out + result.err);
+ const error = JSON.parse(result.out).error;
+ assert.equal(error.code, 'STACKED_ON_UNVERIFIED');
+ assert.match(error.message, new RegExp(`#${itemId}\\b`, 'u'));
+ assert.ok(error.message.includes(commit), error.message);
+ assert.match(error.message, /wait .*accepted/iu);
+ assert.match(error.message, /rebuild without/iu);
+}
+
+test('[V17] submit refuses a candidate stacked on another item until it is accepted', () => {
+ const box = e2e.project('true');
+ const first = add(box, 'web', 'First submission');
+ assert.equal(box.run(box.web, 'claim', String(first)).code, 0);
+ const firstCommit = commitFile(box, box.web, 'web/first.txt', 'first submission');
+ assert.equal(box.run(box.web, 'submit', String(first)).code, 0);
+
+ const stacked = add(box, 'web', 'Stacked submission');
+ assert.equal(box.run(box.web, 'claim', String(stacked)).code, 0);
+ const stackedCommit = commitFile(box, box.web, 'web/stacked.txt', 'stacked submission');
+ assertStackRefusal(box.run(box.web, 'submit', String(stacked), '--json'), first, firstCommit);
+ assert.equal(JSON.parse(box.run(box.web, 'show', String(stacked), '--json').out).item_status, 'claimed');
+
+ const review = join(box.dir, 'review-first');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, firstCommit);
+ assert.match(box.run(review, 'join', 'api').out, /joined as api-1/u);
+ const accepted = box.run(review, 'verify', String(first), 'accept', '--note', 'checked the submitted change', '--json');
+ assert.equal(accepted.code, 0, accepted.out + accepted.err);
+ const resubmitted = box.run(box.web, 'submit', String(stacked), '--json');
+ assert.equal(resubmitted.code, 0, resubmitted.out + resubmitted.err);
+ assert.equal(JSON.parse(box.run(box.web, 'show', String(stacked), '--json').out).item_commit, stackedCommit);
+});
+
+test('[V17] accept refuses a historical candidate stacked on another item', () => {
+ const box = e2e.project('true');
+ const first = add(box, 'web', 'Unverified history');
+ assert.equal(box.run(box.web, 'claim', String(first)).code, 0);
+ const firstCommit = commitFile(box, box.web, 'web/first.txt', 'unverified history');
+ assert.equal(box.run(box.web, 'submit', String(first)).code, 0);
+
+ const stacked = add(box, 'web', 'Historical stacked submission');
+ assert.equal(box.run(box.web, 'claim', String(stacked)).code, 0);
+ const stackedCommit = commitFile(box, box.web, 'web/stacked.txt', 'historical stacked submission');
+ const board = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));
+ try {
+ store.submit(board, stacked, {
+ agentId: 'web-1',
+ commit: stackedCommit,
+ tree: box.git(box.web, 'rev-parse', 'HEAD^{tree}'),
+ policyCommit: JSON.parse(box.run(box.web, 'show', String(stacked), '--json').out).item_claim_head,
+ });
+ } finally {
+ store.closeBoard(board);
+ }
+
+ const review = join(box.dir, 'review-stacked');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, stackedCommit);
+ assert.match(box.run(review, 'join', 'api').out, /joined as api-1/u);
+ assertStackRefusal(box.run(review, 'verify', String(stacked), 'accept', '--note', 'reviewed historical submission', '--json'), first, firstCommit);
+ assert.equal(JSON.parse(box.run(review, 'show', String(stacked), '--json').out).item_status, 'submitted');
+});
+
+/** Create private history where a claimed item is placed at an unverified submission on trunk. */
+function trunkStack(box, { historical = false } = {}) {
+ const stacked = add(box, 'coordinator', 'Single-checkout stack');
+ assert.equal(box.run(box.repo, 'claim', String(stacked)).code, 0);
+ const first = add(box, 'web', 'Unverified trunk commit');
+ assert.equal(box.run(box.web, 'claim', String(first)).code, 0);
+ const firstCommit = commitFile(box, box.web, 'web/trunk.txt', 'unverified trunk commit');
+ assert.equal(box.run(box.web, 'submit', String(first)).code, 0);
+
+ box.git(box.repo, 'merge', '--ff-only', '-q', 'web/one');
+ const trunkHead = box.git(box.repo, 'rev-parse', 'HEAD');
+ assert.equal(trunkHead, firstCommit);
+ if (historical) {
+ const board = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));
+ try {
+ store.submit(board, stacked, {
+ agentId: 'coordinator',
+ commit: trunkHead,
+ tree: box.git(box.repo, 'rev-parse', 'HEAD^{tree}'),
+ policyCommit: JSON.parse(box.run(box.repo, 'show', String(stacked), '--json').out).item_claim_head,
+ });
+ } finally {
+ store.closeBoard(board);
+ }
+ }
+ return { first, firstCommit, stacked, trunkHead };
+}
+
+test('[V17,V1] single-checkout submit allows an unverified head already on trunk', () => {
+ const box = e2e.project('true');
+ const { first, firstCommit, stacked, trunkHead } = trunkStack(box);
+ assert.equal(box.git(box.repo, 'rev-parse', 'HEAD'), trunkHead);
+ const result = box.run(box.repo, 'submit', String(stacked), '--json');
+ assert.equal(result.code, 0, result.out + result.err);
+ assert.equal(JSON.parse(box.run(box.repo, 'show', String(stacked), '--json').out).item_commit, trunkHead);
+ assert.equal(JSON.parse(box.run(box.repo, 'show', String(first), '--json').out).item_status, 'submitted');
+});
+
+test('[V17,V1] detached accept allows an unverified head already on trunk', () => {
+ const box = e2e.project('true');
+ const { first, firstCommit, stacked, trunkHead } = trunkStack(box, { historical: true });
+ const review = join(box.dir, 'review-trunk');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, trunkHead);
+ assert.match(box.run(review, 'join', 'api').out, /joined as api-1/u);
+ const result = box.run(review, 'verify', String(stacked), 'accept', '--note', 'checked detached trunk history', '--json');
+ assert.equal(result.code, 0, result.out + result.err);
+ assert.equal(JSON.parse(box.run(review, 'show', String(stacked), '--json').out).item_status, 'verified');
+ assert.equal(JSON.parse(box.run(review, 'show', String(first), '--json').out).item_status, 'submitted');
+});
+
+test('[V17] a trunk-merged unverified commit is outside a newer candidate range', () => {
+ const box = e2e.project('true');
+ const first = add(box, 'web', 'Merged submission');
+ assert.equal(box.run(box.web, 'claim', String(first)).code, 0);
+ const firstCommit = commitFile(box, box.web, 'web/first.txt', 'merged submission');
+ assert.equal(box.run(box.web, 'submit', String(first)).code, 0);
+ box.git(box.repo, 'merge', '--ff-only', '-q', 'web/one');
+
+ const stacked = add(box, 'web', 'After trunk merge');
+ assert.equal(box.run(box.web, 'claim', String(stacked)).code, 0);
+ const stackedCommit = commitFile(box, box.web, 'web/stacked.txt', 'after trunk merge');
+ assert.notEqual(stackedCommit, firstCommit);
+ const submitted = box.run(box.web, 'submit', String(stacked), '--json');
+ assert.equal(submitted.code, 0, submitted.out + submitted.err);
+ assert.equal(JSON.parse(box.run(box.web, 'show', String(stacked), '--json').out).item_commit, stackedCommit);
+ assert.equal(JSON.parse(box.run(box.web, 'show', String(first), '--json').out).item_status, 'submitted');
+});