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
feat(core): stale verdicts follow changed trunk files [E8,H16,V8]
Corey Olson792170800d28
diff --git a/docs/api.md b/docs/api.mdindex 49c927ae..71a1a040 100644--- a/docs/api.md+++ b/docs/api.md@@ -16,6 +16,12 @@ When `add` or `edit` supplies a new nonempty check, it records the item before mAn item's HTTP detail, and each item in the full board state, include `check` and, when recorded, `checkBaseline` with the same observation fields. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when showing or reserving the item for review, and when filing it with `--wait`. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. Captured observations and completions travel through ordered board moves, so replicas store results without executing commands. A completed result awaiting relay delivery stays on the measuring device and is retried by the next normal CLI command.+An accepted item that has not landed can carry `item_verdict_state` in CLI `show`, `list`, and `resume` JSON. Its `code` is `STALE_VERDICT`; `file` and `commit` identify the first known main change to one of the submitted candidate's files, and `reviewedTrunk` and `main` identify the compared tips. HTTP board states, summaries, and item details expose the same observation as optional `verdictState`. Moving main invalidates both cached state and live change notifications even when the served worktree's HEAD stays fixed. Unrelated files leave acceptance current; reverting a relevant main change still requires re-review. Missing reviewed history also fails closed, with a `reason` and null file/commit instead of an invented change.++Freshness never rewrites the stored ACCEPT or its verdict row. New accept/reject event details carry `review: {commit, trunk, paths}`: the original submitted commit, the known reviewed trunk, and sorted unique submitted paths. Existing receipts replay with their recorded engine and remain unchanged. Older acceptances without captured review metadata use a conservative claim-base bound and may require a new review after upgrading. Recorded or physically landed work no longer needs this freshness check.++For a stale acceptance, merge current main into the submitted work and commit a clean review HEAD. Another agent runs `pullboard verify <id> accept --note "what was re-reviewed"`; its frozen check runs at that combined HEAD, and a new verdict appends to the history while retaining the original submitted commit. A main move during the check refuses `VERDICT_TRUNK_MOVED` and requires another review. `resume` keeps stale acceptances out of its merge list. `land` excludes stale items (and reports their file and commit); when none remain ready, it refuses `STALE_VERDICT`. Nothing in this observation changes the approved criterion or grants person authority.+`pullboard stats [--since <date>] --json` returns `{version: 1, stats: {...}}` from the append-only event log. `submissions` and `rejections` count moves, including repeated attempts; `rejectionShare` is rejections divided by submissions (zero when the window has no submissions). `merged` counts distinct items with a merge move; `mergedWithoutAccept` counts those whose merge lacks an earlier acceptance of the latest submitted commit. That audit uses earlier history even when the acceptance falls before the selected window. Current item and verdict rows do not replace event evidence.`stats.flow` adds the flow through the board:diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex b2af58f0..faff46c4 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -20,7 +20,9 @@ stateDiagram-v2claimed --> submitted: submitsubmitted --> submitted: reservesubmitted --> verified: accept+ verified --> verified: acceptsubmitted --> open: reject+ verified --> open: rejectsubmitted --> open: reopenverified --> open: reopenopen --> open: escalate@@ -56,8 +58,8 @@ Each move checks its guards in this order and refuses with the first one that do| 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), correctionRefrozen (PENDING_REFREEZE), 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), roadmapReadable (MILESTONES_CORRUPT), 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), 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) |+| accept | submitted, verified | 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), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), 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, verified | 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), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED) || reopen | submitted, verified | open | coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_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, when there is no live claim awaiting a coordinator correction | joined (NOT_JOINED), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |@@ -79,8 +81,8 @@ Each move checks its guards in this order and refuses with the first one that do| NOT_YOURS | release: the item is in claimed | pullboard show <id> || NOT_YOURS | submit: the item is in claimed | pullboard show <id> || NOT_SUBMITTED | reserve: the item is in submitted | pullboard show <id> |-| NOT_SUBMITTED | accept: the item is in submitted | pullboard show <id> |-| NOT_SUBMITTED | reject: the item is in submitted | pullboard show <id> |+| NOT_SUBMITTED | accept: the item is in submitted, verified | pullboard show <id> |+| NOT_SUBMITTED | reject: the item is in submitted, verified | pullboard show <id> || NOT_SUBMITTED | reopen: the item is in submitted, verified | pullboard show <id> || CLOSED | escalate: the item is in open, claimed | pullboard show <id> || CLOSED | refreeze: the item is in open, claimed, submitted | pullboard show <id> |@@ -120,8 +122,8 @@ Each move checks its guards in this order and refuses with the first one that do| 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 |+| CHECK_RED | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | reject the failing behavior; the builder fixes and resubmits |+| CHECK_UNVERIFIED | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | 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 || PIPEFAIL_UNAVAILABLE | the gate, which submit runs itself every time, is green at HEAD | rewrite the gate without a pipe || 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 |@@ -132,6 +134,11 @@ Each move checks its guards in this order and refuses with the first one that do| NO_POLICY | the caller's checkout contains the submitted commit | restore the frozen policy objects || BAD_CONFIG | the caller's checkout contains the submitted commit | repair the committed coordinator configuration || GIT_GRAFTS | the caller's checkout contains the submitted commit | ask the coordinator to remove the Git graft file before retrying |+| BAD_VERDICT_REVIEW | a new review binds the submitted commit, a valid trunk commit and canonical candidate paths | restore the submitted Git objects and retry the review with current Pullboard |+| STALE_VERDICT | a stale acceptance is re-reviewed at a clean HEAD containing the current trunk, which stays fixed through its check | merge current main into the submitted commit and re-review it |+| DIRTY | a stale acceptance is re-reviewed at a clean HEAD containing the current trunk, which stays fixed through its check | commit the reviewed composition before re-reviewing |+| UNTRACKED | a stale acceptance is re-reviewed at a clean HEAD containing the current trunk, which stays fixed through its check | commit or ignore untracked files before re-reviewing |+| VERDICT_TRUNK_MOVED | a stale acceptance is re-reviewed at a clean HEAD containing the current trunk, which stays fixed through its check | merge the latest main and re-review the clean composition || SELF_VERIFY | the caller did not build it | another agent verifies it: pullboard next --verify || COORDINATOR_VERIFIES | the repo's verify policy lets the caller verify this lane's work | the coordinator verifies it || O2_FAMILY_MATCH | the builder and verifier have different declared families; an undeclared family counts as a match, only when verify.family is require | ask the coordinator for a verifier from another declared family |diff --git a/src/api.js b/src/api.jsindex 71711c05..fa768894 100644--- a/src/api.js+++ b/src/api.js@@ -17,6 +17,8 @@ import { proofStats } from './stats.js';import { prepareFlowHistory, projectFlowStats } from './stats-flow.js';import { projectRowDecisions } from './row-decisions.js';import { Refused } from './refused.js';+import { verdictProjector } from './verdict-freshness.js';+import { trunkRef } from './trusted-policy.js';import { codeAt, projectItemState, projectState } from './serve.js';import { relayPresentationShout } from './relay-presentation.js';import { createApiHandler } from './api-http.js';@@ -26,7 +28,7 @@ export { moveArgs } from './api-moves.js';/** Inputs shared by the complete state cache and the lightweight live-change watcher. */const STATE_REVISION_INPUTS = Object.freeze([- 'identity', 'head', 'files', 'event', 'agents', 'leases', 'requestReceipts', 'milestones', 'externalRoadmap', 'eventLogVersion',+ 'identity', 'head', 'trunk', 'files', 'event', 'agents', 'leases', 'requestReceipts', 'milestones', 'externalRoadmap', 'eventLogVersion',]);/** Serialize named state inputs in one stable order for cache and stream comparisons. */@@ -99,6 +101,7 @@ function boardStateRevision(root, id, isMain, { projects = listApiProjects, scopconst inputs = {identity: [info.commonDir, id],head: resolveCommit(info.root, 'HEAD'),+ trunk: trunkRevisionReader(info)(),files,event: local.event,agents: local.agents,@@ -155,6 +158,36 @@ function headFileRevision(info) {}}+const TRUNK_REVISION_READERS = new Map();++/** Watch the primary trunk ref even when this served worktree's HEAD remains fixed [E8]. */+function trunkRevisionReader(info) {+ const cached = TRUNK_REVISION_READERS.get(info.commonDir);+ if (cached) return cached;+ let retainedMarker = null;+ let retained = null;+ /** Read loose or packed refs without spawning Git in every event-stream poll. */+ const read = () => {+ const head = readFileSync(join(info.commonDir, 'HEAD'), 'utf8').trim();+ let ref = /^ref: (refs\/heads\/.+)$/u.exec(head)?.[1];+ if (!ref) {+ const marker = fileMarkerForPath(join(info.commonDir, 'config'));+ if (marker !== retainedMarker) { retained = trunkRef(info.root); retainedMarker = marker; }+ ref = retained;+ }+ if (!ref?.startsWith('refs/heads/') || ref.includes('\\') || ref.split('/').some(part => !part || part === '.' || part === '..')) return null;+ try { return readFileSync(join(info.commonDir, ref), 'utf8').trim(); }+ catch (error) { if (error.code !== 'ENOENT') throw error; }+ try {+ return readFileSync(join(info.commonDir, 'packed-refs'), 'utf8').split('\n')+ .find(line => line.endsWith(' ' + ref))?.split(' ')[0] ?? null;+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }+ };+ TRUNK_REVISION_READERS.set(info.commonDir, read);+ while (TRUNK_REVISION_READERS.size > 32) TRUNK_REVISION_READERS.delete(TRUNK_REVISION_READERS.keys().next().value);+ return read;+}+/*** Read the machine registry that milestoneRoadmap resolves against, without listApiProjects' pruning* or metadata writes: a poll must not rewrite the registry it watches.@@ -245,6 +278,7 @@ function openRoadmapInputs(root, milestones, localDb, { scopeCommonDir = null }/** Watch the same named state inputs as the cache without rebuilding a board-state response. */function watchLocalStateRevision(board, { scopeCommonDir = null } = {}) {const info = repoInfo(board.root);+ const readTrunk = trunkRevisionReader(info);const config = loadConfig(info.root);let files = stateFileInputs(info.root, config);const dbPath = join(info.commonDir, 'pullboard', 'board.sqlite');@@ -345,6 +379,7 @@ function watchLocalStateRevision(board, { scopeCommonDir = null } = {}) {return stateRevision({identity: [info.commonDir, board.id],head,+ trunk: readTrunk(),files: fileContent,event: local.event,agents: local.agents,@@ -399,8 +434,13 @@ function buildLocalBoardState(root, boardId, board, codeIsMain, { previous = nul}const config = loadConfig(root);+ const freshness = verdictProjector(root, board, { main: trunkRevisionReader(repoInfo(root))() });const state = projectState(root, { seen: null, board, itemProjector: (item, context) => {- if (dirtyIds.has(item.item_id)) return context.project();+ if (dirtyIds.has(item.item_id)) {+ const projected = context.project();+ const verdictState = freshness.state(item);+ return verdictState ? { ...projected, verdictState } : projected;+ }return previous.items.get(item.item_id);} });state.agents = state.agents.map((agent) => ({ ...agent, model: agent.agent_model ?? 'unknown', displayName: displayAgentName(agent, config.agents.names) }));@@ -470,7 +510,7 @@ function milestoneNamesByItem(milestones) {/** What a board-state item summary keeps: what the lists and the roadmap read (A2, N26). */const SUMMARY_FIELDS = Object.freeze(['id', 'title', 'lane', 'status', 'route', 'milestone', 'specs', 'claim', 'builtBy',- 'blockedBy', 'updatedAt', 'stage', 'since', 'counts', 'verdict']);+ 'blockedBy', 'updatedAt', 'stage', 'since', 'counts', 'verdict', 'verdictState']);const SUMMARY_KEYS = new Set(SUMMARY_FIELDS);const CLOCK_MOVES = MACHINE.moves.filter((move) => move.by.includes('clock'));@@ -575,7 +615,7 @@ function itemSummary(item) {/** Everything a summary leaves out, with the latest verdict whole: laid over its summary, it is the full item. */function itemDetail(item) {- return Object.fromEntries(Object.entries(item).filter(([key]) => key === 'id' || key === 'verdict' || !SUMMARY_KEYS.has(key)));+ return Object.fromEntries(Object.entries(item).filter(([key]) => key === 'id' || key === 'verdict' || key === 'verdictState' || !SUMMARY_KEYS.has(key)));}/** The text the view's search matches for an item, lowercased: its #id, title, lane, spec ids and criterion. */@@ -892,6 +932,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const cookieKey = sessionCookie === undefined ? null : Buffer.from(sessionCookie.value);const permittedOrigins = new Set(allowedOrigins);const stateCache = new Map();+ const verdictCache = new Map();// The fingerprints of the summary states each board's clients were sent, least recently sent// first, and the latest sequence a forgotten one had. A build only read for an item, a search or// a reset was never sent, so no client holds it and it is never a base.@@ -910,7 +951,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =const previous = cached.inputs;const current = before.inputs;if (!previous) return true;- return ['identity', 'head', 'files', 'eventLogVersion'].some((key) => JSON.stringify(previous[key]) !== JSON.stringify(current[key]));+ return ['identity', 'head', 'trunk', 'files', 'eventLogVersion'].some((key) => JSON.stringify(previous[key]) !== JSON.stringify(current[key]));}/** Changed lease tuples include eventless claim/review expiry. */function changedLeaseItems(cached, before) {@@ -1022,8 +1063,26 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =if (row) status.set(dependency, row.item_status);}const base = projectItemState(currentBoard, source, status);+ // Detail reads need no new Git process while the trunk and immutable receipt log hold.+ const info = repoInfo(board.root);+ const tip = trunkRevisionReader(info)();+ const verdictCacheId = JSON.stringify([info.commonDir, board.id]);+ const event = currentBoard.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id;+ const revision = JSON.stringify([tip, event]);+ let cachedVerdicts = verdictCache.get(verdictCacheId);+ if (cachedVerdicts?.revision !== revision) {+ cachedVerdicts = { revision, states: new Map() };+ verdictCache.delete(verdictCacheId);+ verdictCache.set(verdictCacheId, cachedVerdicts);+ while (verdictCache.size > 32) verdictCache.delete(verdictCache.keys().next().value);+ }+ // The projector owns this transaction's connection; only derived values cross requests.+ const verdictState = cachedVerdicts.states.has(id) ? cachedVerdicts.states.get(id)+ : verdictProjector(board.root, currentBoard, { main: tip }).state(source);+ cachedVerdicts.states.set(id, verdictState);const projected = {...base,+ ...(verdictState ? { verdictState } : {}),check: source.item_check,...(source.item_check_baseline ? { checkBaseline: source.item_check_baseline } : {}),thread: store.itemThread(currentBoard, id),diff --git a/src/board.js b/src/board.jsindex 025ae554..a8394992 100644--- a/src/board.js+++ b/src/board.js@@ -12,7 +12,7 @@ import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';import { briefFiles, briefSections } from './brief.js';import { COORDINATOR } from './config.js';-import { ENGINE_VERSION, GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, effectiveGuards, storeTriggers } from './machine.js';+import { ENGINE_VERSION, VERDICT_REVIEW_ENGINE, GUARDS, IN_STATE, MOVES, STATES, UNKNOWN_MOVE, effectiveGuards, storeTriggers } from './machine.js';import { Refused } from './refused.js';import { parseSpec } from './spec.js';@@ -1465,8 +1465,21 @@ function reserveWithin(board, id, { agentId, leaseMs, policy, familyPolicy = 'ofreturn getItem(board, id);}+/** Validate a sealed review without consulting Git or changing either replica [E8,H16]. */+export function verdictReviewProblem(review, commit) {+ const valid = review && typeof review === 'object' && !Array.isArray(review)+ && Object.keys(review).sort().join(',') === 'commit,paths,trunk'+ && review.commit === commit && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(review.commit ?? '')+ && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(review.trunk ?? '')+ && Array.isArray(review.paths) && review.paths.every(path => typeof path === 'string' && !path.includes('\0')+ && path.split('/').every(part => part && part !== '.' && part !== '..'))+ && JSON.stringify(review.paths) === JSON.stringify([...new Set(review.paths)].sort());+ return valid ? null : new Refused('BAD_VERDICT_REVIEW', 'the review must bind the current submitted commit, its reviewed trunk and sorted unique candidate paths; use current Pullboard to review it again');+}+/**- * Record a verdict on a submitted item (V1, V3, V5, V6, V8): an accept verifies it, a reject+ * Record a verdict on submitted work, or a sealed re-review of unlanded work (E8,V1,V3,V8).+ * An accept verifies it; a reject* reopens it for rework.** The verdict binds the submitted commit and the digest frozen at claim. If the criterion's text@@ -1478,21 +1491,32 @@ function reserveWithin(board, id, { agentId, leaseMs, policy, familyPolicy = 'of** @param {any} board* @param {number} id- * @param {{ agentId: string, decision: string, reason?: string, note?: string, head: string, digest: string, policy: string, familyPolicy?: string, check?: 'none' | 'green' }} verdict+ * @param {{ agentId: string, decision: string, reason?: string, note?: string, head: string, digest: string, policy: string, familyPolicy?: string, check?: 'none' | 'green', review?: {commit: string, trunk: string, paths: string[]} }} verdict* @returns {{ decision: string, reason: string, check?: 'none' | 'green' }}*/-export function verify(board, id, { agentId, decision, reason, note = '', head, digest, policy, familyPolicy = 'off', check }) {+export function verify(board, id, { agentId, decision, reason, note = '', head, digest, policy, familyPolicy = 'off', check, review }) {const verb = { ACCEPT: 'accept', REJECT: 'reject' }[decision];if (!verb) throw new Refused('BAD_DECISION', 'the decision is accept or reject');const isAccept = verb === 'accept';const code = isAccept ? ACCEPT_REASON : reason;+ const engine = board.executionEngineVersion ?? ENGINE_VERSION;+ const declaration = MOVES.find(move => move.verb === verb);+ const newReview = engine >= VERDICT_REVIEW_ENGINE && review !== undefined;+ // Without the new sealed metadata, old moves keep their exact submitted-only semantics.+ const transition = newReview ? declaration : { ...declaration, from: ['submitted'],+ guards: declaration.guards.filter(guard => !['notMerged', 'verdictReviewRecorded', 'reviewTreeCurrent'].includes(guard)) };return atomic(board, () => {const item = moveItem(board, id, verb, {+ transition,checks: {coordinatorSaysAs: null,joined: null,[IN_STATE]: (found) => new Refused('NOT_SUBMITTED', `item #${id} is ${current(board, found).item_status}, not submitted`),atSubmittedCommit: null,+ notMerged: found => !found.item_merged_commit ? null+ : new Refused('ALREADY_MERGED', `item #${id} already landed; only unlanded acceptances can be re-reviewed`),+ verdictReviewRecorded: found => verdictReviewProblem(review, found.item_commit),+ reviewTreeCurrent: null,...reviewerChecks(board, { agentId, policy, familyPolicy }),criterionUnchanged: (found) =>digest === found.item_frozen_digest@@ -1523,6 +1547,7 @@ export function verify(board, id, { agentId, decision, reason, note = '', head,});const detail = { reason: code, commit: item.item_commit };if (isAccept && check !== undefined) detail.check = check;+ if (newReview) detail.review = { commit: review.commit, trunk: review.trunk, paths: [...review.paths] };logEvent(board, agentId, verb, id, detail);return { decision, reason: code, ...(isAccept && check !== undefined ? { check } : {}) };});@@ -1797,7 +1822,7 @@ export function verdictsFor(board, id) {return verdicts.map((verdict, index) => {let detail = {};try { detail = JSON.parse(receipts[index]?.event_detail ?? '{}'); } catch { /* Malformed legacy details remain unknown. */ }- return { ...verdict, check: detail.check ?? 'unknown' };+ return { ...verdict, check: detail.check ?? 'unknown', ...(detail.review ? { review: detail.review } : {}) };});}diff --git a/src/cli.js b/src/cli.jsindex 062d6c58..5daf6987 100644--- a/src/cli.js+++ b/src/cli.js@@ -76,6 +76,7 @@ import { serveApi } from './api.js';import { doctorProblems, doctrineProblems } from './doctor.js';import { staleFrozenItems, staleItemFinding } from './approved-rows.js';import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge, trunkRef } from './trusted-policy.js';+import { captureVerdictReview, staleVerdictRefusal, verdictProjector, verdictTrunk } from './verdict-freshness.js';import { proofStats } from './stats.js';import { flowLines, flowAlertLine } from './stats-flow.js';import { releaseHeadlinesBetween } from './changelog.js';@@ -841,8 +842,9 @@ function itemLine(item, name = (id) => id) {const after = item.item_after ? ` after ${item.item_after.split(',').map((id) => `#${id}`).join(',')}` : '';const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : '';const light = item.item_route === 'strong' ? '' : ` ${item.item_route}`;+ const staleVerdict = item.item_verdict_state ? ` ${item.item_verdict_state.code}` : '';const hold = item.item_hold_reason ? ` held by ${name(item.item_hold_by)}: ${item.item_hold_reason}` : '';- return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}${hold}`;+ return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}${hold}${staleVerdict}`;}/** Format a stable agent id for human-facing CLI output. */@@ -1034,6 +1036,10 @@ function coordinatorNext(card, rows) {const [first] = card.toMerge;return `merge #${first.item_id}: git merge --no-edit ${first.item_commit.slice(0, 12)}, run the gate, then pullboard merged ${first.item_id} <merge commit>`;}+ if (card.staleVerdicts?.length) {+ const item = card.staleVerdicts[0];+ return staleVerdictRefusal(item, item.item_verdict_state).message.replace(/^\[STALE_VERDICT\] /u, '');+ }if (card.open.length) {const lanes = [...new Set(card.open.map((item) => item.item_lane))];return `start a builder for each lane with open items (${lanes.join(', ')}): pullboard worktree <lane> --model "<model name>", then the pullboard-run skill`;@@ -1269,8 +1275,11 @@ function resumeHere(io) {const card = withBoard(ctx, (board) => {setupScope = setupIdentity(board);const me = whoAmI(ctx, board);- const all = store.listItems(board, { all: true });- const toMerge = all.filter((item) => item.item_status === 'verified' && !item.item_merged_commit);+ const projector = verdictProjector(root, board);+ const all = store.listItems(board, { all: true }).map(projector.project);+ const pendingMerges = all.filter((item) => item.item_status === 'verified' && !item.item_merged_commit);+ const toMerge = pendingMerges.filter(item => !item.item_verdict_state);+ const staleVerdicts = pendingMerges.filter(item => item.item_verdict_state);const decisionSections = isMain ? coordinatorDecisionSections(board, ctx) : null;const { shouts = [], ...decisions } = decisionSections ?? {};return {@@ -1286,6 +1295,7 @@ function resumeHere(io) {awaiting: all.filter((item) => item.item_status === 'submitted' && item.item_built_by === me.id),toVerify: all.filter((item) => item.item_status === 'submitted' && item.item_built_by !== me.id),toMerge,+ staleVerdicts,...(isMain ? { landingBatches: store.landingBatches(board) } : {}),open: all.filter((item) => item.item_status === 'open'),hold: store.laneHold(board, me.lane),@@ -1354,6 +1364,7 @@ function resumeHere(io) {}if (isMain && card.staleFollowUps.count) say(`${plural(card.staleFollowUps.count, 'stale follow-up')}; list them with ${card.staleFollowUps.list}`);else if (!isMain) for (const item of card.stale) say(`stale: ${item.message}; next: ${item.next}`);+ for (const item of card.staleVerdicts) say(staleVerdictRefusal(item, item.item_verdict_state).message);if (card.awaiting.length) say(`awaiting a verdict: ${card.awaiting.map((item) => `#${item.item_id} (${span(ctx, item.item_updated_at)})`).join(', ')}`);if (isMain) {for (const batch of card.landingBatches.filter((entry) => !['landed', 'blocked'].includes(entry.state))) say(`landing ${batch.id}: ${batch.state}, owner ${batch.owner}, tip ${batch.tip}; log ${batch.logPath}; next: pullboard land --adopt`);@@ -1916,7 +1927,7 @@ function readCommands(io, { first, second, rest, values }) {list: () => {const ctx = context(io);const { items, agents } = withBoard(ctx, (board) => ({- items: store.listItems(board, { lane: first, all: values.all }),+ items: store.listItems(board, { lane: first, all: values.all }).map(verdictProjector(ctx.info.root, board).project),agents: store.listAgents(board),}));const filtered = items.filter((item) => !values.route || item.item_route === values.route);@@ -1945,7 +1956,7 @@ function readCommands(io, { first, second, rest, values }) {const ctx = context(io);const id = idArg(first);const { item, verdicts, moves, thread, related, reviewer, agents } = withBoard(ctx, (board) => ({- item: store.getItem(board, id),+ item: verdictProjector(ctx.info.root, board).project(store.getItem(board, id)),verdicts: store.verdictsFor(board, id),moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),thread: store.itemThread(board, id),@@ -1959,6 +1970,7 @@ function readCommands(io, { first, second, rest, values }) {return 0;}io.say(itemLine(item, agentName));+ if (item.item_verdict_state) io.say(staleVerdictRefusal(item, item.item_verdict_state).message);if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);if (item.item_check) io.say(`check: ${item.item_check}`);sayCheckBaseline(io, item);@@ -2388,7 +2400,9 @@ async function verifyHere(ctx, id, { second, values }) {return await ordered(ctx, board, 'verify', recovered.args);}const item = store.getItem(board, id);- if (item.item_status !== 'submitted') {+ const reReview = item.item_status === 'verified' && !item.item_merged_commit;+ const stale = reReview ? verdictProjector(root, board).state(item) : null;+ if (item.item_status !== 'submitted' && !stale) {throw new Refused('NOT_SUBMITTED', `item #${id} is ${item.item_status}, not submitted`);}const policy = itemPolicy(root, item);@@ -2400,6 +2414,7 @@ async function verifyHere(ctx, id, { second, values }) {}let digest = 'missing';let check;+ let review;try {digest = freezer(ctx)(item).digest;} catch (error) {@@ -2407,23 +2422,38 @@ 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');- const trunk = requireTrunkMerge(root, commit);- refuseUnverifiedStack(root, board, item, commit, trunk);- const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(root, frozenCheck(item), { commit, onFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });- check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs, gateLease: lease }), { browser, agent: me.id, item: String(id), kind: 'review', itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ const checkedCommit = reReview ? head : commit;+ const checkedLabel = reReview ? 'reviewed composition' : 'submitted commit';+ const trunk = requireTrunkMerge(root, checkedCommit);+ if (reReview) {+ if (!isClean(root)) throw new Refused('DIRTY', 'commit the reviewed composition before re-reviewing the stale verdict');+ if (untracked(root).length) throw new Refused('UNTRACKED', 'commit or ignore untracked files before re-reviewing the stale verdict');+ if (!contains(root, trunk.commit, head)) throw staleVerdictRefusal(item, stale);+ }+ review = captureVerdictReview(root, board, item, trunk.commit);+ refuseUnverifiedStack(root, board, item, checkedCommit, trunk);+ const checkedItem = reReview ? { ...item, item_commit: checkedCommit } : item;+ const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(root, frozenCheck(item), { commit: checkedCommit, onFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });+ check = await withGateSlot(root, (lease) => checkAtCommit(root, checkedItem, { waitMs: lease.waitMs, gateLease: lease }), { browser, agent: me.id, item: String(id), kind: 'review', itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ invalidateGitFacts(); // A private check can outlive changes in the reviewer's live checkout.verificationProfile = check.profile ?? null;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}` : ''})`}`: '';const checkTimings = timingDigest(check.profile);const timingEvidence = check.profilePath ? `\n${checkTimings}\ntiming profile: ${check.profilePath}` : '';- if (check.state === 'unverified') throw new Refused('CHECK_UNVERIFIED', `the frozen ${check.stage} could not be verified at the submitted commit; restore the install or check environment, then retry verification; output digest:\n${check.report.replace(/^/gm, ' ')}${evidence}${timingEvidence}`);- 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}${timingEvidence}`);+ if (check.state === 'unverified') throw new Refused('CHECK_UNVERIFIED', `the frozen ${check.stage} could not be verified at the ${checkedLabel}; restore the install or check environment, then retry verification; output digest:\n${check.report.replace(/^/gm, ' ')}${evidence}${timingEvidence}`);+ if (check.state === 'red') throw new Refused('CHECK_RED', `the frozen item check is red at the ${checkedLabel} (${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}${timingEvidence}`);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) });- const currentTrunk = requireTrunkMerge(root, commit); // Re-read after the frozen check, before accepting.- refuseUnverifiedStack(root, board, item, commit, currentTrunk);+ const currentTrunk = requireTrunkMerge(root, checkedCommit); // Re-read after the frozen check, before accepting.+ if (currentTrunk.commit !== trunk.commit) throw new Refused('VERDICT_TRUNK_MOVED', `main moved from ${trunk.commit} to ${currentTrunk.commit} during review; merge the latest main and re-review the clean composition`);+ if (headCommit(root) !== head || (reReview && (!isClean(root) || untracked(root).length))) {+ throw new Refused('NOT_AT_COMMIT', 'the reviewed checkout moved during its check; restore the clean reviewed HEAD and retry verification');+ }+ refuseUnverifiedStack(root, board, item, checkedCommit, currentTrunk);}+ review ??= captureVerdictReview(root, board, item, verdictTrunk(root));return await ordered(ctx, board, 'verify', [id, {agentId: me.id,decision,@@ -2433,6 +2463,7 @@ async function verifyHere(ctx, id, { second, values }) {digest,policy: ctx.config.verify.policy,familyPolicy: ctx.config.verify.family,+ review,...(decision === 'ACCEPT' ? { check: check.checked ? 'green' : 'none' } : {}),}]);});@@ -2906,6 +2937,7 @@ function workCommands(io, args) {write: (operation, parameters) => ordered(ctx, board, operation, parameters), say: io.say, owner: agentSessionDigest() ?? `pid-${process.pid}`,maximum: values.max === undefined ? Infinity : Number(values.max), dryRun: Boolean(values['dry-run']), adopt: Boolean(values.adopt), onWait: gateWaitReporter(io) });io.result?.(result);+ for (const blocked of result.blocked ?? []) if (blocked.code === 'STALE_VERDICT') io.say(staleVerdictRefusal({ item_id: blocked.id }, blocked).message);if (!result.batch) io.say(result.items ? `would land: ${result.items.map((id) => `#${id}`).join(', ') || 'none'}` : 'no verified items ready to land');return 0;}),diff --git a/src/engine.js b/src/engine.jsindex 3b5c167c..cc1b1cb2 100644--- a/src/engine.js+++ b/src/engine.js@@ -2,7 +2,7 @@import { createHash, randomUUID } from 'node:crypto';import * as store from './board.js';import { refusalDocument } from './json.js';-import { ENGINE_VERSION } from './machine.js';+import { ENGINE_VERSION, VERDICT_REVIEW_ENGINE } from './machine.js';import { Refused } from './refused.js';import { requestMoveProblem, recordRequestMove } from './relay-requests.js';import { relayMoveActor, relaySenderProblem, validRelaySender } from './relay-sender.js';@@ -22,9 +22,10 @@ export const ENGINE_OPERATIONS = Object.freeze([/** Engine version at which each ordered operation first has stable replay semantics. */const OPERATION_ENGINE = Object.freeze({ reopen: 8, recordLandingBatch: 8, recordLandingWaiver: 8, recordLandingFlake: 8, finishLandingBatch: 8 });-/** Dependency edits add engine-10 meaning without changing ordinary historical edit envelopes. */+/** Dependency edits and sealed review metadata need their own engine meanings; historical envelopes retain theirs. */function minimumOperationEngine(operation, args) {const options = args[1];+ if (operation === 'verify' && options && Object.hasOwn(options, 'review')) return VERDICT_REVIEW_ENGINE;return operation === 'editItem' && options && Object.hasOwn(options, 'after') && options.after !== undefined? 10 : OPERATION_ENGINE[operation] ?? 1;}diff --git a/src/land.js b/src/land.jsindex 03816629..79cc3c24 100644--- a/src/land.js+++ b/src/land.js@@ -7,6 +7,7 @@ import { git, headCommit, headTree, isClean, mainCheckout, repoInfo, tryGit, untimport { runGate, runProfiledShell, withGateSlot } from './gate.js';import { laneOf } from './lanes.js';import { Refused } from './refused.js';+import { staleVerdictRefusal, verdictProjector } from './verdict-freshness.js';/** Quote a command argument without allowing shell interpolation. */function quote(value) { return `'${String(value).replaceAll("'", "'\\''")}'`; }@@ -59,6 +60,7 @@ export function landingSubject(item) {/** Select verified, unmerged candidates in verdict order, retaining dependency order [B3,R3]. */function candidates(board, root, base, maximum) {const all = store.listItems(board, { all: true });+ const projector = verdictProjector(root, board, { main: base });const pending = all.filter((item) => item.item_status === 'verified' && !item.item_merged_commit);const order = new Map();for (const event of store.events(board)) if (event.event_kind === 'accept') order.set(event.item_id, event.event_id);@@ -67,6 +69,8 @@ function candidates(board, root, base, maximum) {const blocked = [];const knownReds = store.landingBatches(board).flatMap((batch) => batch.culprits ?? []);for (const item of pending) {+ const stale = projector.state(item);+ if (stale) { blocked.push({ id: item.item_id, ...stale }); continue; }const known = knownReds.find((entry) => entry.id === item.item_id && entry.commit === item.item_commit);if (known && !known.tests.every((failure) => store.landingWaiverFor(board, failure))) {blocked.push({ id: item.item_id, code: 'LAND_KNOWN_RED', tests: known.tests });@@ -103,6 +107,8 @@ async function mergeGroup(state, items) {for (const entry of items) {const item = store.getItem(state.board, entry.id ?? entry.item_id);if (item.item_status !== 'verified' || item.item_commit !== (entry.commit ?? item.item_commit)) throw new Refused('LAND_ITEM_MOVED', `item #${item.item_id} changed; rebuild the batch from current verified work`);+ const stale = verdictProjector(state.root, state.board, { main: batch.base }).state(item);+ if (stale) throw staleVerdictRefusal(item, stale);const result = tryGit(batch.root, ['merge', '--no-ff', item.item_commit, '-m', landingSubject(item)]);if (result.status !== 0) {const files = tryGit(batch.root, ['diff', '--name-only', '--diff-filter=U']).stdout.split('\n').filter(Boolean);@@ -262,6 +268,8 @@ export async function land({ root, board, config, write, say, owner, maximum = Iif (!trunk?.commit) throw new Refused('LAND_TRUNK', 'landing needs the coordinator’s primary branch; return its checkout to the trunk');const unfinished = store.landingBatches(board).findLast((batch) => batch.state !== 'landed' && batch.state !== 'blocked');const selected = candidates(board, root, trunk.commit, maximum);+ const stale = selected.blocked.find(item => item.code === 'STALE_VERDICT');+ if (!selected.ready.length && stale) throw staleVerdictRefusal({ item_id: stale.id }, stale);if (dryRun) {const conflicts = [];for (const item of selected.ready) {diff --git a/src/machine.js b/src/machine.jsindex 605bf80b..11ce2e18 100644--- a/src/machine.js+++ b/src/machine.js@@ -10,7 +10,10 @@*//** Executable move semantics, carried by every sealed move and retained during replay [H16]. */-export const ENGINE_VERSION = 12;+export const ENGINE_VERSION = 13;++/** First engine sealing reviewed trunk/path metadata and append-only re-review [E8,H16]. */+export const VERDICT_REVIEW_ENGINE = 13;/** @typedef {'agent' | 'coordinator' | 'clock'} Role */@@ -120,13 +123,15 @@ export const GUARDS = [{ 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: '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 submitted commit, or its clean reviewed composition for a stale acceptance', 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' },{ id: 'treeStillDuringGate', refuse: 'MOVED_DURING_GATE', rule: 'when the gate ends, HEAD and every tracked file are as they were when it started', next: 'leave the worktree alone until the gate finishes, then submit again', source: 'cli' },{ id: 'childrenDone', refuse: 'CHILDREN_OPEN', rule: 'every child item is verified or withdrawn', next: 'finish the child items, or the coordinator withdraws them', source: 'board' },{ id: 'headIsNew', refuse: 'HEAD_NOT_NEW', rule: 'a verifier has not rejected this commit at this bar; after a no-verdict reopen, the bar was refrozen', next: 'commit the rework, or refreeze the bar after a no-verdict reopen before resubmitting the same commit', source: 'board' },{ id: 'atSubmittedCommit', refuse: 'NOT_AT_COMMIT', alsoRefuses: [{ code: 'OUTSIDE_LANE', next: 'restore foreign paths before accepting' }, { code: 'NO_POLICY', next: 'restore the frozen policy objects' }, { code: 'BAD_CONFIG', next: 'repair the committed coordinator configuration' }, { code: 'GIT_GRAFTS', next: 'ask the coordinator to remove the Git graft file before retrying' }], rule: "the caller's checkout contains the submitted commit", next: 'git switch --detach <commit>', source: 'cli' },+ { id: 'verdictReviewRecorded', refuse: 'BAD_VERDICT_REVIEW', rule: 'a new review binds the submitted commit, a valid trunk commit and canonical candidate paths', next: 'restore the submitted Git objects and retry the review with current Pullboard', source: 'board' },+ { id: 'reviewTreeCurrent', refuse: 'STALE_VERDICT', alsoRefuses: [{ code: 'DIRTY', next: 'commit the reviewed composition before re-reviewing' }, { code: 'UNTRACKED', next: 'commit or ignore untracked files before re-reviewing' }, { code: 'VERDICT_TRUNK_MOVED', next: 'merge the latest main and re-review the clean composition' }], rule: 'a stale acceptance is re-reviewed at a clean HEAD containing the current trunk, which stays fixed through its check', next: 'merge current main into the submitted commit and re-review it', source: 'cli' },{ id: 'notBuilder', refuse: 'SELF_VERIFY', rule: 'the caller did not build it', next: 'another agent verifies it: pullboard next --verify', source: 'board' },{ id: 'policyAllows', refuse: 'COORDINATOR_VERIFIES', rule: "the repo's verify policy lets the caller verify this lane's work", next: 'the coordinator verifies it', source: 'board' },{ id: 'familyAllows', refuse: 'O2_FAMILY_MATCH', rule: 'the builder and verifier have different declared families; an undeclared family counts as a match', next: 'ask the coordinator for a verifier from another declared family', source: 'board', when: 'only when verify.family is require' },@@ -164,13 +169,13 @@ export const MOVES = [sets: ['item_review_by', 'item_review_until'], command: 'pullboard next --verify',},{- 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', 'noUnverifiedStack', 'itemCheckGreen', 'proofNoted'],+ verb: 'accept', from: ['submitted', 'verified'], to: 'verified', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED',+ guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notMerged', 'verdictReviewRecorded', 'reviewTreeCurrent', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonIsMet', 'trunkMergeClean', 'noUnverifiedStack', 'itemCheckGreen', 'proofNoted'],sets: ['item_verified_by'], command: 'pullboard verify <id> accept --note "..."',},{- verb: 'reject', from: ['submitted'], to: 'open', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED',- guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonCoded', 'noteGiven'],+ verb: 'reject', from: ['submitted', 'verified'], to: 'open', by: ['agent', 'coordinator'], refuse: 'NOT_SUBMITTED',+ guards: ['coordinatorSaysAs', 'joined', 'itemExists', IN_STATE, 'atSubmittedCommit', 'notMerged', 'verdictReviewRecorded', 'reviewTreeCurrent', 'notBuilder', 'routeAllows', 'policyAllows', 'familyAllows', 'reviewFree', 'criterionUnchanged', 'reasonCoded', 'noteGiven'],command: 'pullboard verify <id> reject --reason CODE --note "..."',},{diff --git a/src/verdict-freshness.js b/src/verdict-freshness.jsnew file mode 100644index 00000000..b9983514--- /dev/null+++ b/src/verdict-freshness.js@@ -0,0 +1,119 @@+/** Acceptance stays append-only; freshness is derived from the known Git trunk [E8,V8]. */+import { spawnSync } from 'node:child_process';+import * as store from './board.js';+import { cleanGitEnvironment, mainCheckout } from './git.js';+import { trunkRef } from './trusted-policy.js';+import { Refused } from './refused.js';++/** Read exact Git objects without inherited selectors, replacements, or filename quoting. */+function readGit(root, args) {+ const result = spawnSync('git', ['--no-replace-objects', ...args], {+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024,+ });+ if (result.status !== 0) throw new Error('Git history is unavailable');+ return result.stdout;+}++/** Read the actual retained trunk tip, rather than a cached checkout HEAD used during review. */+export function verdictTrunk(root) {+ try {+ const ref = mainCheckout(root)?.branch ?? trunkRef(root);+ if (!ref?.startsWith('refs/heads/')) throw new Error('The retained trunk is unavailable');+ return readGit(root, ['rev-parse', '--verify', `${ref}^{commit}`]).trim();+ } catch {+ throw new Refused('BAD_VERDICT_REVIEW', 'the retained trunk cannot be read; restore its branch and Git objects before reviewing');+ }+}++/** Capture the review's trunk and candidate delta against its submitted coordinator snapshot. */+export function captureVerdictReview(root, board, item, trunk = verdictTrunk(root)) {+ const receipt = store.events(board, { itemId: item.item_id }).findLast(event => {+ if (event.event_kind !== 'submit') return false;+ return JSON.parse(event.event_detail).commit === item.item_commit;+ });+ const submittedMain = receipt ? JSON.parse(receipt.event_detail).policyCommit : null;+ const base = submittedMain ?? item.item_claim_head;+ if (!base) throw new Refused('BAD_VERDICT_REVIEW', 'the submitted base is unavailable; restore its Git objects before reviewing');+ try {+ const ancestor = readGit(root, ['merge-base', base, item.item_commit]).trim();+ const paths = readGit(root, ['diff', '--no-renames', '--name-only', '-z', ancestor, item.item_commit, '--'])+ .split('\0').filter(Boolean).sort();+ return { commit: item.item_commit, trunk, paths };+ } catch {+ throw new Refused('BAD_VERDICT_REVIEW', 'the submitted paths cannot be read; restore the submitted commit and base objects before reviewing');+ }+}++/** Name the concrete stale proof and the required re-review without changing the original verdict. */+export function staleVerdictRefusal(item, state) {+ const changed = state.file && state.commit+ ? `${JSON.stringify(state.file)} changed on main in ${state.commit}`+ : state.reason ?? 'the reviewed Git history is unavailable';+ return new Refused('STALE_VERDICT', `item #${item.item_id}: ${changed}; merge current main into the submitted commit, commit a clean composition, then another agent runs pullboard verify ${item.item_id} accept --note "what was re-reviewed" before landing`);+}++/** Create one read's projector, sharing Git history lookups across its unlanded acceptances. */+export function verdictProjector(root, board, { main } = {}) {+ let tip = main;+ let resolved = main !== undefined;+ const histories = new Map();+ const changes = new Map();+ /** Cache each first-parent range once, including changes whose effects were later reverted. */+ const history = baseline => {+ if (!histories.has(baseline)) {+ readGit(root, ['merge-base', '--is-ancestor', baseline, tip]);+ histories.set(baseline, readGit(root, ['rev-list', '--first-parent', '--reverse', `${baseline}..${tip}`]).trim().split('\n').filter(Boolean));+ }+ return histories.get(baseline);+ };+ /** Compare every commit with its first parent, so a merge's files and a revert both count. */+ const changedFiles = commit => {+ if (!changes.has(commit)) changes.set(commit,+ readGit(root, ['diff', '--no-renames', '--name-only', '-z', `${commit}^1`, commit, '--']).split('\0').filter(Boolean));+ return changes.get(commit);+ };+ /** Return a derived state only for a verified item still waiting to land. */+ const state = item => {+ if (item.item_status !== 'verified' || item.item_merged_commit) return null;+ let review;+ try {+ if (!resolved) {+ resolved = true;+ tip = verdictTrunk(root);+ }+ if (!tip) throw new Error('The known trunk is unavailable');+ // A physical landing is final even before its board merge receipt reaches this replica.+ const landed = spawnSync('git', ['--no-replace-objects', 'merge-base', '--is-ancestor', item.item_commit, tip],+ { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8' });+ if (landed.status === 0) return null;+ if (landed.status !== 1) throw new Error('The submitted commit is unavailable');+ const accepted = store.verdictsFor(board, item.item_id).findLast(verdict =>+ verdict.verdict_decision === 'ACCEPT' && verdict.verdict_commit === item.item_commit);+ review = accepted?.review;+ if (!review) {+ // Legacy receipts did not seal a reviewed trunk. Use a conservative claim-base bound,+ // never invent a capture time or rewrite those immutable receipts.+ const baseline = readGit(root, ['merge-base', item.item_claim_head, tip]).trim();+ review = { trunk: baseline,+ paths: readGit(root, ['diff', '--no-renames', '--name-only', '-z', baseline, item.item_commit, '--']).split('\0').filter(Boolean), legacy: true };+ }+ if (!review.legacy && store.verdictReviewProblem(review, item.item_commit)) throw new Error('The sealed review is invalid');+ const paths = new Set(review.paths);+ for (const commit of history(review.trunk)) {+ const file = changedFiles(commit).find(path => paths.has(path));+ if (file) return { code: 'STALE_VERDICT', file, commit, reviewedTrunk: review.trunk, main: tip,+ ...(review.legacy ? { legacy: true } : {}) };+ }+ return null;+ } catch {+ return { code: 'STALE_VERDICT', file: null, commit: null, reviewedTrunk: review?.trunk ?? null,+ main: tip ?? null, reason: 'the reviewed Git history is unavailable; restore its objects and re-review' };+ }+ };+ /** Decorate a public item read while preserving every stored proof field. */+ const project = item => {+ const freshness = state(item);+ return freshness ? { ...item, item_verdict_state: freshness } : item;+ };+ return { state, project, main: tip ?? null };+}diff --git a/test/agent-model-engine.test.js b/test/agent-model-engine.test.jsindex e85e2e8d..a37c0d00 100644--- a/test/agent-model-engine.test.js+++ b/test/agent-model-engine.test.js@@ -10,9 +10,9 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-test('model declarations and event snapshots retain engines 1 through 11 semantics [O8,O3,H16]', (t) => {- assert.equal(ENGINE_VERSION, 12, 'engine 12 preserves the released engine-8 through engine-11 model behavior');- for (const version of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ENGINE_VERSION]) {+test('model declarations and event snapshots retain engines 1 through 12 semantics [O8,O3,H16]', (t) => {+ assert.ok(ENGINE_VERSION > 12, 'the new writer preserves released model behavior through engine 12');+ for (const version of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ENGINE_VERSION]) {const board = store.openBoard(':memory:');t.after(() => store.closeBoard(board));const registration = prepareEngineMove(board, 'register', [{ lane: 'web', path: '/web', model: 'First Model' }]);diff --git a/test/land.test.js b/test/land.test.jsindex 6ebbbdb4..5471933a 100644--- a/test/land.test.js+++ b/test/land.test.js@@ -365,6 +365,7 @@ function submitItem(box, entry, contents = 'PASS\n') {/** Verify only private fixture items at their actual submitted commits. */function acceptItem(box, entry) {+ entry.reviewedTrunk = box.git(box.repo, 'rev-parse', 'main');box.git(box.repo, 'switch', '-q', '--detach', entry.commit);try {const verdict = box.run(box.repo, 'verify', String(entry.item), 'accept', '--as', 'coordinator', '--note', 'private landing fixture check passed');@@ -493,7 +494,7 @@ test('land pushes one exact batch in verdict order and records each first-contaiassert.equal(JSON.parse(lane.out).error?.code, 'COORDINATOR_ONLY');});-test('land bisects a real red, skips named conflicts and refuses an unverified stack [B3,R3]', () => {+test('land bisects a real red, blocks stale proof and refuses an unverified stack [B3,R3,E8]', () => {const box = landProject();box.env.LAND_SUPPRESS_RED = '1';const entries = FILES.map((file, index) => itemWorktree(box, index + 1, file));@@ -511,8 +512,12 @@ test('land bisects a real red, skips named conflicts and refuses an unverified sconst beforeEvents = events(box).length;const beforeCalls = calls(box).length;const dry = json(box, box.repo, 'land', '--max', '4', '--dry-run');- assert.deepEqual(dry.conflicts, [{ id: entries[1].item, files: [FILES[1]] }], JSON.stringify(dry));- assert.deepEqual(dry.blocked, [{ id: entries[3].item, code: 'STACKED_UNVERIFIED', stacked: hidden.item }]);+ assert.deepEqual(dry.conflicts, [], 'main changed the reviewed path, so stale proof is blocked before attempting its merge');+ assert.deepEqual(dry.blocked, [+ { id: entries[1].item, code: 'STALE_VERDICT', file: FILES[1], commit: base,+ reviewedTrunk: entries[1].reviewedTrunk, main: base },+ { id: entries[3].item, code: 'STACKED_UNVERIFIED', stacked: hidden.item },+ ]);assert.equal(events(box).length, beforeEvents, 'dry run creates no board batch');assert.equal(calls(box).length, beforeCalls, 'dry run runs no gate');const result = json(box, box.repo, 'land', '--max', '4');@@ -529,13 +534,28 @@ test('land bisects a real red, skips named conflicts and refuses an unverified sassert.equal(box.git(box.remote, 'rev-parse', 'main'), result.batch.tip);assert.notEqual(result.batch.tip, base);const afterCalls = calls(box).length;- const again = json(box, box.repo, 'land');- assert.deepEqual(again.landed, []);- assert.equal(json(box, box.repo, 'show', String(entries[2].item)).item_status, 'open', 'the known red is returned to its builder');- assert.ok(!again.blocked.some((entry) => entry.id === entries[2].item), 'returned work is not offered as a verified landing candidate');+ const again = box.run(box.repo, 'land', '--json');+ assert.equal(again.code, 1, again.out + again.err);+ assert.equal(JSON.parse(again.out).error.code, 'STALE_VERDICT', 'an all-blocked queue refuses instead of suggesting an empty successful land');+ assert.equal(json(box, box.repo, 'show', String(entries[2].item)).item_status, 'open', 'the known red is returned to its builder and is no longer a verified landing candidate');assert.equal(calls(box).length, afterCalls, 'known unchanged red is not retried');});+test('land names sibling conflicts whose reviews share the unchanged main [B3,R3,E8]', () => {+ const box = landProject();+ const entries = [1, 2].map(number => itemWorktree(box, number, FILES[0]));+ submitItem(box, entries[0], 'PASS\nfirst sibling\n');+ submitItem(box, entries[1], 'PASS\nsecond sibling\n');+ for (const entry of entries) acceptItem(box, entry);+ const dry = json(box, box.repo, 'land', '--dry-run');+ assert.deepEqual(dry.blocked, [], 'neither acceptance is stale against unchanged main');+ assert.deepEqual(dry.conflicts, [], 'each sibling merges with the current main considered individually');+ assert.deepEqual(dry.items, entries.map(entry => entry.item));+ const result = json(box, box.repo, 'land');+ assert.deepEqual(result.landed, [entries[0].item]);+ assert.deepEqual(result.conflicts, [{ id: entries[1].item, files: [FILES[0]] }], 'the actual batch names the collision between the two fresh siblings');+});+test('land diagnostics inherit their browser gate lease [C7]', () => {const box = landProject();const marker = join(box.dir, 'land-diagnostic-lease.json');diff --git a/test/machine.test.js b/test/machine.test.jsindex 985d8fc1..cfac6959 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -838,8 +838,8 @@ const PRECHECKED = {claim: ['joined'],submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'noUnverifiedStack'],reserve: ['coordinatorSaysAs', 'joined', 'roadmapReadable'],- accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'trunkMergeClean', 'itemCheckGreen', 'noUnverifiedStack'],- reject: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit'],+ accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'reviewTreeCurrent', 'trunkMergeClean', 'itemCheckGreen', 'noUnverifiedStack'],+ reject: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'reviewTreeCurrent'],};/**@@ -956,15 +956,20 @@ test('submit, accept and reject refuse in the declared order, one failure peeledfor (const verb of ['accept', 'reject']) {const decision = verb === 'accept' ? 'ACCEPT' : 'REJECT';const built = submittedItem(board);+ const landed = submittedItem(board);+ verdictOn(board, landed, 'web-2', 'ACCEPT');+ store.merged(board, landed, { agentId: 'coordinator', commit: SHA_A });const open = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });store.reserveReview(board, built, { agentId: 'web-2', leaseMs: 3_600_000, policy: 'any' });const judge = (id, agentId, fields) =>- outcome(() => store.verify(board, id, { agentId, decision, head: SHA_A, digest: 'wrong', policy: 'coordinator', note: '', ...fields }));+ outcome(() => store.verify(board, id, { agentId, decision, head: SHA_A, digest: 'wrong', policy: 'coordinator', note: '', review: { commit: SHA_A, trunk: SHA_B, paths: ['web/page.js'] }, ...fields }));const bad = verb === 'accept' ? 'TEST_FAILURE' : 'NOPE';const good = verb === 'accept' ? undefined : 'TEST_FAILURE';const fired = [judge(999, 'web-2', { reason: bad }),judge(open, 'web-2', { reason: bad }),+ judge(landed, 'web-2', { reason: bad }),+ judge(built, 'web-2', { reason: bad, review: null }),judge(built, 'web-1', { reason: bad }),judge(built, light, { reason: bad }),judge(built, 'web-2', { reason: bad }),@@ -1217,7 +1222,7 @@ test('the review lease is reviewLease in pullboard.json, 30 minutes unless the rtest('the lifecycle page and the help show the reservation: reserve, and reviewFree on every verdict [V15, M1]', () => {const page = lifecycleMarkdown();assert.match(page, /^\| reserve \| submitted \| submitted \| agent, coordinator \| .*reviewFree \(REVIEW_HELD\) \|$/m);- for (const verb of ['accept', 'reject']) assert.match(page, new RegExp(`^\\| ${verb} \\| submitted \\| .*policyAllows \\(COORDINATOR_VERIFIES\\), familyAllows \\(O2_FAMILY_MATCH\\), reviewFree \\(REVIEW_HELD\\), criterionUnchanged`, 'm'));+ for (const verb of ['accept', 'reject']) assert.match(page, new RegExp(`^\\| ${verb} \\| submitted, verified \\| .*policyAllows \\(COORDINATOR_VERIFIES\\), familyAllows \\(O2_FAMILY_MATCH\\), reviewFree \\(REVIEW_HELD\\), criterionUnchanged`, 'm'));assert.match(page, /^\| REVIEW_HELD \| no other agent holds its review under a live lease \| pullboard next --verify/m);assert.match(HELP.all, /^ {2}agent +claim, release, submit, reserve, accept, reject, escalate, refreeze \(when a live claim has a pending coordinator correction\)$/m);assert.match(HELP.all, /pullboard next --verify +reserve the next submitted item you can check/);diff --git a/test/pending-refreeze.test.js b/test/pending-refreeze.test.jsindex 15ad01aa..99dc9c84 100644--- a/test/pending-refreeze.test.js+++ b/test/pending-refreeze.test.js@@ -243,16 +243,16 @@ async function checkDependencyLegacyClients(cleanup, directory, snapshot, targetconst oldFeature = legacyEngine.applyRelayMove(old, engine10Move, engine10Receipt);const currentFeature = applyRelayMove(current, engine10Move, engine10Receipt);assert.equal(oldFeature.error, undefined, JSON.stringify(oldFeature));- assert.deepEqual(currentFeature, oldFeature, 'engine 12 reproduces engine 10 dependency additions and clears');+ assert.deepEqual(currentFeature, oldFeature, 'the current writer reproduces engine 10 dependency additions and clears');assert.deepEqual(store.getItem(current, target), legacyStore.getItem(old, target));- assert.deepEqual(store.events(current), legacyStore.events(old), 'engine 10 and engine 12 replay identical events');+ assert.deepEqual(store.events(current), legacyStore.events(old), 'engine 10 and the current writer replay identical events');assert.equal(appliedSequence(current), legacyEngine.appliedSequence(old));assert.deepEqual(engineReceipt(current, engine10Move.id), legacyEngine.engineReceipt(old, engine10Move.id),- 'engine 10 and engine 12 retain the same dependency-move receipts');+ 'engine 10 and the current writer retain the same dependency-move receipts');const oldSnapshot = legacyExchange.exportBoard(old);const currentSnapshot = exportBoard(current);assert.equal(oldSnapshot.tables.board_meta.find((row) => row.meta_key === 'relay_engine_version').meta_value, '10');- assert.equal(currentSnapshot.tables.board_meta.find((row) => row.meta_key === 'relay_engine_version').meta_value, '12');+ assert.equal(currentSnapshot.tables.board_meta.find((row) => row.meta_key === 'relay_engine_version').meta_value, String(ENGINE_VERSION));assert.deepEqual(withoutEngineMarker(currentSnapshot), withoutEngineMarker(oldSnapshot),'the sole snapshot difference is the intentionally newer writer-version marker');}@@ -261,7 +261,7 @@ async function checkDependencyLegacyClients(cleanup, directory, snapshot, target}test('dependency edits replay the same on every engine [B3,V2,H16]', async (t) => {- assert.equal(ENGINE_VERSION, 12);+ assert.ok(ENGINE_VERSION > 12);const directory = mkdtempSync(join(tmpdir(), 'pullboard-dependency-engines-'));const cleanup = [];t.after(() => {diff --git a/test/row-decisions-replay.test.js b/test/row-decisions-replay.test.jsindex 8f048ccf..d1f2e58a 100644--- a/test/row-decisions-replay.test.js+++ b/test/row-decisions-replay.test.js@@ -144,7 +144,7 @@ test('captured person decisions and coordinator apply replay identically without});test('engine 12 records preserved decline text and replays a separate reason [S18,S19,H16]', (t) => {- assert.equal(ENGINE_VERSION, 12);+ assert.ok(ENGINE_VERSION >= 12);const { source, copies: [one, two] } = decisionCopies(t);const preserved = {kind: 'spec', file: 'SPEC.md', id: 'G2',@@ -161,10 +161,10 @@ test('engine 12 records preserved decline text and replays a separate reason [S1agentId: 'person', channel: 'view', decisions: [legacy],}), { code: 'ROW_DECISION' }, 'engine 12 refuses a new legacy-shaped decline');- const move = prepareEngineMove(one, 'recordRowDecisions', [{+ const move = { ...prepareEngineMove(one, 'recordRowDecisions', [{agentId: 'person', channel: 'view', decisions: [preserved],- }], { id: 'engine-12-preserved-decline' });- assert.equal(move.engine, ENGINE_VERSION);+ }], { id: 'engine-12-preserved-decline' }), engine: 12 };+ assert.equal(move.engine, 12);const first = applyEngineMove(one, move, { sequence: 1, at: RECORDED_AT });const second = applyEngineMove(two, move, { sequence: 1, at: RECORDED_AT });assert.deepEqual(first, second);diff --git a/test/team-engine.test.js b/test/team-engine.test.jsnew file mode 100644index 00000000..5856d5c3--- /dev/null+++ b/test/team-engine.test.js@@ -0,0 +1,120 @@+/** Sealed re-reviews bind the original work without changing released receipts [E8,H16,V8]. */+import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';+import { test } from 'node:test';+import * as store from '../src/board.js';+import { exportBoard, importBoard } from '../src/exchange.js';+import { applyEngineMove, appliedSequence, engineReceipt, prepareEngineMove } from '../src/engine.js';+import { VERDICT_REVIEW_ENGINE } from '../src/machine.js';+import { unpackRelease } from './release-archive.js';++const BASE = 'a'.repeat(40);+const COMMIT = 'b'.repeat(40);+const TRUNK = 'c'.repeat(40);+const DIGEST = 'd'.repeat(64);+const AT = '2026-10-16T00:00:00.000Z';++/** Build a submitted, registered board entirely through public engine/store operations. */+function submitted(t) {+ const board = store.openBoard(':memory:', { now: () => new Date(AT) });+ t.after(() => store.closeBoard(board));+ store.register(board, { lane: 'coordinator', path: '/fixture' });+ store.register(board, { lane: 'web', path: '/fixture/web-1' });+ store.register(board, { lane: 'web', path: '/fixture/web-2' });+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Sealed review fixture' });+ store.claim(board, id, { agentId: 'web-1', lane: 'web', leaseMs: 3_600_000, head: BASE,+ freeze: () => ({ text: JSON.stringify({ rows: [], policy: { version: 1, commit: BASE, verify: { policy: 'any', family: 'off' } } }), digest: DIGEST }) });+ store.submit(board, id, { agentId: 'web-1', commit: COMMIT, tree: TRUNK, files: ['web/feature.js'], policyCommit: BASE });+ return board;+}++/** Produce one independent replica through the public board exchange format. */+function replica(t, seed) {+ const board = store.openBoard(':memory:');+ t.after(() => store.closeBoard(board));+ importBoard(board, exportBoard(seed));+ return board;+}++/** The normal verifier's typed arguments, with optional new review metadata. */+function verdict(review) {+ return { agentId: 'web-2', decision: 'ACCEPT', note: 'The verifier checked the original work with the known trunk.',+ head: COMMIT, digest: DIGEST, policy: 'any', familyPolicy: 'off', check: 'green',+ ...(review === undefined ? {} : { review }) };+}++/** A writer-version marker is intentionally newer; all historical semantic rows must still match. */+function withoutWriterMarker(document) {+ const copy = structuredClone(document);+ copy.tables.board_meta = copy.tables.board_meta.filter(row => row.meta_key !== 'relay_engine_version');+ return copy;+}++test('engine 12 acceptance receipts stay exact and sealed re-review needs a newer engine [E8,H16,V8]', async t => {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-review-engines-'));+ const archived = join(directory, 'engine12');+ mkdirSync(archived);+ unpackRelease('59a6e2b286ee852add0d68a659f1a1e6b3257c44', archived);+ const oldStore = await import(pathToFileURL(join(archived, 'src/board.js')).href);+ const oldEngine = await import(pathToFileURL(join(archived, 'src/engine.js')).href);+ const oldExchange = await import(pathToFileURL(join(archived, 'src/exchange.js')).href);+ const oldMachine = await import(pathToFileURL(join(archived, 'src/machine.js')).href);+ assert.equal(oldMachine.ENGINE_VERSION, 12, 'this is the actual released executable, not a retagged new engine');+ const seed = submitted(t);+ const one = replica(t, seed);+ const two = replica(t, seed);+ const old = oldStore.openBoard(join(directory, 'old.sqlite'));+ t.after(() => { oldStore.closeBoard(old); rmSync(directory, { recursive: true, force: true }); });+ oldExchange.importBoard(old, exportBoard(seed));+ const accept = oldEngine.prepareEngineMove(old, 'verify', [1, verdict()], { id: 'old-engine12-accept' });+ const repeated = oldEngine.prepareEngineMove(old, 'verify', [1, verdict()], { id: 'old-engine12-repeated-accept' });+ for (const [index, move] of [accept, repeated].entries()) {+ const order = { sequence: index + 1, at: `2026-10-16T00:00:0${index + 1}.000Z` };+ const original = oldEngine.applyEngineMove(old, move, order);+ assert.equal(original.error?.code, index === 0 ? undefined : 'NOT_SUBMITTED');+ for (const board of [one, two]) {+ assert.deepEqual(applyEngineMove(board, move, order), original);+ assert.deepEqual(engineReceipt(board, move.id), oldEngine.engineReceipt(old, move.id));+ assert.deepEqual(withoutWriterMarker(exportBoard(board)), withoutWriterMarker(oldExchange.exportBoard(old)));+ }+ }+ const originalVerdicts = store.verdictsFor(one, 1);+ const reReview = { ...prepareEngineMove(one, 'verify', [1, verdict({ commit: COMMIT, trunk: TRUNK, paths: ['web/feature.js'] })], { id: 'sealed-new-review' }), engine: VERDICT_REVIEW_ENGINE };+ assert.equal(reReview.engine, 13, 'the feature replays at its introduction version even after a later writer upgrade');+ const oldBefore = oldExchange.exportBoard(old);+ assert.throws(() => oldEngine.applyEngineMove(old, reReview, { sequence: 3, at: AT }), { code: 'ENGINE_VERSION' });+ assert.deepEqual(oldExchange.exportBoard(old), oldBefore, 'an actual old client refuses the future envelope before changing its prefix');+ const before = exportBoard(one);+ assert.throws(() => applyEngineMove(one, { ...reReview, engine: 12 }, { sequence: 3, at: AT }), { code: 'RELAY_MOVE' });+ assert.deepEqual(exportBoard(one), before, 'new metadata cannot acquire old-engine meaning by changing the tag');+ const order = { sequence: 3, at: '2026-10-16T00:00:03.000Z' };+ assert.deepEqual(applyEngineMove(one, reReview, order), applyEngineMove(two, reReview, order));+ assert.equal(appliedSequence(one), 3);+ assert.equal(store.verdictsFor(one, 1).length, 2);+ assert.deepEqual(store.verdictsFor(one, 1).slice(0, 1), originalVerdicts, 'the old proof remains byte-for-byte unchanged');+ assert.deepEqual(exportBoard(one), exportBoard(two));+});++test('malformed sealed reviews cannot append proof or bind a different submission [E8,H16,V8]', t => {+ const one = submitted(t);+ const two = replica(t, one);+ const valid = { commit: COMMIT, trunk: TRUNK, paths: ['web/feature.js'] };+ const invalid = [null, { ...valid, commit: BASE }, { ...valid, trunk: 'not-a-commit' },+ { ...valid, paths: 'web/feature.js' }, { ...valid, paths: ['web/feature.js', 'web/feature.js'] },+ { ...valid, paths: ['web/z.js', 'web/a.js'] }, { ...valid, paths: ['/web/feature.js'] },+ { ...valid, paths: ['web/../feature.js'] }, { ...valid, paths: ['web//feature.js'] },+ { ...valid, unexpected: true }];+ for (const [index, review] of invalid.entries()) {+ const move = prepareEngineMove(one, 'verify', [1, verdict(review)], { id: `invalid-review-${index}` });+ const order = { sequence: index + 1, at: AT };+ const first = applyEngineMove(one, move, order);+ assert.equal(first.error?.code, 'BAD_VERDICT_REVIEW', JSON.stringify(first));+ assert.deepEqual(first, applyEngineMove(two, move, order));+ assert.deepEqual(store.verdictsFor(one, 1), []);+ assert.equal(store.getItem(one, 1).item_status, 'submitted');+ assert.deepEqual(exportBoard(one), exportBoard(two));+ }+});diff --git a/test/team.test.js b/test/team.test.jsnew file mode 100644index 00000000..e583be13--- /dev/null+++ b/test/team.test.js@@ -0,0 +1,224 @@+/** Two independent Git/SQLite replicas derive verdict freshness without rewriting proof [E8]. */+import assert from 'node:assert/strict';+import childProcess from 'node:child_process';+import { syncBuiltinESMExports } from 'node:module';+import { existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { after, test } from 'node:test';+import * as store from '../src/board.js';+import { exportBoard, importBoard } from '../src/exchange.js';+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';+import { createE2eHelpers } from './e2e-helpers.js';+import { serveApi } from '../src/api.js';+import { main } from '../src/cli.js';+import { fetchFresh } from './http-fixture.js';++const helpers = createE2eHelpers();+after(helpers.cleanup);++/** Open a fixture's independent board and always close it after its observation or public move. */+function withBoard(root, action) {+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));+ try { return action(board); }+ finally { store.closeBoard(board); }+}++/** Run a real fixture CLI command, retaining the refusal or successful document verbatim. */+function run(box, root, ...args) {+ const result = box.run(root, ...args);+ assert.equal(result.code, 0, `${args.join(' ')}: ${result.err}${result.out}`);+ return result.out;+}++test('a verdict reads stale when main moves under its files [E8]', { timeout: 120_000 }, async t => { // budget: hang ceiling for two real replicas, CLI checks and Git history; not a speed target.+ const box = helpers.project();+ assert.equal(helpers.commitFile(box, box.repo, 'web/feature.js', 'feature = 0\nmain = 0\n', 'feat(web): baseline [G1]').status, 0);+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');+ const checkedHeads = join(box.dir, 'checked-heads');+ const check = `grep -q '^feature = 1$' web/feature.js && git rev-parse HEAD >> '${checkedHeads}'`;+ run(box, box.repo, 'add', 'web', 'Feature', '--specs', 'G1', '--check', check, '--wait');+ run(box, box.web, 'claim', '1');+ assert.equal(helpers.commitFile(box, box.web, 'web/feature.js', 'feature = 1\nmain = 0\n', 'feat(web): feature [G1]').status, 0);+ const submitted = box.git(box.web, 'rev-parse', 'HEAD');+ run(box, box.web, 'submit', '1');+ const reviewer = join(box.dir, 'web-2');+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', reviewer, submitted);+ run(box, reviewer, 'join', 'web');+ run(box, reviewer, 'verify', '1', 'accept', '--note', 'The feature changes its first line and the frozen check observes it.');+ const original = withBoard(box.repo, board => store.verdictsFor(board, 1));+ const peer = join(box.dir, 'replica');+ box.git(box.dir, 'clone', '-q', box.repo, peer);+ withBoard(peer, board => importBoard(board, withBoard(box.repo, exportBoard)));++ /** Move only the peer's Git trunk; its independently stored acceptance stays unchanged. */+ const syncTrunk = () => {+ box.git(peer, 'fetch', '-q', 'origin', 'main');+ box.git(peer, 'merge', '-q', '--ff-only', 'origin/main');+ };+ /** Read each replica through its actual public CLI, rather than a test-only freshness helper. */+ const items = () => [box.repo, peer].map(root => JSON.parse(run(box, root, 'show', '1', '--json')));+ let streamController;+ let streamReader;+ let builds = 0;+ const api = await serveApi({ runCommand: main, projects: () => [{ root: reviewer, name: 'Verdict fixture' }], onStateBuild: () => { builds += 1; } });+ t.after(async () => {+ streamController?.abort();+ await streamReader?.cancel().catch(() => {});+ await api.close();+ });+ const address = new URL(api.url);+ const headers = { 'x-pullboard-key': address.searchParams.get('k') };+ const apiPath = '/api/v1/boards/' + withBoard(box.repo, store.boardId);+ /** Read one authenticated public HTTP endpoint on the persistent worktree-backed server. */+ const http = async suffix => {+ const response = await fetchFresh(address.origin + apiPath + suffix, { headers });+ const document = await response.json();+ assert.equal(response.status, 200, JSON.stringify(document));+ return document;+ };+ const initialState = (await http('/state')).state;+ await http('/state');+ assert.equal(builds, 1, 'unchanged HTTP reads reuse the state cache');+ await http('/items/1'); // Warm the independent detail freshness projection for a verified item.+ const processMethods = ['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync'];+ const originals = new Map(processMethods.map(method => [method, childProcess[method]]));+ const processCalls = [];+ try {+ for (const method of processMethods) childProcess[method] = function (...args) {+ processCalls.push({ method, command: args[0] });+ return Reflect.apply(originals.get(method), this, args);+ };+ syncBuiltinESMExports();+ await http('/items/1');+ await http('/state');+ await http('/items/1');+ assert.deepEqual(processCalls, [], 'unchanged accepted-item detail and state reads spawn no process');+ } finally {+ for (const [method, original] of originals) childProcess[method] = original;+ syncBuiltinESMExports();+ }++ assert.ok(items().every(item => !item.item_verdict_state));+ assert.equal(helpers.commitFile(box, box.repo, 'web/unrelated.js', 'unrelated = 1\n', 'feat(web): unrelated [G1]').status, 0);+ syncTrunk();+ assert.ok(items().every(item => !item.item_verdict_state), 'unrelated main files do not stale acceptance');+ assert.equal((await http('/state')).state.items[0].verdictState, undefined);+ const beforeMoveHead = box.git(reviewer, 'rev-parse', 'HEAD');+ streamController = new AbortController();+ const stream = await fetchFresh(address.origin + apiPath + '/events?after=' + initialState.sequence, {+ headers: { ...headers, accept: 'text/event-stream' }, signal: streamController.signal,+ });+ assert.equal(stream.status, 200);+ streamReader = stream.body.getReader();+ assert.equal(helpers.commitFile(box, box.repo, 'web/feature.js', 'feature = 0\nmain = 1\n', 'feat(web): change main caller [G1]').status, 0);+ const movingCommit = box.git(box.repo, 'rev-parse', 'HEAD');+ syncTrunk();+ for (const item of items()) {+ assert.equal(item.item_verdict_state?.code, 'STALE_VERDICT');+ assert.equal(item.item_verdict_state.file, 'web/feature.js');+ assert.equal(item.item_verdict_state.commit, movingCommit);+ assert.equal(item.item_verdict, 'ACCEPT', 'the historical acceptance remains a fact');+ }+ assert.equal(box.git(reviewer, 'rev-parse', 'HEAD'), beforeMoveHead, 'the served worktree HEAD stayed fixed while main moved');+ const apiStale = (await http('/state')).state;+ assert.equal(apiStale.sequence, initialState.sequence, 'Git movement needs no board event to invalidate the state cache');+ assert.equal(apiStale.items[0].verdictState?.code, 'STALE_VERDICT');+ assert.equal(apiStale.items[0].verdictState.commit, movingCommit);+ assert.equal((await http('/items/1')).item.verdictState?.commit, movingCommit);+ const streamDeadline = setTimeout(() => streamController.abort(new Error('trunk movement produced no live changed event')), 5_000); // budget: hang ceiling for a fixture-local change notification; no throughput claim.+ try {+ let buffered = '';+ while (!/event: changed\n/u.test(buffered)) {+ const { value, done } = await streamReader.read();+ assert.equal(done, false, 'the live stream stays open through the trunk change');+ buffered += new TextDecoder().decode(value);+ }+ } finally { clearTimeout(streamDeadline); }+ streamController.abort();+ await streamReader.cancel().catch(() => {});+ for (const root of [box.repo, peer]) {+ assert.match(run(box, root, 'show', '1'), /STALE_VERDICT/u);+ assert.equal(JSON.parse(run(box, root, 'list', '--all', '--json')).items[0].item_verdict_state?.commit, movingCommit);+ const resume = JSON.parse(run(box, root, 'resume', '--json'));+ assert.equal(resume.all[0].item_verdict_state?.commit, movingCommit);+ assert.deepEqual(resume.toMerge, [], 'resume never suggests landing a stale acceptance');+ assert.equal(resume.staleVerdicts[0].item_id, 1);+ assert.deepEqual(withBoard(root, board => store.verdictsFor(board, 1)), original, 'read projection cannot rewrite original proof');+ const refused = box.run(root, 'land', '--dry-run', '--json');+ assert.equal(refused.code, 1, refused.out + refused.err);+ const error = JSON.parse(refused.out).error;+ assert.equal(error.code, 'STALE_VERDICT');+ assert.ok(error.message.includes('web/feature.js') && error.message.includes(movingCommit), error.message);+ }+ box.git(box.repo, 'revert', '--no-edit', movingCommit);+ syncTrunk();+ assert.ok(items().every(item => item.item_verdict_state?.commit === movingCommit), 'a revert cannot turn an old review into a new review');+ const priorChecks = readFileSync(checkedHeads, 'utf8');+ const oldHead = box.run(reviewer, 'verify', '1', 'accept', '--note', 'Trying the old candidate is insufficient.');+ assert.equal(oldHead.code, 1);+ assert.equal(readFileSync(checkedHeads, 'utf8'), priorChecks, 'old candidate is refused before running its check');+ box.git(reviewer, 'merge', '-q', '--no-edit', 'main');+ const composed = box.git(reviewer, 'rev-parse', 'HEAD');+ assert.notEqual(composed, submitted);+ run(box, reviewer, 'verify', '1', 'accept', '--note', 'Re-reviewed the feature with the latest main caller and its reverted history.');+ assert.equal(readFileSync(checkedHeads, 'utf8').trim().split('\n').at(-1), composed, 'the frozen check ran on the reviewed composition');+ const reviewed = withBoard(box.repo, board => store.verdictsFor(board, 1));+ assert.deepEqual(reviewed.slice(0, original.length), original);+ assert.equal(reviewed.length, original.length + 1, 're-review appends independent proof');+ const verdict = reviewed.at(-1);+ const outcome = withBoard(peer, board => {+ const move = prepareEngineMove(board, 'verify', [1, {+ agentId: verdict.verdict_by, decision: 'ACCEPT', note: verdict.verdict_note,+ head: verdict.verdict_head, digest: verdict.verdict_digest, policy: 'any',+ check: verdict.check, review: verdict.review,+ }]);+ return applyEngineMove(board, move, { sequence: 1, at: verdict.verdict_at });+ });+ assert.equal(outcome.error, undefined, JSON.stringify(outcome));+ assert.ok(items().every(item => !item.item_verdict_state), 'the same sealed re-review clears both replicas');+ assert.equal((await http('/state')).state.items[0].verdictState, undefined, 'a newer acceptance invalidates stale cached state');+ assert.equal((await http('/items/1')).item.verdictState, undefined);+ assert.deepEqual(withBoard(peer, board => store.verdictsFor(board, 1)), reviewed);+ box.git(box.repo, 'merge', '-q', '--no-edit', composed);+ syncTrunk();+ const landed = box.git(box.repo, 'rev-parse', 'HEAD');+ for (const root of [box.repo, peer]) withBoard(root, board => store.merged(board, 1, { agentId: 'coordinator', commit: landed }));+ assert.equal(helpers.commitFile(box, box.repo, 'web/feature.js', 'feature = 1\nmain = 2\n', 'feat(web): after landing [G1]').status, 0);+ syncTrunk();+ assert.ok(items().every(item => !item.item_verdict_state), 'landed items are not waiting for re-review');+ assert.ok(existsSync(join(peer, '.git', 'pullboard', 'board.sqlite')));+});+++test('a checkout or trunk moving during verification cannot acquire proof [E8]', () => {+ const box = helpers.project();+ const reviewer = join(box.dir, 'moving-reviewer');+ const moveHead = join(box.dir, 'move-review-head');+ const moveMain = join(box.dir, 'move-review-main');+ const baseline = box.git(box.repo, 'rev-parse', 'main');+ const check = `grep -q '^feature = 1$' web/feature.js && if test -f '${moveHead}'; then git -C '${reviewer}' checkout -q --detach '${baseline}'; fi && if test -f '${moveMain}'; then git -C '${box.repo}' commit -q --allow-empty -m 'chore: move review trunk [G1]'; fi`;+ run(box, box.repo, 'add', 'web', 'Moving review', '--specs', 'G1', '--check', check, '--wait');+ run(box, box.web, 'claim', '1');+ assert.equal(helpers.commitFile(box, box.web, 'web/feature.js', 'feature = 1\n', 'feat(web): moving review feature [G1]').status, 0);+ const submitted = box.git(box.web, 'rev-parse', 'HEAD');+ run(box, box.web, 'submit', '1');+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', reviewer, submitted);+ run(box, reviewer, 'join', 'web');+ writeFileSync(moveHead, 'armed');+ const moved = box.run(reviewer, 'verify', '1', 'accept', '--note', 'The check moved the live reviewer checkout.');+ assert.equal(moved.code, 1, moved.out + moved.err);+ assert.match(moved.err, /NOT_AT_COMMIT/u);+ assert.equal(box.git(reviewer, 'rev-parse', 'HEAD'), baseline, 'the actual checkout moved while its private check was running');+ assert.deepEqual(withBoard(box.repo, board => store.verdictsFor(board, 1)), []);+ rmSync(moveHead);+ box.git(reviewer, 'checkout', '-q', '--detach', submitted);+ writeFileSync(moveMain, 'armed');+ const mainMoved = box.run(reviewer, 'verify', '1', 'accept', '--note', 'The check moved the known main.');+ assert.equal(mainMoved.code, 1, mainMoved.out + mainMoved.err);+ assert.match(mainMoved.err, /VERDICT_TRUNK_MOVED/u);+ assert.notEqual(box.git(box.repo, 'rev-parse', 'main'), baseline);+ assert.deepEqual(withBoard(box.repo, board => store.verdictsFor(board, 1)), []);+ rmSync(moveMain);+ run(box, reviewer, 'verify', '1', 'accept', '--note', 'The candidate and known trunk stayed fixed through the complete frozen check.');+ assert.equal(withBoard(box.repo, board => store.verdictsFor(board, 1)).length, 1);+});