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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(core): refuse candidates that conflict with the trunk [B34,V6]
Corey Olson63bdfcb52210
diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex 991b2450..90725f67 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -46,9 +46,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) || 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), 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), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), 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 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) |+| 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), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), 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 or NO_POLICY or BAD_CONFIG) |@@ -98,6 +98,10 @@ Each move checks its guards in this order and refuses with the first one that do| 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 |+| MERGE_CONFLICT | the candidate merges cleanly into the current primary branch without changing an index or worktree | merge the trunk into your branch, resolve conflicts, commit and resubmit |+| 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 || 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 |diff --git a/src/board.js b/src/board.jsindex 97f7b2c2..aa998242 100644--- a/src/board.js+++ b/src/board.js@@ -432,6 +432,12 @@ export function agentAt(board, path) {return board.db.prepare('SELECT * FROM agent WHERE agent_path = ?').get(path);}+/** Remember the primary branch locally, so a detached review can still check its current trunk [B34,V6]. */+export function trunkRef(board, branch) {+ if (branch !== undefined) board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value').run('trunk_ref', branch);+ return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('trunk_ref')?.meta_value ?? null;+}+/*** Register a worktree as an agent (B3): the main checkout as the one coordinator, any other* worktree as the next agent in its lane (`web-1`, `web-2`, ...), on a route: the tier of model@@ -1000,6 +1006,7 @@ export function submit(board, id, { agentId, commit, tree, files = [], policyComnothingUntracked: null,hasCommit: null,withinLane: null,+ trunkMergeClean: null,gateConfigured: null,gateGreen: null,treeStillDuringGate: null,@@ -1177,6 +1184,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),+ trunkMergeClean: null,itemCheckGreen: null,proofNoted: () =>note.trim()diff --git a/src/cli.js b/src/cli.jsindex 53a3d1d7..23de8104 100644--- a/src/cli.js+++ b/src/cli.js@@ -14,7 +14,7 @@ import { loadDoctrine } from './doctrine.js';import { requirePersonChannel } from './person.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';import { digestOf, gateReport, runGate, runShell } from './gate.js';-import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';+import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, mainCheckout, repoInfo, resolveCommit, tryGit, untracked } from './git.js';import {FIX_NOTE,applyFixers,@@ -56,7 +56,7 @@ import { exportView, serveView } from './serve.js';import { serveApi } from './api.js';import { doctorProblems } from './doctor.js';import { staleFrozenItems, staleItemFinding } from './approved-rows.js';-import { mainPolicy, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots } from './trusted-policy.js';+import { mainPolicy, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge } from './trusted-policy.js';import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';import { loadMachineSettings, setGateSlots } from './settings.js';@@ -631,7 +631,13 @@ function withBoard(ctx, work) {store.closeBoard(board);};let result;- try { result = work(board); }+ try {+ if (ctx.info.isMain) {+ const primary = mainCheckout(ctx.info.root);+ if (primary?.branch) store.trunkRef(board, primary.branch);+ }+ result = work(board);+ }catch (error) { finish(); throw error; }if (result && typeof result.then === 'function') return result.finally(finish);finish();@@ -1437,6 +1443,7 @@ 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');+ withBoard(ctx, board => requireTrunkMerge(root, commit, store.trunkRef(board)));// Submit runs the gate itself, every time: a stamp from an earlier run is a file any agent can// write, so it never stands in for this run (V16). It starts on the commit submitted, and must end// on it too. What the gate's own code does in between is the submitted tree's, under review.@@ -1448,6 +1455,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 => requireTrunkMerge(root, commit, store.trunkRef(board))); // 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 pin = `refs/pullboard/items/${id}/${commit.slice(0, 12)}`;git(root, ['update-ref', pin, commit]);@@ -1493,9 +1501,11 @@ 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, store.trunkRef(board));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) });+ requireTrunkMerge(root, commit, store.trunkRef(board)); // Re-read after the frozen check, before accepting.}return await ordered(ctx, board, 'verify', [id, {agentId: me.id,@@ -2321,6 +2331,24 @@ async function runCommand(argv, io) {}}+/** Retain the primary branch on every command without creating a board for global help. */+function rememberTrunk(io) {+ let info;+ try { info = repoInfo(io.cwd); }+ catch (error) {+ if (error instanceof Refused && ['NOT_A_REPO', 'NO_REPO', 'CORE_BARE'].includes(error.code)) return;+ throw error;+ }+ if (!info.isMain) return;+ const file = join(info.commonDir, 'pullboard', 'board.sqlite');+ if (!existsSync(file)) return;+ const primary = mainCheckout(info.root);+ if (!primary?.branch) return;+ const board = store.openBoard(file, io.clock ?? store.systemClock);+ try { store.trunkRef(board, primary.branch); }+ finally { store.closeBoard(board); }+}+/** Run one command and emit its single versioned JSON result when requested (A1). */export async function main(argv, streams) {const io = commandOutput(argv, streams);@@ -2338,6 +2366,7 @@ export async function main(argv, streams) {if (!['NOT_A_REPO', 'NO_REPO', 'NO_CONFIG', 'CORE_BARE'].includes(error.code)) io.err(`pullboard: ${error.message}`);}};+ rememberTrunk(io);if (sync) await retry();const code = await runCommand(argv, io);if (sync && code === 0) await retry();diff --git a/src/machine.js b/src/machine.jsindex f3933b9b..07211cba 100644--- a/src/machine.js+++ b/src/machine.js@@ -115,6 +115,7 @@ export const GUARDS = [{ 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: '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: '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' },@@ -145,7 +146,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', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],+ guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],sets: ['item_built_by', 'item_commit'], command: 'pullboard submit <id>',},{@@ -155,7 +156,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', 'itemCheckGreen', 'proofNoted'],+ guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonIsMet', 'trunkMergeClean', 'itemCheckGreen', 'proofNoted'],sets: ['item_verified_by'], command: 'pullboard verify <id> accept --note "..."',},{diff --git a/src/trusted-policy.js b/src/trusted-policy.jsindex 6023dd0f..788d4fa9 100644--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@ -23,6 +23,25 @@ export function mainPolicy(root) {return policyAt(root, checkout.commit);}+/** Refuse a candidate that conflicts with the current primary branch, without touching an index or worktree [B34,V6]. */+export function requireTrunkMerge(root, commit, retainedRef = null) {+ const checkout = mainCheckout(root);+ const branchRef = checkout?.branch ?? retainedRef;+ if (!branchRef?.startsWith('refs/heads/')) throw new Refused('NO_TRUNK', 'no trunk branch was recorded; check out the trunk branch in the main checkout once and run pullboard inbox');+ const tip = spawnSync('git', ['--no-replace-objects', 'rev-parse', '--verify', '--quiet', branchRef + '^{commit}'], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8' });+ if (tip.status !== 0) throw new Refused('NO_TRUNK', 'the recorded trunk branch has no readable tip; check out the trunk branch in the main checkout once and run pullboard inbox');+ 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 !== 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('');+ const files = records.slice(0, end < 0 ? records.length : end).map(path => JSON.stringify(path));+ const branch = branchRef.replace(/^refs\/heads\//, '');+ throw new Refused('MERGE_CONFLICT', `the candidate conflicts with the current trunk ${branch} in ${files.join(', ') || 'unresolved files'}; merge the trunk into your branch, resolve these files, commit and resubmit`);+}+/** 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');diff --git a/test/machine.test.js b/test/machine.test.jsindex 01a0e795..caeb0ee9 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -781,9 +781,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', 'gateConfigured', 'gateGreen', 'treeStillDuringGate'],+ submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate'],reserve: ['coordinatorSaysAs', 'joined'],- accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'itemCheckGreen'],+ accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'trunkMergeClean', 'itemCheckGreen'],reject: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit'],};diff --git a/test/trunk.test.js b/test/trunk.test.jsindex 96fca8f8..0198103d 100644--- a/test/trunk.test.js+++ b/test/trunk.test.js@@ -5,7 +5,7 @@ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { after, test } from 'node:test';-import { mainPolicy } from '../src/trusted-policy.js';+import { mainPolicy, requireTrunkMerge } from '../src/trusted-policy.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const TEMP_DIRS = [];@@ -67,7 +67,7 @@ function project(branch) {const configPath = join(repo, 'pullboard.json');const config = JSON.parse(readFileSync(configPath, 'utf8'));config.gate = 'true';- config.lanes = { web: { owns: ['web/'], specs: ['G1'] } };+ config.lanes = { web: { owns: ['web/'], specs: ['G1'] }, review: { owns: [] } };writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');writeFileSync(join(repo, 'SPEC.md'), SPEC);mkdirSync(join(repo, 'web'));@@ -135,3 +135,115 @@ test('[B34,P2] add --check reports an unavailable baseline for a detached coordicommand: 'true', main: null, result: 'unavailable', reason: 'coordinator checkout is detached',});});++/** Claim and commit one real lane item while the primary branch remains separate. */+function mergeCandidate(branch = 'trunk') {+ const box = project(branch);+ const web = join(box.dir, 'merge-web');+ box.git(box.repo, 'worktree', 'add', '-q', web, '-b', 'web/merge-candidate');+ assert.equal(box.run(web, 'join', 'web', '--family', 'builder-fixture').code, 0);+ const added = box.run(box.repo, 'add', 'web', 'Merge candidate', '--specs', 'G1', '--criterion', 'merges without touching a checkout', '--json');+ assert.equal(added.code, 0, added.err);+ const id = JSON.parse(added.out).item.item_id;+ assert.equal(box.run(web, 'claim', String(id)).code, 0);+ writeFileSync(join(web, 'web/result.txt'), 'builder result\n');+ box.git(web, 'add', 'web/result.txt');+ box.git(web, 'commit', '-q', '-m', 'feat(web): build merge candidate [G1]');+ return { ...box, web, id };+}++/** Capture the bytes and state a speculative merge must leave alone. */+function checkoutState(box, cwd) {+ return {+ head: box.git(cwd, 'rev-parse', 'HEAD'),+ index: readFileSync(resolve(cwd, box.git(cwd, 'rev-parse', '--git-path', 'index'))).toString('base64'),+ status: box.git(cwd, 'status', '--porcelain'),+ staged: box.git(cwd, 'diff', '--cached', '--binary'),+ work: box.git(cwd, 'diff', '--binary'),+ result: readFileSync(join(cwd, 'web/result.txt'), 'utf8'),+ };+}++/** Move only the fixture's primary branch, optionally making an actual content conflict. */+function advanceMergeTrunk(box, conflict) {+ const file = conflict ? 'result.txt' : 'trunk.txt';+ writeFileSync(join(box.repo, 'web', file), 'trunk result\n');+ box.git(box.repo, 'add', 'web/' + file);+ box.git(box.repo, 'commit', '-q', '-m', 'feat(web): advance fixture trunk [G1]');+}++/** A different fixture agent reviews the submitted commit, never a shared-board item. */+function mergeReviewer(box) {+ const review = join(box.dir, 'merge-review');+ box.git(box.repo, 'worktree', 'add', '-q', review, '-b', 'review/merge-candidate', box.git(box.web, 'rev-parse', 'HEAD'));+ assert.equal(box.run(review, 'join', 'review', '--family', 'reviewer-fixture').code, 0);+ return review;+}++test('[B34,V6] clean divergent submit and accept preserve every checkout and index', () => {+ const box = mergeCandidate('master');+ advanceMergeTrunk(box, false);+ const before = [checkoutState(box, box.repo), checkoutState(box, box.web)];+ const submitted = box.run(box.web, 'submit', String(box.id));+ assert.equal(submitted.code, 0, submitted.err);+ assert.deepEqual([checkoutState(box, box.repo), checkoutState(box, box.web)], before);+ const review = mergeReviewer(box);+ const reviewBefore = checkoutState(box, review);+ const accepted = box.run(review, 'verify', String(box.id), 'accept', '--note', 'Tried divergent trunk changes; merge and checkout bytes are checked by this fixture.');+ assert.equal(accepted.code, 0, accepted.err);+ assert.deepEqual(checkoutState(box, review), reviewBefore);+ assert.deepEqual([checkoutState(box, box.repo), checkoutState(box, box.web)], before);+});++test('[B34,V6] conflicting submit names files and refuses without changing any checkout or index', () => {+ const box = mergeCandidate();+ advanceMergeTrunk(box, true);+ const before = [checkoutState(box, box.repo), checkoutState(box, box.web)];+ const refused = box.run(box.web, 'submit', String(box.id));+ assert.notEqual(refused.code, 0, refused.out + refused.err);+ assert.match(refused.err, /MERGE_CONFLICT/);+ assert.match(refused.err, /web\/result\.txt/);+ assert.match(refused.err, /merge the trunk into your branch.*resubmit/);+ assert.deepEqual([checkoutState(box, box.repo), checkoutState(box, box.web)], before);+ const shown = box.run(box.web, 'show', String(box.id), '--json');+ assert.equal(JSON.parse(shown.out).item_status, 'claimed', 'refusal leaves the claim available for a resolved new commit');+});++test('[B34,V6] accept rechecks the moved trunk and refuses with indexes and checkouts intact', () => {+ const box = mergeCandidate();+ const submitted = box.run(box.web, 'submit', String(box.id));+ assert.equal(submitted.code, 0, submitted.err);+ const review = mergeReviewer(box);+ advanceMergeTrunk(box, true);+ const before = [box.repo, box.web, review].map(cwd => checkoutState(box, cwd));+ const refused = box.run(review, 'verify', String(box.id), 'accept', '--note', 'Tried divergent trunk changes; merge and checkout bytes are checked by this fixture.');+ assert.notEqual(refused.code, 0, refused.out + refused.err);+ assert.match(refused.err, /MERGE_CONFLICT/);+ assert.match(refused.err, /web\/result\.txt/);+ assert.match(refused.err, /merge the trunk into your branch.*resubmit/);+ assert.deepEqual([box.repo, box.web, review].map(cwd => checkoutState(box, cwd)), before);+ const shown = box.run(box.web, 'show', String(box.id), '--json');+ assert.equal(JSON.parse(shown.out).item_status, 'submitted', 'conflict cannot produce an accept receipt');+});++test('[B34,V6] a detached coordinator accept checks the retained non-main trunk tip', () => {+ const box = mergeCandidate('master');+ assert.equal(box.run(box.web, 'submit', String(box.id)).code, 0);+ advanceMergeTrunk(box, true);+ box.git(box.repo, 'switch', '-q', '--detach', box.git(box.web, 'rev-parse', 'HEAD'));+ const before = checkoutState(box, box.repo);+ const refused = box.run(box.repo, 'verify', String(box.id), 'accept', '--as', 'coordinator', '--note', 'Fixture checks retained branch conflicts.');+ assert.match(refused.err, /MERGE_CONFLICT/);+ assert.match(refused.err, /master/);+ assert.match(refused.err, /web\/result\.txt/);+ assert.deepEqual(checkoutState(box, box.repo), before);+});++test('[B34,V6] an unrecorded detached trunk refuses with NO_TRUNK and its repair', () => {+ const box = project('trunk');+ const commit = box.git(box.repo, 'rev-parse', 'HEAD');+ box.git(box.repo, 'switch', '-q', '--detach', commit);+ const before = checkoutState(box, box.repo);+ assert.throws(() => requireTrunkMerge(box.repo, commit), error => error.code === 'NO_TRUNK' && /check out the trunk branch in the main checkout once/.test(error.message));+ assert.deepEqual(checkoutState(box, box.repo), before);+});