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): compute automatic conflict returns natively [V4,H16]
Corey Olson9c97f4cf4533
diff --git a/docs/formats.md b/docs/formats.mdindex 36b6ea39..a206b8ba 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -412,7 +412,7 @@ Each connection also has a temporary `moving(token INTEGER)` table and `status_tThe `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its append-only record format has the independent `EVENT_LOG_VERSION`. Each event has an increasing integer id, an ISO timestamp, the actor, the event kind, an optional item id, and a JSON object in `event_detail`. Board moves append their event inside the same immediate transaction as the move. Events are append-only; board triggers reject updates and deletes. The actor column is the acting agent id, except guard-repair events, which use `board`. Under engine 8 and later, each event by a registered agent also carries a `model` string snapshot in `event_detail`; legacy agents without a declaration use `unknown`. Declared models live under `agent_model:<agent id>` in `board_meta`, without changing the agent table or stable ids. Rejoining with another model appends a `model` event whose common snapshot holds the new declaration. This common snapshot is separate from the per-kind payload fields listed below. The following rows name the emitted kinds and the union of their operation-specific detail keys; CLI accept events additionally carry the frozen-check result described below:-The computed-grant engine adds `grantEngine` to new join, claim and renewal events as a version marker only. It stores no grant or scope: permission is computed from the seat lane, current claim and lease, or the current review reservation. Older event bytes remain unchanged. A new marker prevents an older engine from reinterpreting a narrowed claim; shout, release and review reservation keep their existing engine floors. Reopen still checks the marked seat and target version floor, while its own authority guards decide permission: current conflict returns are coordinator-only, and the exact accepting reviewer can withdraw its current verdict independently of a build claim. Older recorded submitted-conflict moves retain their joined-seat authority.+The computed-grant engine adds `grantEngine` to new join, claim and renewal events as a version marker only. It stores no grant or scope: permission is computed from the seat lane, current claim and lease, or the current review reservation. Older event bytes remain unchanged. A new marker prevents an older engine from reinterpreting a narrowed claim; shout, release and review reservation keep their existing engine floors. Reopen still checks the marked seat and target version floor, while its own authority guards decide permission: direct current conflict requests are coordinator-only; automatic review preflight records native-computed evidence bound to the board, actor, item, submitted head, trunk and conflicting files, validated at origin before sealing and replayed without Git. The exact accepting reviewer can withdraw its current verdict independently of a build claim. Older recorded submitted-conflict moves retain their joined-seat authority.<!-- events:start -->| Kind | Actor | Detail fields |diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex f2ac9487..0af4d74a 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -97,9 +97,9 @@ Each move checks its guards in this order and refuses with the first one that do| AGENT_REPLACED | the caller is the main checkout, or an unreplaced worktree seat that joined a lane; an agent session's claims, submits and verdicts can be checked against its local ledger | read the takeover and only shout on its exact hand-off item; continue work from the incoming agent worktree || SESSION_LEDGER | the caller is the main checkout, or an unreplaced worktree seat that joined a lane; an agent session's claims, submits and verdicts can be checked against its local ledger | make the agent-session ledger named in the message readable and writable by this user, then run the command again || NO_ITEM | the item exists | pullboard list --all |-| COORDINATOR_ONLY | the coordinator reopens, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | ask the coordinator or the reviewer who recorded the accept |-| VERDICT_WITHDRAW_FORBIDDEN | the coordinator reopens, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | ask the accepting reviewer or coordinator to withdraw the verdict |-| VERDICT_WITHDRAW_STATE | the coordinator reopens, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | refresh the item; only a current acceptance before landing can be withdrawn |+| COORDINATOR_ONLY | the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | ask the coordinator or the reviewer who recorded the accept |+| VERDICT_WITHDRAW_FORBIDDEN | the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | ask the accepting reviewer or coordinator to withdraw the verdict |+| VERDICT_WITHDRAW_STATE | the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | refresh the item; only a current acceptance before landing can be withdrawn || COORDINATOR_ONLY | the caller is the coordinator | run it from the main checkout || MILESTONES_CORRUPT | the recorded queue policy and roadmap are readable when selecting the next review, only next --verify selection; a review reserved by id does not consult the roadmap | restore board metadata from a known-good board export || LINE_SETTING_RANGE | the recorded queue policy and roadmap are readable when selecting the next review, only next --verify selection; a review reserved by id does not consult the roadmap | restore the recorded board line setting from its ordered event history, then retry next --verify |diff --git a/src/board.js b/src/board.jsindex b6b5a8b1..d2556529 100644--- a/src/board.js+++ b/src/board.js@@ -1,4 +1,5 @@-import { AGENT_GRANT_ENGINE } from './agent-grant-engine.js';+import * as computedConflictEvidence from './computed-conflict-receipt.js';+import { reopenAuthority } from './reopen-authority.js';import {focusOrder,focusReasons,@@ -189,7 +190,6 @@ import {IN_STATE,MOVES,STATES,- SUBMITTED_CONFLICT_ENGINE,UNKNOWN_MOVE,VERIFIER_STANDING_ENGINE,effectiveGuards,@@ -1454,9 +1454,11 @@ export function verify(board, id, { agentId, decision, reason, note = '', cause,* @param {{ agentId: string, note: string, cause?: string, withdrawVerdict?: boolean }} request* @returns {{ id: number, commit: string, supersedes?: number, landingFailure?: object }}*/-export function reopen(board, id, { agentId, note = '', conflict, cause, reopenFirstRefusalMinutes, quotedLandingFailure, withdrawVerdict }) {+export function reopen(board, id, { agentId, note = '', conflict, cause, reopenFirstRefusalMinutes, quotedLandingFailure, withdrawVerdict, computedConflict }) {return atomic(board, () => {let submittedCommit = null;+ const assertedConflict = conflict;+ conflict = computedConflictEvidence.conflictValue(computedConflict, conflict);const forMerge = conflict !== undefined && conflict !== null;let supersedes, landingFailure, withdrawnVerdict;const forWithdrawal = withdrawVerdict === true;@@ -1469,13 +1471,8 @@ export function reopen(board, id, { agentId, note = '', conflict, cause, reopenFchecks: {joined: null,[IN_STATE]: (found) => new Refused('NOT_SUBMITTED', `item #${id} is ${current(board, found).item_status}, not submitted`),- // Historic joined-seat conflict reports keep their authority; current conflicts belong to the coordinator.- reopenAuthority: (found) => {- if (forWithdrawal) { withdrawnVerdict = verdictWithdrawal.verdictWithdrawalTarget(board, found, agentId); return null; }- return (forMerge && found.item_status === 'submitted' && currentEngine >= SUBMITTED_CONFLICT_ENGINE- && currentEngine < AGENT_GRANT_ENGINE && listAgents(board).some((agent) => agent.agent_id === agentId)- ? null : onlyCoordinator(agentId, 'reopens submissions'));- },+ reopenAuthority: (found) => reopenAuthority(board, found, agentId,+ { forWithdrawal, forMerge, currentEngine, computedConflict, assertedConflict }, value => { withdrawnVerdict = value; }),noteGiven: () => (forMerge || note.trim() ? null : new Refused('NOTE_REQUIRED', 'say why the criterion needs correction: --note "why"')),causeWellFormed: () => causeProblem(cause),notMerged: (found) => found.item_status !== 'verified' || !found.item_merged_commit@@ -1521,7 +1518,7 @@ export function reopen(board, id, { agentId, note = '', conflict, cause, reopenF});const returnedAt = (forMerge || landingFailure || forWithdrawal) && currentEngine >= REOPEN_FIRST_REFUSAL_ENGINE && reopenFirstRefusalMinutes > 0 && item.item_built_by ? board.clock.now() : undefined;const reservation = (forMerge || landingFailure || forWithdrawal) && currentEngine >= REOPEN_FIRST_REFUSAL_ENGINE ? firstRefusalDetail(board, item, reopenFirstRefusalMinutes, returnedAt) : {};- const returned = forWithdrawal ? { supersedes, withdrawnVerdict } : forMerge ? { supersedes, ...conflictDetail(conflict) } : supersedes ? { supersedes, landingFailure } : {};+ const returned = forWithdrawal ? { supersedes, withdrawnVerdict } : forMerge ? { supersedes, ...conflictDetail(conflict), ...(computedConflict !== undefined ? { computedConflict } : {}) } : supersedes ? { supersedes, landingFailure } : {};const derivedCause = currentEngine >= RIGOR_AUTO_ENGINE? deriveRigorCause(board, item, { cause, conflict, landingFailure, agentId }) : cause != null ? { cause } : {};const returnedWithCause = currentEngine >= RIGOR_AUTO_ENGINE ? { ...returned, ...derivedCause } : { ...derivedCause, ...returned };diff --git a/src/cli.js b/src/cli.jsindex e2138b3b..a8eeef54 100644--- a/src/cli.js+++ b/src/cli.js@@ -1,3 +1,4 @@+import { computedReturnArgs } from './computed-conflict-return.js';import { AGENT_GRANT_ENGINE } from './agent-grant-engine.js';import { requireAgentGrant } from './agent-grant.js';import {@@ -572,6 +573,7 @@ export function relayOutboxSetting(root) {}export async function ordered(ctx, board, operation, args) {+ if (operation === 'reopen') args = computedReturnArgs(board, args);const initialBaseline = initialSpecApprovalBaseline(ctx, board, operation);// Only a reject or a reopen can open a builder's first-refusal window (#954), so an accept never reads the coordinator's policy.if (operation === 'reopen' || operation === 'verify' && args[1]?.decision === 'REJECT') args = firstRefusalArgs(operation, args, configFromSource(coordinatorFile(ctx.info.root, CONFIG_FILE).stdout));diff --git a/src/computed-conflict-receipt.js b/src/computed-conflict-receipt.jsnew file mode 100644index 00000000..00a88b25--- /dev/null+++ b/src/computed-conflict-receipt.js@@ -0,0 +1,58 @@+/** Board-bound computed conflict evidence is checked before sealing and replayed without Git [V4,H16]. */+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { dirname } from 'node:path';+import { join } from 'node:path';+import { Refused } from './refused.js';++const SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;+const ID = /^[a-f0-9-]{36}$/u;++/** Resolve the evidence store from the board file, never from a caller-provided path. */+export function computedConflictStore(board) {+ const file = board.db.prepare('PRAGMA database_list').all().find(row => row.name === 'main')?.file;+ return file ? join(dirname(file), 'computed-conflicts') : null;+}++/** Read the canonical immutable record, rejecting altered, unknown or malformed fields. */+export function computedConflictFields(value) {+ if (!value || value.version !== 1 || !ID.test(value.id ?? '') || !/^[a-f0-9]{32}$/u.test(value.board ?? '')+ || !Number.isSafeInteger(value.item) || value.item < 1 || typeof value.actor !== 'string' || !value.actor || value.actor.length > 128 || /[\r\n\0]/u.test(value.actor)+ || !Number.isSafeInteger(value.submission) || value.submission < 1+ || !SHA.test(value.head ?? '') || !SHA.test(value.trunk ?? '') || !Array.isArray(value.files)+ || !value.files.length || value.files.length > 4096 || value.files.some(file => typeof file !== 'string' || !file || file.length > 4096 || file.includes('\0'))+ || new Set(value.files).size !== value.files.length || typeof value.at !== 'string' || !Number.isFinite(Date.parse(value.at))) return null;+ const fields = { version: 1, id: value.id, board: value.board, item: value.item, actor: value.actor,+ head: value.head, trunk: value.trunk, files: [...value.files], at: value.at, submission: value.submission };+ const digest = createHash('sha256').update(JSON.stringify(fields)).digest('hex');+ return value.digest === digest && Object.keys(value).length === Object.keys(fields).length + 1 ? { ...fields, digest } : null;+}++/** Refuse an unbound origin record; another machine validates its sealed canonical record on replay. */+export function requireComputedConflictBound(board, receipt) {+ const fields = computedConflictFields(receipt), directory = computedConflictStore(board);+ let stored;+ try { stored = fields && directory && readFileSync(join(directory, `${fields.id}.json`), 'utf8'); } catch { /* Missing evidence is not authority. */ }+ if (!fields || stored !== JSON.stringify(fields) + '\n') throw new Refused('COORDINATOR_ONLY',+ 'automatic conflict return requires the native board computation; agents cannot supply conflict assertions');+ return fields;+}++/** Bind recorded evidence to this board's current submitted item and actual actor, on every replica. */+export function computedConflictProblem(board, item, actor, receipt) {+ const fields = computedConflictFields(receipt);+ const identity = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get()?.meta_value;+ const submission = board.db.prepare("SELECT event_id FROM event WHERE item_id=? AND event_kind='submit' ORDER BY event_id DESC LIMIT 1").get(item.item_id)?.event_id;+ if (!fields || fields.submission !== submission || fields.board !== identity || fields.item !== item.item_id || fields.actor !== actor+ || fields.head !== item.item_commit || item.item_status !== 'submitted') return new Refused('COORDINATOR_ONLY',+ 'automatic conflict evidence must name this board, actor and current submitted head');+ if (board.executionEngineVersion === undefined) requireComputedConflictBound(board, fields);+ return null;+}++/** Derive merge fields from canonical evidence; malformed evidence remains a merge request that authority refuses. */+export function conflictValue(receipt, asserted) {+ if (receipt === undefined) return asserted;+ const fields = computedConflictFields(receipt);+ return fields ? { files: fields.files, trunk: fields.trunk } : {};+}diff --git a/src/computed-conflict-return.js b/src/computed-conflict-return.jsnew file mode 100644index 00000000..d8c4c1a2--- /dev/null+++ b/src/computed-conflict-return.js@@ -0,0 +1,41 @@+/** Native computation of automatic submitted-head returns; callers supply no conflict assertion [V4,H16]. */+import { createHash } from 'node:crypto';+import { randomUUID } from 'node:crypto';+import { mkdirSync } from 'node:fs';+import { realpathSync } from 'node:fs';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { repoInfo } from './git.js';+import { trunkMerge } from './trunk-merge.js';+import { computedConflictStore } from './computed-conflict-receipt.js';+import { Refused } from './refused.js';++/** Compute and privately store evidence only for this exact native board and current submitted head. */+export function computeConflictReturn(board, id, actor) {+ const root = board.db.prepare("SELECT agent_path FROM agent WHERE agent_id='coordinator'").get()?.agent_path;+ const file = board.db.prepare('PRAGMA database_list').all().find(row => row.name === 'main')?.file;+ let native = false;+ try { native = Boolean(root && file && realpathSync(join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite')) === realpathSync(file)); } catch { /* Unreadable or imported paths fail closed. */ }+ if (!native) throw new Refused('COORDINATOR_ONLY', 'automatic conflict return requires this board\'s registered native repository');+ const item = board.db.prepare('SELECT item_id,item_status,item_commit FROM item WHERE item_id=?').get(id);+ if (!item || item.item_status !== 'submitted' || !item.item_commit) throw new Refused('NOT_SUBMITTED', `item #${id} is not submitted`);+ if (!board.db.prepare('SELECT agent_id FROM agent WHERE agent_id=?').get(actor)) throw new Refused('NOT_JOINED', 'join before selecting a review');+ const merge = trunkMerge(root, item.item_commit);+ if (!merge.files?.length) throw new Refused('NOT_CONFLICTING', 'the submitted head merges cleanly; no automatic return is needed');+ const fields = { version: 1, id: randomUUID(), board: board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='board_id'").get().meta_value,+ item: item.item_id, actor, head: item.item_commit, trunk: merge.commit, files: merge.files, at: board.clock.now().toISOString(),+ submission: board.db.prepare("SELECT event_id FROM event WHERE item_id=? AND event_kind='submit' ORDER BY event_id DESC LIMIT 1").get(item.item_id).event_id };+ const receipt = { ...fields, digest: createHash('sha256').update(JSON.stringify(fields)).digest('hex') };+ const directory = computedConflictStore(board);+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ writeFileSync(join(directory, `${receipt.id}.json`), JSON.stringify(receipt) + '\n', { flag: 'wx', mode: 0o600 });+ return receipt;+}++/** Convert a native automatic request to evidence, rejecting mixed caller assertions. */+export function computedReturnArgs(board, args) {+ if (args[1]?.automaticConflict !== true) return args;+ if (args[1].conflict !== undefined || args[1].computedConflict !== undefined) throw new Refused('COORDINATOR_ONLY', 'automatic conflict return accepts no caller conflict assertion');+ const { automaticConflict, ...options } = args[1];+ return [args[0], { ...options, computedConflict: computeConflictReturn(board, args[0], options.agentId) }];+}diff --git a/src/engine.js b/src/engine.jsindex 74906690..36547cbb 100644--- a/src/engine.js+++ b/src/engine.js@@ -1,3 +1,5 @@+import { computedReturnArgs } from './computed-conflict-return.js';+import { requireComputedConflictBound } from './computed-conflict-receipt.js';import { agentGrantMinimum } from './agent-grant.js';import { requireAgentGrant } from './agent-grant.js';import {@@ -90,6 +92,7 @@ export function startRelayEpoch(board, boardId) {/** Turn caller-only callbacks into deterministic values before sealing an executable operation. */export function prepareEngineMove(board, operation, args, { id = randomUUID(), actor } = {}) {if (!ENGINE_OPERATIONS.includes(operation) || !Array.isArray(args)) throw new Refused('RELAY_MOVE', 'use a supported board-engine operation with its argument array');+ if (operation === 'reopen') args = computedReturnArgs(board, args);const values = args.map((value) => value && typeof value === 'object' ? { ...value } : value);if (operation === 'reopen' && values[1] && typeof values[1] === 'object'&& manualLandingFailureQuoted(values[1].note)) values[1].quotedLandingFailure = true;@@ -101,6 +104,10 @@ export function prepareEngineMove(board, operation, args, { id = randomUUID(), aif (ENGINE_VERSION < minimumEngine) throw new Refused('ENGINE_VERSION', `${operation} requires engine version ${minimumEngine}; this pullboard uses engine ${ENGINE_VERSION}; upgrade before sending it`);// A gate run is sealed only as its gate's own receipt; a run made up by hand is refused before it reaches any replica.if (operation === 'recordGateRun') requireBound(board, values[0]?.receipt);+ if (operation === 'reopen' && values[1]?.computedConflict !== undefined) {+ if (values[1].conflict !== undefined) throw new Refused('COORDINATOR_ONLY', 'automatic conflict evidence accepts no caller conflict assertion');+ requireComputedConflictBound(board, values[1].computedConflict);+ }if (operation === 'verify' && values[1]?.sandbox !== undefined) requireOutsideReceipt(board, values[1].sandbox);if (operation === 'release') {const problem = store.reviewReleaseNoteProblem(board, values[0], values[1], values[2]);diff --git a/src/machine.js b/src/machine.jsindex 2b8f5160..cf12fdb7 100644--- a/src/machine.js+++ b/src/machine.js@@ -99,7 +99,7 @@ export const GUARDS = [{ id: IN_STATE, refuse: '', rule: "the move can start from the item's current state", next: 'pullboard show <id>', source: 'board' },{ id: 'joined', refuse: 'NOT_JOINED', alsoRefuses: [{ code: 'AGENT_REPLACED', next: 'read the takeover and only shout on its exact hand-off item; continue work from the incoming agent worktree' }, { code: 'SESSION_LEDGER', next: 'make the agent-session ledger named in the message readable and writable by this user, then run the command again' }], rule: 'the caller is the main checkout, or an unreplaced worktree seat that joined a lane; an agent session\'s claims, submits and verdicts can be checked against its local ledger', next: 'pullboard join <lane> --model "<model name>" (see: pullboard lanes)', source: 'cli' },{ id: 'itemExists', refuse: 'NO_ITEM', rule: 'the item exists', next: 'pullboard list --all', source: 'board' },- { id: 'reopenAuthority', refuse: 'COORDINATOR_ONLY', rule: 'the coordinator reopens, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority', next: 'ask the coordinator or the reviewer who recorded the accept', source: 'board', alsoRefuses: [{ code: 'VERDICT_WITHDRAW_FORBIDDEN', next: 'ask the accepting reviewer or coordinator to withdraw the verdict' }, { code: 'VERDICT_WITHDRAW_STATE', next: 'refresh the item; only a current acceptance before landing can be withdrawn' }] },+ { id: 'reopenAuthority', refuse: 'COORDINATOR_ONLY', rule: 'the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority', next: 'ask the coordinator or the reviewer who recorded the accept', source: 'board', alsoRefuses: [{ code: 'VERDICT_WITHDRAW_FORBIDDEN', next: 'ask the accepting reviewer or coordinator to withdraw the verdict' }, { code: 'VERDICT_WITHDRAW_STATE', next: 'refresh the item; only a current acceptance before landing can be withdrawn' }] },{ id: 'coordinatorOnly', refuse: 'COORDINATOR_ONLY', rule: 'the caller is the coordinator', next: 'run it from the main checkout', source: 'board' },{ id: 'roadmapReadable', refuse: 'MILESTONES_CORRUPT', alsoRefuses: [{ code: 'LINE_SETTING_RANGE', rule: 'the recorded board line-order setting has a valid registry value', next: 'restore the recorded board line setting from its ordered event history, then retry next --verify' }], rule: 'the recorded queue policy and roadmap are readable when selecting the next review', next: 'restore board metadata from a known-good board export', source: 'board', when: 'only next --verify selection; a review reserved by id does not consult the roadmap' },{ id: 'coordinatorSaysAs', refuse: 'MAIN_IS_COORDINATOR', rule: 'in the main checkout, the caller says it is the coordinator', next: 'verify from your own worktree; the coordinator adds --as coordinator', source: 'cli' },diff --git a/src/moves/reopen.js b/src/moves/reopen.jsindex 14d48ba8..177e4f1f 100644--- a/src/moves/reopen.js+++ b/src/moves/reopen.js@@ -1,3 +1,4 @@+import { AGENT_GRANT_ENGINE } from '../agent-grant-engine.js';import { VERDICT_WITHDRAW_ENGINE } from '../verdict-withdraw-engine.js';import { RIGOR_AUTO_ENGINE } from '../rigor-auto-engine.js';/** Routing metadata owned by reopen, discovered without a shared registry edit [C7,V4,H16]. */@@ -29,7 +30,8 @@ function existingEngine(args, board, at) {/** Keep verdict withdrawal as an independent maximum over every prior first-match floor [H16]. */function minimumEngine(args, board, at) {- return Math.max(args[1]?.withdrawVerdict === true ? VERDICT_WITHDRAW_ENGINE : 1, existingEngine(args, board, at));+ return Math.max(args[1]?.computedConflict !== undefined ? AGENT_GRANT_ENGINE : 1,+ args[1]?.withdrawVerdict === true ? VERDICT_WITHDRAW_ENGINE : 1, existingEngine(args, board, at));}/** Read precisely the actor argument used by this operation [H2,H16]. */diff --git a/src/next-review.js b/src/next-review.jsindex 2e6392fd..3d42dd41 100644--- a/src/next-review.js+++ b/src/next-review.js@@ -26,7 +26,7 @@ export async function returnUnmergeable(root, board, me, { ordered, trunkMerge }catch (error) { if (error instanceof Refused) return returned; throw error; }if (!merge.files?.length) continue;try {- await ordered('reopen', [item.item_id, { agentId: me.id, conflict: { files: merge.files, trunk: merge.commit } }]);+ await ordered('reopen', [item.item_id, { agentId: me.id, automaticConflict: true }]);returned.push({ id: item.item_id, files: merge.files });} catch (error) {// Only a race is forgiven: another move already took the head out of review. A head still waitingdiff --git a/src/reopen-authority.js b/src/reopen-authority.jsnew file mode 100644index 00000000..fb314e14--- /dev/null+++ b/src/reopen-authority.js@@ -0,0 +1,18 @@+/** Versioned coordinator, computed-conflict and exact-reviewer reopen authority [V2,H16]. */+import { AGENT_GRANT_ENGINE } from './agent-grant-engine.js';+import { SUBMITTED_CONFLICT_ENGINE } from './engine-metadata.js';+import { listAgents } from './board-query.js';+import { verdictWithdrawalTarget } from './verdict-withdrawal.js';+import { computedConflictProblem } from './computed-conflict-receipt.js';+import { Refused } from './refused.js';++/** Preserve historical authority and refusal order without granting a caller assertion new authority. */+export function reopenAuthority(board, found, actor, options, withdrawn) {+ const { forWithdrawal, forMerge, currentEngine, computedConflict, assertedConflict } = options;+ if (computedConflict !== undefined) return currentEngine >= AGENT_GRANT_ENGINE && assertedConflict === undefined+ ? computedConflictProblem(board, found, actor, computedConflict) : new Refused('COORDINATOR_ONLY', 'only the coordinator reopens submissions');+ if (forWithdrawal) { withdrawn(verdictWithdrawalTarget(board, found, actor)); return null; }+ if (forMerge && found.item_status === 'submitted' && currentEngine >= SUBMITTED_CONFLICT_ENGINE+ && currentEngine < AGENT_GRANT_ENGINE && listAgents(board).some(agent => agent.agent_id === actor)) return null;+ return actor === 'coordinator' ? null : new Refused('COORDINATOR_ONLY', 'only the coordinator reopens submissions');+}diff --git a/src/trunk-merge.js b/src/trunk-merge.jsnew file mode 100644index 00000000..60a4703f--- /dev/null+++ b/src/trunk-merge.js@@ -0,0 +1,30 @@+/** In-memory Git conflict computation without loading check execution or resource admission [V4,C7]. */+import { spawnSync } from 'node:child_process';+import { cleanGitEnvironment } from './git.js';+import { mainCheckout } from './git.js';+import { trunkRef } from './trusted-policy-read.js';+import { Refused } from './refused.js';++/** Merge a commit onto the trunk tip in memory: the ref, the tip, and the conflicting files or null [B34,V6].+ *+ * @param {string} root+ * @param {string} commit+ * @param {string} [retainedRef]+ * @returns {{ ref: string, commit: string, files: string[] | null }}+ */+export function trunkMerge(root, commit, retainedRef = trunkRef(root)) {+ 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 { ref: branchRef, commit: tip.stdout.trim(), files: null };+ 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('');+ return { ref: branchRef, commit: tip.stdout.trim(), files: records.slice(0, end < 0 ? records.length : end) };+}+diff --git a/src/trusted-policy.js b/src/trusted-policy.jsindex 8e615111..2e99de8a 100644--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@ -1,3 +1,5 @@+import { trunkMerge } from './trunk-merge.js';+export { trunkMerge } from './trunk-merge.js';import {mainPolicy,policyAt,@@ -65,29 +67,6 @@ export function requireTrunkMerge(root, commit, retainedRef = trunkRef(root)) {throw new Refused('MERGE_CONFLICT', `the candidate conflicts with the current trunk ${branch} in ${files.map(path => JSON.stringify(path)).join(', ') || 'unresolved files'}; merge the trunk into your branch, resolve these files, commit and resubmit`);}-/** Merge a commit onto the trunk tip in memory: the ref, the tip, and the conflicting files or null [B34,V6].- *- * @param {string} root- * @param {string} commit- * @param {string} [retainedRef]- * @returns {{ ref: string, commit: string, files: string[] | null }}- */-export function trunkMerge(root, commit, retainedRef = trunkRef(root)) {- 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 { ref: branchRef, commit: tip.stdout.trim(), files: null };- 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('');- return { ref: branchRef, commit: tip.stdout.trim(), files: records.slice(0, end < 0 ? records.length : end) };-}-/** Use new claims' frozen policy; legacy claims retain their committed claim-base settings. */export function itemPolicy(root, item) {let frozen;diff --git a/test/review-queue.test.js b/test/review-queue.test.jsindex f87b190a..b9ae4e43 100644--- a/test/review-queue.test.js+++ b/test/review-queue.test.js@@ -333,3 +333,66 @@ test('recorded pre-grant submitted-conflict moves retain joined-seat authority [assert.deepEqual(store.events(board), legacyStore.events(legacy), 'replay preserves historical event bytes');}});+++test('automatic conflict returns bind native evidence and replay without caller assertions [V4,H16]', t => {+ const copies = [];+ t.after(() => copies.forEach(board => store.closeBoard(board)));+ const { box, json, conflicted, reviewer, build } = staleHeadFixture(t);+ const source = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));+ copies.push(source);+ const actor = store.agentAt(source, reviewer).agent_id;+ const original = exportBoard(source);+ const move = prepareEngineMove(source, 'reopen', [conflicted, { agentId: actor, automaticConflict: true }]);+ const evidence = move.args[1].computedConflict;+ assert.equal(move.args[1].automaticConflict, undefined, 'a caller boolean does not enter the executable move');+ assert.equal(move.args[1].conflict, undefined, 'the agent asserts no conflict tuple');+ assert.equal(evidence.head, store.getItem(source, conflicted).item_commit);+ assert.equal(evidence.trunk, box.git(box.repo, 'rev-parse', 'HEAD'));+ assert.deepEqual(evidence.files, ['web/list.html']);+ assert.equal(evidence.actor, actor, 'the move retains the actual reviewer actor');+ const forged = { ...evidence, id: 'ffffffff-ffff-ffff-ffff-ffffffffffff' };+ const { digest: ignored, ...forgedFields } = forged;+ forged.digest = createHash('sha256').update(JSON.stringify(forgedFields)).digest('hex');+ for (const receipt of [forged, { ...evidence, files: ['web/false.html'] }]) {+ assert.throws(() => prepareEngineMove(source, 'reopen', [conflicted, { agentId: actor, computedConflict: receipt }]),+ error => error.code === 'COORDINATOR_ONLY', 'unbound or mutated evidence cannot be sealed');+ assert.throws(() => store.reopen(source, conflicted, { agentId: actor, computedConflict: receipt }),+ error => error.code === 'COORDINATOR_ONLY', 'the direct origin API also requires its own stored evidence');+ }+ assert.deepEqual(exportBoard(source), original, 'evidence preparation and refusals do not change the board');+ /** Each imported replica has no native evidence store or usable coordinator repository binding. */+ const replica = name => {+ const board = store.openBoard(join(box.dir, `${name}.sqlite`));+ copies.push(board); importBoard(board, original); return board;+ };+ for (const [name, options] of [+ ['flag', { agentId: actor, automaticConflict: true }],+ ['mutated', { agentId: actor, computedConflict: { ...evidence, files: ['web/false.html'] } }],+ ['actor', { agentId: store.agentAt(source, box.web).agent_id, computedConflict: evidence }],+ ]) {+ const board = replica(name);+ const result = applyEngineMove(board, { ...move, id: `${move.id}-${name}`, args: [conflicted, options] },+ { sequence: 1, at: new Date().toISOString() });+ assert.equal(result.error?.code, 'COORDINATOR_ONLY', 'a flag, altered evidence or different actor grants no replay authority');+ assert.equal(store.getItem(board, conflicted).item_status, 'submitted');+ }+ const left = replica('valid-left'), right = replica('valid-right');+ assert.throws(() => prepareEngineMove(left, 'reopen', [conflicted, { agentId: actor, automaticConflict: true }]),+ error => error.code === 'COORDINATOR_ONLY', 'an imported replica cannot fabricate native origin evidence');+ assert.throws(() => applyEngineMove(left, { ...move, engine: AGENT_GRANT_ENGINE - 1 }, { sequence: 1, at: new Date().toISOString() }),+ error => error.code === 'RELAY_MOVE', 'an older engine cannot interpret the new computed-return record');+ const receipt = { sequence: 1, at: new Date().toISOString() };+ const results = [left, right].map(board => applyEngineMove(board, move, receipt));+ assert.deepEqual(results[0], results[1]);+ assert.equal(results[0].error, undefined);+ assert.deepEqual(store.events(left), store.events(right));+ assert.equal(store.getItem(left, conflicted).item_status, 'open');+ const second = join(box.dir, 'clean-computed-return');+ box.git(box.repo, 'worktree', 'add', '-q', second, '-b', 'web/clean-return', 'main');+ json(box.run(second, 'join', 'web', '--json'));+ const clean = build('Keep a clean footer', 'web/footer.html', '<footer>clean</footer>\n', second);+ assert.throws(() => prepareEngineMove(source, 'reopen', [clean, { agentId: actor, automaticConflict: true }]),+ error => error.code === 'NOT_CONFLICTING', 'a clean submitted head cannot acquire computed conflict evidence');+ assert.equal(store.getItem(source, clean).item_status, 'submitted');+});