Skip to content

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

feat(claim): reserve reopened work for its builder [B13,B5]

Corey Olsoncd7db2f574f1
diff --git a/docs/api.md b/docs/api.md
index 58583429..148a449a 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -191,6 +191,8 @@ With `submitGate: "landing"`, `status.submitInvariantProposals` lists files that
Releasing a reserved review requires a nonempty one-line `--note` (or `--note-file`); the authenticated release action accepts the same `note` field. A refusal keeps the reservation and records no release. The same reviewer is not offered that submission again until it is resubmitted or an hour passes, while other reviewers remain eligible. Releasing a build claim keeps its existing behavior and does not require a reason.
+`claim.reopenFirstRefusalMinutes` in `pullboard.json` is a non-negative whole number of minutes, default `0` (off). With a positive value, rejection, a failed landing or a trunk conflict gives the original builder first refusal until the recorded UTC deadline. Another seat receives `REOPEN_HELD_FOR_BUILDER` with the builder and deadline; `next` skips that reserved work for other seats. The builder receives one persisted notice when the item returns. At the deadline anyone may claim. Before it, the builder may yield with `pullboard release <id>` directly from the open state, or release after reclaiming. Other seats and review releases cannot cancel that reservation. Ordinary lane, route, dependency and one-live-claim rules still apply. Without the setting, reopened claims and releases keep their existing behavior. The window is recorded in the return event so linked replicas use the same builder and deadline.
+
With `verify.unrelatedTrunkMoves: true` in `pullboard.json` (off by default), an accept whose review saw main move is still recorded when every moved commit changes none of the item's files and none of the files its check and affected tests read; the verdict note names those commits. Any other move, or a check that is not an explicit test selection, refuses `VERDICT_TRUNK_MOVED` as before, naming the file that reaches the review.
When outstanding reviews reach `verify.reviewRatio` times the active reviewers (default 3, with zero reviewers counting as one), `next` first offers a review the agent may take. This creates no claim or reservation. Its additive v1 `offer` has the review's `item` id, exact `command` to reserve it, `queue` and `ratio`; `build` previews the otherwise available build or is `null`. `next --verify <id>` reserves explicitly. `next --build` claims explicitly; a fresh claim's event detail records `reviewSkipped` with the offered id (or `null`), ratio and queue snapshot. Renewing an existing claim creates no new skip.
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index af1e0b1e..f95d4527 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -15,6 +15,7 @@ stateDiagram-v2
[*] --> open
open --> claimed: claim
claimed --> claimed: claim
+ open --> open: release
claimed --> open: release
claimed --> open: lapse (clock)
claimed --> submitted: submit
@@ -53,14 +54,14 @@ Each move checks its guards in this order and refuses with the first one that do
| Move | From | To | Who | Guards, in order; result refusals |
| --- | --- | --- | --- | --- |
-| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |
-| release | claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) |
+| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), builderFirstRefusal (REOPEN_HELD_FOR_BUILDER), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |
+| release | open, claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), releaseOwnsWork (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) |
| lapse | claimed | open | clock, when its lease runs out | none |
| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), 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), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |
| reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), roadmapReadable (MILESTONES_CORRUPT), itemExists (NO_ITEM), inState (NOT_SUBMITTED), reviewCooldownElapsed (REVIEW_COOLDOWN), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD) |
| accept | submitted, verified | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), 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 or VERIFIER_STANDING or SELF_SESSION_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), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), itemCheckGreen (CHECK_RED or CHECK_UNVERIFIED or GUARD_CANNOT_FAIL or GUARD_NOT_FOUND), proofNoted (PROOF_REQUIRED), result (LAND_HEADER), result (ENGINE_VERSION) |
| reject | submitted, verified | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), 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 or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), result (LAND_HEADER), result (ENGINE_VERSION), result (NOT_YOURS), result (CLOSED) |
-| reopen | submitted, verified | open | coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_REQUIRED), trunkConflicts (NOT_CONFLICTING or CONFLICT_FILES or NO_TRUNK or MERGE_CHECK_FAILED), conflictAccepted (NOT_ACCEPTED or BAD_CONFLICT or ENGINE_VERSION) |
+| reopen | submitted, verified | open | coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_REQUIRED), trunkConflicts (NOT_CONFLICTING or CONFLICT_FILES or NO_TRUNK or MERGE_CHECK_FAILED), conflictAccepted (NOT_ACCEPTED or BAD_CONFLICT or ENGINE_VERSION), result (BAD_CONFIG) |
| escalate | open, claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), 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 or SESSION_LEDGER), 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) |
| refreeze | claimed | claimed | agent, coordinator, when a live claim has a pending coordinator correction | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |
@@ -78,7 +79,7 @@ Each move checks its guards in this order and refuses with the first one that do
| Code | Raised when this does not hold | Next step |
| --- | --- | --- |
| NOT_CLAIMABLE | claim: the item is in open, claimed | pullboard show <id> |
-| NOT_YOURS | release: the item is in claimed | pullboard show <id> |
+| NOT_YOURS | release: the item is in open, 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, verified | pullboard show <id> |
@@ -95,10 +96,12 @@ Each move checks its guards in this order and refuses with the first one that do
| MILESTONES_CORRUPT | the roadmap is 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 |
| MAIN_IS_COORDINATOR | in the main checkout, the caller says it is the coordinator | verify from your own worktree; the coordinator adds --as coordinator |
| NOT_YOURS | the caller holds the item, or is the coordinator | shout its holder, or the coordinator |
+| NOT_YOURS | the caller holds the claim or is the builder yielding its active first-refusal window | release your own claim or reservation, or ask the current builder |
| NOT_YOURS | the caller holds the claim | pullboard claim <id> |
| WRONG_LANE | the item is in the caller's lane; the main checkout builds coordinator-lane items only | cd <the lane's worktree> && pullboard claim <id> |
| ROUTE | the caller's route covers the item's: light, then mid, then strong | pullboard next, which offers only items your route covers |
| BLOCKED | every item it waits on is verified | claim another item, or shout the lane it waits on |
+| REOPEN_HELD_FOR_BUILDER | a returned item waits for its original builder until its recorded deadline or builder release | wait until the named deadline, or ask its builder to run pullboard release <id> |
| HELD | no other agent holds it under a live lease | pullboard next |
| LANE_HELD | nobody holds its lane, unless the caller is renewing its own live claim | pullboard next --wait 9 (minutes) |
| ITEM_HELD | the coordinator has not put this item on hold, unless the caller is renewing its own live claim | the coordinator lifts it with pullboard hold <id> --off |
@@ -181,6 +184,7 @@ Each move checks its guards in this order and refuses with the first one that do
| ENGINE_VERSION | a verdict that implies items replays only under engine 20 or later (reject result) | upgrade Pullboard on every linked device before using --implies |
| NOT_YOURS | the automatic escalation is authorized as the coordinator or item holder (reject result) | ask the coordinator to inspect the item and its route |
| CLOSED | the rejected item remains open or claimed when automatic escalation starts (reject result) | pullboard show <id>, then ask the coordinator to inspect its current state |
+| BAD_CONFIG | the configured first-refusal duration fits a valid UTC deadline (reopen result) | set claim.reopenFirstRefusalMinutes to a non-negative whole number within the supported date range, or 0 to disable |
| BAD_DECISION | a verdict is accept or reject | pullboard verify <id> accept, or reject --reason CODE --note "..." |
For check diagnostics, a refusal from a failed or unverifiable check includes an output digest, sanitized tail, and a private full-output path in the CLI message (also `error.message` in JSON). The artifact is owner-readable only. If it cannot be saved, the tail remains available and the message names the storage error instead of claiming a path.
diff --git a/src/board.js b/src/board.js
index 31a46e2b..9a5c4082 100644
--- a/src/board.js
+++ b/src/board.js
@@ -29,8 +29,10 @@ import {
briefSections,
} from './brief.js';
import { COORDINATOR } from './config.js';
+import { manualLandingFailure, firstRefusal, firstRefusalProblem, firstRefusalReason, firstRefusalDetail, tellFirstRefusal } from './claims.js';
import {
ENGINE_VERSION,
+ REOPEN_FIRST_REFUSAL_ENGINE,
VERDICT_REVIEW_ENGINE,
MILESTONE_RANK_ENGINE,
GUARDS,
@@ -1135,6 +1137,7 @@ export function claim(board, id, { agentId, lane, leaseMs, freeze, head = null,
return null;
},
notHeldByAnother: (found) => (isHeld(board, found) && found.item_owner !== agentId ? new Refused('HELD', `item #${id} is held by ${found.item_owner} until ${found.item_lease_until}`) : null),
+ builderFirstRefusal: () => (board.executionEngineVersion ?? ENGINE_VERSION) >= REOPEN_FIRST_REFUSAL_ENGINE ? firstRefusalProblem(board, id, agentId) : null,
correctionRefrozen: () => pendingRefreezeProblem(board, id),
laneOpen: (found) => {
// Declared: not checked when the caller renews its own live claim.
@@ -1216,11 +1219,13 @@ export function release(board, id, agentId, note = '') {
else logEvent(board, agentId, 'release', id);
return true;
}
+ const window = (board.executionEngineVersion ?? ENGINE_VERSION) >= REOPEN_FIRST_REFUSAL_ENGINE ? firstRefusal(board, id) : null;
moveItem(board, id, 'release', {
+ transition: (board.executionEngineVersion ?? ENGINE_VERSION) < REOPEN_FIRST_REFUSAL_ENGINE ? { ...MOVES.find(move => move.verb === 'release'), from: ['claimed'] } : null,
checks: {
joined: null,
[IN_STATE]: () => new Refused('NOT_YOURS', `item #${id} is not claimed by you`),
- isHolder: (found) => (found.item_owner === agentId ? null : new Refused('NOT_YOURS', `item #${id} is not claimed by you`)),
+ releaseOwnsWork: (found) => (found.item_owner === agentId || found.item_status === 'open' && window?.builder === agentId ? null : new Refused('NOT_YOURS', `item #${id} is not claimed by you`)),
reviewReleaseExplained: null, // Claimed releases do not free a submitted review.
},
set: () => ({ item_owner: null, item_lease_until: null }),
@@ -1551,7 +1556,7 @@ function reserveWithin(board, id, { agentId, leaseMs, policy, familyPolicy = 'of
* @param {{ agentId: string, decision: string, reason?: string, note?: string, cause?: string, head: string, digest: string, policy: string, familyPolicy?: string, check?: 'none' | 'green', review?: {commit: string, head?: string, trunk: string, paths: string[]}, implies?: number[], impliesId?: string }} verdict - implies: items this verdict changes (B29)
* @returns {{ decision: string, reason: string, check?: 'none' | 'green' }}
*/
-export function verify(board, id, { agentId, decision, reason, note = '', cause, head, digest, policy, familyPolicy = 'off', check, review, implies, impliesId }) {
+export function verify(board, id, { agentId, decision, reason, note = '', cause, head, digest, policy, familyPolicy = 'off', check, review, implies, impliesId, reopenFirstRefusalMinutes }) {
const verb = { ACCEPT: 'accept', REJECT: 'reject' }[decision];
if (!verb) throw new Refused('BAD_DECISION', 'the decision is accept or reject');
const isAccept = verb === 'accept';
@@ -1603,11 +1608,13 @@ export function verify(board, id, { agentId, decision, reason, note = '', cause,
},
set: (found) => ({ item_verdict: decision, item_verified_by: isAccept ? agentId : null, item_owner: isAccept ? found.item_owner : null }),
});
- const detail = { reason: code, commit: item.item_commit, ...(!isAccept && cause !== undefined && cause !== null ? { cause } : {}) };
+ const reservation = !isAccept && engine >= REOPEN_FIRST_REFUSAL_ENGINE ? firstRefusalDetail(board, item, reopenFirstRefusalMinutes) : {};
+ const detail = { ...reservation, reason: code, commit: item.item_commit, ...(!isAccept && cause !== undefined && cause !== null ? { cause } : {}) };
if (isAccept && check !== undefined) detail.check = check;
if (newReview) detail.review = { commit: review.commit, ...(Object.hasOwn(review, 'head') ? { head: review.head } : {}), trunk: review.trunk, paths: [...review.paths] };
logEvent(board, agentId, verb, id, implies?.length ? { ...detail, implies } : detail);
const trigger = board.lastEvent;
+ tellFirstRefusal(board, item, reservation, persistShout);
if (!isAccept) recordRejectedItemRoute(board, id, engine, item, { escalate, shout, logEvent });
tellVerdictImplications(board, (by, itemId, fact) => logEvent(board, by, 'fact', itemId, fact), id, { seed: impliesId, implies });
if (!isAccept) postRigorNotices(board, trigger);
@@ -1623,7 +1630,7 @@ export function verify(board, id, { agentId, decision, reason, note = '', cause,
* @param {{ agentId: string, note: string, cause?: string }} request
* @returns {{ id: number, commit: string, supersedes?: number, landingFailure?: object }}
*/
-export function reopen(board, id, { agentId, note = '', conflict, cause }) {
+export function reopen(board, id, { agentId, note = '', conflict, cause, reopenFirstRefusalMinutes }) {
return atomic(board, () => {
let submittedCommit = null;
const forMerge = conflict !== undefined && conflict !== null;
@@ -1679,32 +1686,18 @@ export function reopen(board, id, { agentId, note = '', conflict, cause }) {
};
},
});
+ const reservation = (forMerge || landingFailure) && currentEngine >= REOPEN_FIRST_REFUSAL_ENGINE ? firstRefusalDetail(board, item, reopenFirstRefusalMinutes) : {};
const returned = forMerge ? { supersedes, ...conflictDetail(conflict) } : supersedes ? { supersedes, landingFailure } : {};
- logEvent(board, agentId, 'reopen', id, { commit: submittedCommit, note: note.trim() || conflictNote(conflict), judgment: null,
+ logEvent(board, agentId, 'reopen', id, { commit: submittedCommit, note: note.trim() || conflictNote(conflict), judgment: null, ...reservation,
...(cause !== undefined && cause !== null ? { cause } : {}), ...returned });
- if (forMerge && supersedes === undefined && item.item_built_by) persistShout(board, { from: agentId, to: item.item_built_by, text: returnedHeadNotice(id, submittedCommit, conflict) });
- postRigorNotices(board, board.lastEvent);
+ const trigger = board.lastEvent;
+ tellFirstRefusal(board, item, reservation, persistShout);
+ if (!reservation.reopenFirstRefusal && forMerge && supersedes === undefined && item.item_built_by) persistShout(board, { from: agentId, to: item.item_built_by, text: returnedHeadNotice(id, submittedCommit, conflict) });
+ postRigorNotices(board, trigger);
return { id: item.item_id, commit: submittedCommit, ...returned };
});
}
-/** Read test and merge-commit evidence from a hand-written landing note without checking Git. */
-function manualLandingFailure(note) {
- const generatedPrefix = /^Landing batch [a-z0-9_-]{1,80} failed /iu.exec(note);
- const body = generatedPrefix ? note.slice(generatedPrefix[0].length) : note;
- const evidence = body.match(/;[ \t]*merge commit[ \t]+(?<mergeCommit>[a-f0-9]{40}|[a-f0-9]{64})$/iu);
- if (!evidence) return null;
- const failureText = body.slice(0, evidence.index);
- const firstTest = /(?<file>(?:[\w.-]+\/)*[\w.-]+\.[a-z0-9]+):[ \t]*/iu.exec(failureText);
- if (!firstTest) return null;
- const tests = failureText.slice(firstTest.index).split(/;[ \t]*/u).map((entry) => {
- const test = entry.match(/^(?<file>(?:[\w.-]+\/)*[\w.-]+\.[a-z0-9]+):[ \t]*(?<name>[^;\r\n]+)$/iu);
- if (!test || !test.groups.name.trim()) return null;
- return { file: test.groups.file, name: test.groups.name.trim() };
- });
- if (!tests.length || tests.some((test) => !test)) return null;
- return { tests, mergeCommit: evidence.groups.mergeCommit };
-}
/**
* Refuse unless the acting agent is the coordinator.
@@ -2376,6 +2369,8 @@ export function nextFor(board, { agentId, lane, verify = false, policy = 'any',
const waiting = (entry.item_after ? entry.item_after.split(',').map(Number) : [])
.map((id) => current(board, itemById(board, id)))
.filter((before) => before.item_status !== 'verified');
+ const reserved = firstRefusalReason(board, entry.item_id, agentId);
+ if (reserved) { reasons.push(reserved); continue; }
if (!waiting.length) return { item: entry, reasons, shared };
reasons.push(`#${entry.item_id} waits on ${waiting.map(waitingOn).join(', ')}`);
}
diff --git a/src/claims.js b/src/claims.js
new file mode 100644
index 00000000..05319a31
--- /dev/null
+++ b/src/claims.js
@@ -0,0 +1,76 @@
+/** Durable first-refusal windows for reopened work [B13,B5]. */
+import { Refused } from './refused.js';
+
+/** Read the latest return's window, ignoring review releases and earlier submissions. */
+export function firstRefusal(board, id) {
+ const history = board.db.prepare("SELECT event_kind, event_detail, event_by FROM event WHERE item_id = ? AND event_kind IN ('reject', 'reopen', 'submit', 'release') ORDER BY event_id DESC").all(id);
+ const releases = [];
+ for (const event of history) {
+ const detail = JSON.parse(event.event_detail);
+ if (event.event_kind === 'release') { releases.push(event); continue; }
+ if (event.event_kind === 'submit') return null;
+ const window = detail.reopenFirstRefusal;
+ if (!window || !window.builder || !Number.isFinite(Date.parse(window.until))) return null;
+ if (releases.some(release => release.event_by === window.builder && JSON.parse(release.event_detail).review !== true)) return null;
+ return board.clock.now().getTime() < Date.parse(window.until) ? window : null;
+ }
+ return null;
+}
+
+/** Give the original builder first refusal while preserving every ordinary claim guard. */
+export function firstRefusalProblem(board, id, agentId) {
+ const reason = firstRefusalReason(board, id, agentId);
+ return reason ? new Refused('REOPEN_HELD_FOR_BUILDER', reason) : null;
+}
+
+/** Explain ineligible build work without raising an item refusal from review selection. */
+export function firstRefusalReason(board, id, agentId) {
+ const window = firstRefusal(board, id);
+ return window && window.builder !== agentId
+ ? `item #${id} waits for ${window.builder} until ${window.until}; claim it after that time, or ask its builder to release it`
+ : null;
+}
+
+/** Freeze an enabled reservation into the return event so replicas need no local configuration. */
+export function firstRefusalDetail(board, item, minutes) {
+ if (minutes === undefined || minutes === 0 || !item.item_built_by) return {};
+ const until = board.clock.now().getTime() + minutes * 60_000;
+ if (!Number.isSafeInteger(minutes) || minutes < 0 || !Number.isFinite(until) || Math.abs(until) > 8_640_000_000_000_000) {
+ throw new Refused('BAD_CONFIG', 'claim.reopenFirstRefusalMinutes must be a non-negative whole number within the supported date range; set it to 0 to disable');
+ }
+ return { reopenFirstRefusal: { builder: item.item_built_by, until: new Date(until).toISOString() } };
+}
+
+/** Record one notice in the same transaction as the return and its frozen window. */
+export function tellFirstRefusal(board, item, detail, persistShout) {
+ const window = detail.reopenFirstRefusal;
+ if (window) persistShout(board, { from: 'coordinator', to: window.builder,
+ text: `Item #${item.item_id} waits for you until ${window.until}; claim it to resume, or run pullboard release ${item.item_id} to let another builder take it.` });
+}
+
+/** Copy only enabled coordinator policy into ordered moves before they are sealed for replay. */
+export function firstRefusalArgs(operation, args, config) {
+ const minutes = config.claim?.reopenFirstRefusalMinutes;
+ if (!minutes || !['verify', 'reopen'].includes(operation)) return args;
+ if (operation === 'verify' && args[1]?.decision !== 'REJECT') return args;
+ return [args[0], { ...args[1], reopenFirstRefusalMinutes: minutes }, ...args.slice(2)];
+}
+
+/** Read test and merge-commit evidence from a hand-written landing note without checking Git. */
+export function manualLandingFailure(note) {
+ const generatedPrefix = /^Landing batch [a-z0-9_-]{1,80} failed /iu.exec(note);
+ const body = generatedPrefix ? note.slice(generatedPrefix[0].length) : note;
+ const evidence = body.match(/;[ \t]*merge commit[ \t]+(?<mergeCommit>[a-f0-9]{40}|[a-f0-9]{64})$/iu);
+ if (!evidence) return null;
+ const failureText = body.slice(0, evidence.index);
+ const firstTest = /(?<file>(?:[\w.-]+\/)*[\w.-]+\.[a-z0-9]+):[ \t]*/iu.exec(failureText);
+ if (!firstTest) return null;
+ const tests = failureText.slice(firstTest.index).split(/;[ \t]*/u).map((entry) => {
+ const test = entry.match(/^(?<file>(?:[\w.-]+\/)*[\w.-]+\.[a-z0-9]+):[ \t]*(?<name>[^;\r\n]+)$/iu);
+ if (!test || !test.groups.name.trim()) return null;
+ return { file: test.groups.file, name: test.groups.name.trim() };
+ });
+ if (!tests.length || tests.some((test) => !test)) return null;
+ return { tests, mergeCommit: evidence.groups.mergeCommit };
+}
+
diff --git a/src/cli.js b/src/cli.js
index 0322d407..8b781eeb 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -360,6 +360,7 @@ import {
} from './rigor-conflicts.js';
import { draftConflictSplits } from './rigor-splits.js';
import { nextReview } from './next-review.js';
+import { firstRefusalArgs } from './claims.js';
import { serveApi } from './api.js';
import { watchCommand } from './watch.js';
import { serveMcp } from './mcp.js';
@@ -476,12 +477,10 @@ import {
} from './land.js';
import { installStep } from './worktree.js';
import * as infraNotes from './infra-note.js';
-
export { gateWaitReporter };
const CHECKOUT_LEASES = new WeakMap();
const CHECKOUT_BOARD_ONLY = new WeakMap();
let startupMainTraced = false;
-
/**
* Read the collision baseline from the primary branch, retained trunk, or detached HEAD default.
*
@@ -519,7 +518,6 @@ function coordinatorFile(root, path, revision) {
...(detachedHeadDefault ? { baseline: 'collision baseline default: detached HEAD' } : {}),
};
}
-
/** Find the nearest declared command for a useful typo hint. */
function closestHelpCommand(input) {
const needle = input.toLowerCase();
@@ -974,11 +972,11 @@ async function reserveRow(ctx, row, written) {
return withBoard(ctx, async (board) => ordered(ctx, board, 'draftSpecRow', [{ agentId: store.agentAt(board, ctx.info.root)?.agent_id ?? whoAmI(ctx, board).id, row, written }]));
}
-/** Dispatch a board mutation locally, or seal it before any linked replica applies it. */
/** Note the session behind a claim or submit (#921): its ledger must be writable before the move, and record after it. */
async function withItemSession(info, operation, args, move) { const noted = operation === 'claim' || operation === 'submit'; if (noted) itemSessions.requireLedger(info); const result = await move(); if (noted) itemSessions.recordItemSession(info, args[0], operation); return result; }
async function ordered(ctx, board, operation, args) {
+ if (['verify', 'reopen'].includes(operation)) args = firstRefusalArgs(operation, args, mainPolicy(ctx.info.root).config);
// Every engine-27 registration records the seat that made it: the coordinator from the main
// checkout, the joined agent from its worktree, or `machine` for a join no seat made (#579).
if (operation === 'register' && args[0] && args[0].createdBy === undefined) {
diff --git a/src/config.js b/src/config.js
index 60572f35..d9aabd4a 100644
--- a/src/config.js
+++ b/src/config.js
@@ -52,6 +52,7 @@ export function defaults() {
verify: { policy: 'any', family: 'off', reviewRatio: 3 },
agents: { names: 'suffix' },
check: { install: '', timeout: '5m' },
+ claim: { reopenFirstRefusalMinutes: 0 },
lanes: {},
products: {},
shared: [],
@@ -108,6 +109,10 @@ function merge(base, raw) {
: raw.agents && typeof raw.agents === 'object' && !Array.isArray(raw.agents)
? { ...base.agents, ...raw.agents }
: raw.agents,
+ claim: raw.claim === undefined ? base.claim
+ : raw.claim && typeof raw.claim === 'object' && !Array.isArray(raw.claim)
+ ? { ...base.claim, ...raw.claim }
+ : raw.claim,
check: raw.check === undefined ? base.check
: raw.check && typeof raw.check === 'object' && !Array.isArray(raw.check)
? { ...base.check, ...raw.check }
@@ -204,6 +209,11 @@ export function configProblems(config) {
|| Object.keys(config.checks).some((key) => key !== 'provesNothing') || !['hold', 'warn'].includes(config.checks.provesNothing))) {
problems.push('"checks" is { "provesNothing": "hold" or "warn" }: "hold" refuses claim and submit while an item\'s check already passes on main');
}
+ if (!config.claim || typeof config.claim !== 'object' || Array.isArray(config.claim)
+ || !Number.isSafeInteger(config.claim.reopenFirstRefusalMinutes) || config.claim.reopenFirstRefusalMinutes < 0
+ || config.claim.reopenFirstRefusalMinutes > Math.floor(8_640_000_000_000_000 / 60_000)) {
+ problems.push('"claim.reopenFirstRefusalMinutes" is a non-negative whole number of minutes within the supported date range; 0 disables it');
+ }
if (typeof config.check?.install !== 'string') problems.push('"check.install" is an install command string');
const timeout = typeof config.check?.timeout === 'string' ? CHECK_TIMEOUT_RE.exec(config.check.timeout) : null;
const timeoutMs = timeout ? Number(timeout[1]) * CHECK_TIMEOUT_MS[timeout[2]] : NaN;
diff --git a/src/engine.js b/src/engine.js
index 2f44adab..6ba45b1f 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -22,6 +22,7 @@ import { CHECK_ACCEPT_ENGINE } from './check-accept.js';
import { HEALTH_SENTINEL_ENGINE } from './health-receipts.js';
import { BOARD_SENTINEL_ENGINE } from './sentinels.js';
import {
+ REOPEN_FIRST_REFUSAL_ENGINE,
CAUSE_ENGINE,
ENGINE_VERSION,
VERIFIER_STANDING_ENGINE,
@@ -35,6 +36,7 @@ import {
canonicalMilestoneTarget,
} from './milestones.js';
import { Refused } from './refused.js';
+import { firstRefusal } from './claims.js';
import {
requestMoveProblem,
recordRequestMove,
@@ -73,6 +75,8 @@ const OPERATION_ENGINE = Object.freeze({ draftSpecRow: ROW_DRAFT_ENGINE, orderMi
/** Dependency edits, causes, sealed reviews, submission proofs, trunk conflicts, health observations and milestone targets retain distinct recorded engine meanings. */
function minimumOperationEngine(operation, args, board) {
+ if (['verify', 'reopen'].includes(operation) && args[1]?.reopenFirstRefusalMinutes !== undefined
+ || ['claim', 'release'].includes(operation) && board && firstRefusal(board, args[0])) return REOPEN_FIRST_REFUSAL_ENGINE;
if (operation === 'recordFlakeObservation') return NATIVE_FLAKE_ENGINE;
if (operation === 'recordLandingBatch' && carriesFlakeDiagnostics(args[0]?.batch)) return NATIVE_FLAKE_ENGINE;
if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(operation) || typeof args[1]?.cause === 'string' && args[1].cause.startsWith('sentinel:')) return BOARD_SENTINEL_ENGINE;
diff --git a/src/machine.js b/src/machine.js
index ed199461..243d2850 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -32,7 +32,11 @@ export const STRONG_REJECTION_NOTICE_ENGINE = 54;
*/
export const SUBMITTED_CONFLICT_ENGINE = 60;
+/** First engine reserving opt-in reopened work for its builder (#954, coordinator allocation). */
+export const REOPEN_FIRST_REFUSAL_ENGINE = 66;
+
export const ENGINE_VERSION = Math.max(
+ REOPEN_FIRST_REFUSAL_ENGINE,
HEALTH_CAP_ENGINE,
SUBMITTED_CONFLICT_ENGINE,
NATIVE_FLAKE_ENGINE,
@@ -151,10 +155,12 @@ export const GUARDS = [
{ id: 'roadmapReadable', refuse: 'MILESTONES_CORRUPT', rule: 'the roadmap is 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' },
{ id: 'holderOrCoordinator', refuse: 'NOT_YOURS', rule: 'the caller holds the item, or is the coordinator', next: 'shout its holder, or the coordinator', source: 'board' },
+ { id: 'releaseOwnsWork', refuse: 'NOT_YOURS', rule: 'the caller holds the claim or is the builder yielding its active first-refusal window', next: 'release your own claim or reservation, or ask the current builder', source: 'board' },
{ id: 'isHolder', refuse: 'NOT_YOURS', rule: 'the caller holds the claim', next: 'pullboard claim <id>', source: 'board' },
{ id: 'inLane', refuse: 'WRONG_LANE', rule: "the item is in the caller's lane; the main checkout builds coordinator-lane items only", next: "cd <the lane's worktree> && pullboard claim <id>", source: 'board' },
{ id: 'routeAllows', refuse: 'ROUTE', rule: "the caller's route covers the item's: light, then mid, then strong", next: 'pullboard next, which offers only items your route covers', source: 'board' },
{ id: 'dependenciesVerified', refuse: 'BLOCKED', rule: 'every item it waits on is verified', next: 'claim another item, or shout the lane it waits on', source: 'board' },
+ { id: 'builderFirstRefusal', refuse: 'REOPEN_HELD_FOR_BUILDER', rule: 'a returned item waits for its original builder until its recorded deadline or builder release', next: 'wait until the named deadline, or ask its builder to run pullboard release <id>', source: 'board' },
{ id: 'notHeldByAnother', refuse: 'HELD', rule: 'no other agent holds it under a live lease', next: 'pullboard next', source: 'board' },
{ id: 'laneOpen', refuse: 'LANE_HELD', rule: 'nobody holds its lane', next: 'pullboard next --wait 9 (minutes)', source: 'board', when: 'unless the caller is renewing its own live claim' },
{ id: 'itemNotHeld', refuse: 'ITEM_HELD', rule: 'the coordinator has not put this item on hold', next: 'the coordinator lifts it with pullboard hold <id> --off', source: 'board', when: 'unless the caller is renewing its own live claim' },
@@ -204,12 +210,12 @@ export const GUARDS = [
export const MOVES = [
{
verb: 'claim', from: ['open', 'claimed'], to: 'claimed', by: ['agent', 'coordinator'], refuse: 'NOT_CLAIMABLE',
- guards: ['joined', 'itemExists', IN_STATE, 'checkProvesSomething', 'itemNotHeld', 'inLane', 'routeAllows', 'dependenciesVerified', 'notHeldByAnother', 'correctionRefrozen', 'laneOpen', 'oneLiveClaim', 'rowsInForce'],
+ guards: ['joined', 'itemExists', IN_STATE, 'checkProvesSomething', 'itemNotHeld', 'inLane', 'routeAllows', 'dependenciesVerified', 'notHeldByAnother', 'builderFirstRefusal', 'correctionRefrozen', 'laneOpen', 'oneLiveClaim', 'rowsInForce'],
sets: ['item_owner', 'item_lease_until', 'item_frozen_digest'], command: 'pullboard claim <id>',
},
{
- verb: 'release', from: ['claimed'], to: 'open', by: ['agent', 'coordinator'], refuse: 'NOT_YOURS',
- guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'reviewReleaseExplained'], command: 'pullboard release <id>',
+ verb: 'release', from: ['open', 'claimed'], to: 'open', by: ['agent', 'coordinator'], refuse: 'NOT_YOURS',
+ guards: ['joined', 'itemExists', IN_STATE, 'releaseOwnsWork', 'reviewReleaseExplained'], command: 'pullboard release <id>',
},
{ verb: 'lapse', from: ['claimed'], to: 'open', by: ['clock'], guards: [], when: 'its lease runs out' },
{
@@ -237,6 +243,7 @@ export const MOVES = [
{
verb: 'reopen', from: ['submitted', 'verified'], to: 'open', by: ['coordinator'], refuse: 'NOT_SUBMITTED',
guards: ['joined', 'itemExists', IN_STATE, 'coordinatorOnly', 'noteGiven', 'causeWellFormed', 'notMerged', 'landingFailureRecorded', 'trunkConflicts', 'conflictAccepted'],
+ alsoRefuses: [{ code: 'BAD_CONFIG', rule: 'the configured first-refusal duration fits a valid UTC deadline', next: 'set claim.reopenFirstRefusalMinutes to a non-negative whole number within the supported date range, or 0 to disable' }],
sets: ['item_verdict', 'item_verified_by', 'item_owner', 'item_lease_until', 'item_review_by', 'item_review_until'],
command: 'pullboard reopen <id> --note "why" | --conflict <file> [--conflict <file>]',
},
diff --git a/src/next-steps.js b/src/next-steps.js
index 1cee1c4a..9ae55966 100644
--- a/src/next-steps.js
+++ b/src/next-steps.js
@@ -290,6 +290,7 @@ export const NEXT_STEPS = Object.freeze({
GIT_GRAFTS: 'ask the coordinator to remove the git graft file: pullboard shout coordinator "please remove .git/info/grafts"',
HEAD_NOT_NEW: 'commit the rework, then pullboard submit <id>',
HELD: 'take another item: pullboard next',
+ REOPEN_HELD_FOR_BUILDER: 'wait until the named deadline, or ask the builder to run pullboard release <id>',
HOST_NAME: 'reword the named commit\'s message without this machine\'s name (git rebase -i, then reword), then run pullboard submit <id> again',
HUMAN_REQUIRED: 'send it from the paired phone, or run pullboard relay on --all from the person\'s terminal',
IMPORT_FORMAT: 'make an export with pullboard export > board.json, then import that file',
diff --git a/test/claim-reopen.test.js b/test/claim-reopen.test.js
new file mode 100644
index 00000000..92b07851
--- /dev/null
+++ b/test/claim-reopen.test.js
@@ -0,0 +1,181 @@
+/** @pullboard-test-loads src/board.js src/claims.js src/config.js src/machine.js src/engine.js */
+/** Reopened claims reserve the original builder's context only when enabled [B13,B5]. */
+import assert from 'node:assert/strict';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { submitFixture } from './board-submit-fixture.js';
+import { configFromSource, defaults } from '../src/config.js';
+import { prepareEngineMove, applyEngineMove } from '../src/engine.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+
+const COMMIT = 'a'.repeat(40);
+const TRUNK = 'b'.repeat(40);
+/** Open a real SQLite board with a clock advanced independently of the host. */
+function fixture(t) {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-reopen-'));
+ let at = Date.parse('2026-01-01T00:00:00Z');
+ const board = store.openBoard(join(directory, 'board.sqlite'), { now: () => new Date(at) });
+ t.after(() => { store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); });
+ store.register(board, { lane: 'coordinator', path: '/repo' });
+ const builder = store.register(board, { lane: 'core', path: '/builder', route: 'mid' });
+ const other = store.register(board, { lane: 'core', path: '/other', route: 'mid' });
+ return { board, directory, builder, other, advance: (minutes) => { at += minutes * 60_000; } };
+}
+/** Claim the item with a frozen bar and a bounded lease. */
+function claim(f, id, agentId) {
+ return store.claim(f.board, id, { agentId, lane: 'core', leaseMs: 7_200_000,
+ freeze: () => ({ text: JSON.stringify({ policy: { version: 1, commit: COMMIT, verify: { policy: 'any', family: 'off' } } }), digest: 'digest:bar' }) });
+}
+/** Submit and return an item through the real rejection, landing-failure or conflict path. */
+function returned(f, cause, minutes, causeKey) {
+ const id = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'fix', criterion: 'prove', specIds: ['B13'], route: 'mid', check: 'true', brief: 'Files: src/a.js\nTest: proves the fix' });
+ claim(f, id, f.builder);
+ submitFixture(f.board, id, { agentId: f.builder, commit: COMMIT, tree: COMMIT });
+ const verdict = { agentId: f.other, head: COMMIT, digest: 'digest:bar', policy: 'any', note: 'proof', ...(causeKey ? { cause: causeKey } : {}) };
+ if (cause === 'reject') store.verify(f.board, id, { ...verdict, decision: 'REJECT', reason: 'OTHER', reopenFirstRefusalMinutes: minutes });
+ else {
+ store.verify(f.board, id, { ...verdict, decision: 'ACCEPT' });
+ store.reopen(f.board, id, { agentId: 'coordinator', reopenFirstRefusalMinutes: minutes, ...(causeKey ? { cause: causeKey } : {}),
+ ...(cause === 'conflict' ? { conflict: { files: ['src/a.js'], trunk: TRUNK } }
+ : { note: `test/a.test.js: failed case; merge commit ${TRUNK}` }) });
+ }
+ return id;
+}
+
+test('[B13,B5] a reopened item waits for its builder first', (t) => {
+ for (const cause of ['reject', 'landing', 'conflict']) {
+ const f = fixture(t);
+ const id = returned(f, cause, 30);
+ const notices = store.inbox(f.board, f.builder).filter(row => row.shout_text.includes('waits for you'));
+ assert.equal(notices.length, 1, cause);
+ assert.equal(store.recentShouts(f.board).filter(row => row.shout_to === f.builder && row.shout_text.includes('waits for you')).length, 1);
+ f.advance(5);
+ assert.throws(() => claim(f, id, f.other), error => error.code === 'REOPEN_HELD_FOR_BUILDER'
+ && error.message.includes(f.builder) && error.message.includes('2026-01-01T00:30:00.000Z'), cause);
+ claim(f, id, f.builder);
+ assert.equal(store.getItem(f.board, id).item_owner, f.builder);
+ assert.equal(store.inbox(f.board, f.builder).filter(row => row.shout_text.includes('waits for you')).length, 0);
+ assert.equal(store.recentShouts(f.board).filter(row => row.shout_to === f.builder && row.shout_text.includes('waits for you')).length, 1);
+ f.advance(26);
+ // A fresh return keeps the expiry proof independent of a builder's live lease.
+ const fresh = fixture(t);
+ const expired = returned(fresh, cause, 30);
+ fresh.advance(31);
+ claim(fresh, expired, fresh.other);
+ assert.equal(store.getItem(fresh.board, expired).item_owner, fresh.other);
+ }
+});
+
+
+test('[B13,B5] reopen first refusal is a default-off validated board setting', () => {
+ assert.equal(defaults().claim.reopenFirstRefusalMinutes, 0);
+ assert.equal(configFromSource('{}').claim.reopenFirstRefusalMinutes, 0);
+ assert.equal(configFromSource('{"claim":{}}').claim.reopenFirstRefusalMinutes, 0);
+ assert.equal(configFromSource('{"claim":{"reopenFirstRefusalMinutes":30}}').claim.reopenFirstRefusalMinutes, 30);
+ for (const claim of [null, [], false, { reopenFirstRefusalMinutes: -1 }, { reopenFirstRefusalMinutes: 0.5 },
+ { reopenFirstRefusalMinutes: '30' }, { reopenFirstRefusalMinutes: Number.MAX_SAFE_INTEGER }]) {
+ assert.throws(() => configFromSource(JSON.stringify({ claim })), /claim.reopenFirstRefusalMinutes/);
+ }
+});
+
+test('[B13,B5] first refusal ends on direct builder release, claimed release or exact expiry', (t) => {
+ for (const cause of ['reject', 'landing', 'conflict']) {
+ for (const mode of ['direct', 'claimed', 'expiry']) {
+ const f = fixture(t);
+ const id = returned(f, cause, 30);
+ assert.throws(() => store.release(f.board, id, f.other), error => error.code === 'NOT_YOURS');
+ f.advance(5);
+ if (mode === 'expiry') f.advance(25);
+ else {
+ if (mode === 'claimed') claim(f, id, f.builder);
+ store.release(f.board, id, f.builder);
+ }
+ claim(f, id, f.other);
+ assert.equal(store.getItem(f.board, id).item_owner, f.other, `${cause}/${mode}`);
+ }
+ }
+});
+
+test('[B13,B5] omitted or zero first refusal keeps reopened claims unchanged', (t) => {
+ for (const cause of ['reject', 'landing', 'conflict']) {
+ for (const minutes of [undefined, 0]) {
+ const f = fixture(t);
+ const id = returned(f, cause, minutes);
+ assert.equal(store.inbox(f.board, f.builder).filter(row => row.shout_text.includes('waits for you')).length, 0);
+ f.advance(5);
+ claim(f, id, f.other);
+ assert.equal(store.getItem(f.board, id).item_owner, f.other);
+ }
+ }
+});
+
+test('[B13,B5] first refusal does not bypass the existing one-live-claim rule', (t) => {
+ const f = fixture(t);
+ const id = returned(f, 'landing', 30);
+ const second = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'another', route: 'mid',
+ criterion: 'prove', check: 'true', brief: 'Files: src/a.js\nTest: proves another fix' });
+ claim(f, second, f.builder);
+ assert.throws(() => claim(f, id, f.builder), error => error.code === 'ONE_CLAIM');
+ store.release(f.board, second, f.builder);
+ claim(f, id, f.builder);
+});
+
+
+test('[B13,B5] releasing another review cannot cancel the builder reservation', (t) => {
+ const f = fixture(t);
+ const id = returned(f, 'reject', 30);
+ const another = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'review another', route: 'mid',
+ criterion: 'prove', check: 'true', brief: 'Files: src/a.js\nTest: proves another fix' });
+ claim(f, another, f.other);
+ submitFixture(f.board, another, { agentId: f.other, commit: COMMIT, tree: COMMIT });
+ store.reserveReview(f.board, another, { agentId: f.builder, leaseMs: 1_800_000, policy: 'any' });
+ assert.equal(store.release(f.board, another, f.builder, 'another reviewer can take this'), true);
+ assert.throws(() => claim(f, id, f.other), error => error.code === 'REOPEN_HELD_FOR_BUILDER');
+ assert.equal(store.nextFor(f.board, { agentId: f.other, lane: 'core' }).item, null);
+ assert.equal(store.nextFor(f.board, { agentId: f.builder, lane: 'core' }).item.item_id, id);
+});
+
+test('[B13,B5,H16] a sealed return persists one window and notice across replay and snapshots', async (t) => {
+ const { REOPEN_FIRST_REFUSAL_ENGINE } = await import('../src/machine.js');
+ const { firstRefusalArgs } = await import('../src/claims.js');
+ const f = fixture(t);
+ const id = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'replay', route: 'mid',
+ criterion: 'prove', check: 'true', brief: 'Files: src/a.js\nTest: proves replay' });
+ claim(f, id, f.builder);
+ submitFixture(f.board, id, { agentId: f.builder, commit: COMMIT, tree: COMMIT });
+ const args = firstRefusalArgs('verify', [id, { agentId: f.other, decision: 'REJECT', reason: 'OTHER',
+ note: 'proof', head: COMMIT, digest: 'digest:bar', policy: 'any' }], configFromSource('{"claim":{"reopenFirstRefusalMinutes":30}}'));
+ const move = prepareEngineMove(f.board, 'verify', args);
+ assert.equal(move.engine, REOPEN_FIRST_REFUSAL_ENGINE);
+ assert.throws(() => applyEngineMove(f.board, { ...move, engine: REOPEN_FIRST_REFUSAL_ENGINE - 1 },
+ { sequence: 1, at: '2026-01-01T00:00:00Z' }), /engine/);
+ const receipt = { sequence: 1, at: '2026-01-01T00:00:00Z' };
+ applyEngineMove(f.board, move, receipt);
+ applyEngineMove(f.board, move, receipt);
+ assert.equal(store.recentShouts(f.board).filter(row => row.shout_text.includes('waits for you')).length, 1);
+ const replica = store.openBoard(join(f.directory, 'replica.sqlite'), { now: () => new Date('2026-01-01T00:05:00Z') });
+ t.after(() => store.closeBoard(replica));
+ importBoard(replica, exportBoard(f.board));
+ assert.throws(() => store.claim(replica, id, { agentId: f.other, lane: 'core', leaseMs: 7_200_000, freeze: () => null }),
+ error => error.code === 'REOPEN_HELD_FOR_BUILDER' && error.message.includes('2026-01-01T00:30:00.000Z'));
+ assert.equal(store.recentShouts(replica).filter(row => row.shout_text.includes('waits for you')).length, 1);
+ const claimMove = prepareEngineMove(replica, 'claim', [id, { agentId: f.other, lane: 'core', leaseMs: 7_200_000, freeze: () => null }]);
+ assert.throws(() => applyEngineMove(replica, { ...claimMove, engine: REOPEN_FIRST_REFUSAL_ENGINE - 1 }, { sequence: 2, at: '2026-01-01T00:05:00Z' }), /engine/);
+ assert.equal(store.getItem(replica, id).item_owner, null);
+ assert.equal(prepareEngineMove(replica, 'release', [id, f.builder]).engine, REOPEN_FIRST_REFUSAL_ENGINE);
+ store.release(replica, id, f.builder);
+ store.claim(replica, id, { agentId: f.other, lane: 'core', leaseMs: 7_200_000, freeze: () => null });
+});
+
+
+test('[B13,B5,D1] a builder notice preserves the reopen cause that triggers rigor', (t) => {
+ const f = fixture(t);
+ returned(f, 'landing', 30, 'refusal:CHECK_RED');
+ returned(f, 'landing', 30, 'refusal:CHECK_RED');
+ const notices = store.recentShouts(f.board);
+ assert.equal(notices.filter(row => row.shout_from === 'rigor' && row.shout_to === 'coordinator').length, 1);
+ assert.equal(notices.filter(row => row.shout_to === f.builder && row.shout_text.includes('waits for you')).length, 2);
+});
diff --git a/test/machine.test.js b/test/machine.test.js
index a76d92c9..e87f40a4 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -914,6 +914,8 @@ test('claim refuses in the declared order, one failure peeled at a time, on a re
const strong = store.register(board, { lane: 'web', path: '/repo-web-strong' });
const claimAs = (id, agentId, lane, freezer = retiredFreeze) => outcome(() => store.claim(board, id, { agentId, lane, leaseMs: 7_200_000, freeze: freezer }));
const done = submittedItem(board);
+ const returned = submittedItem(board);
+ store.verify(board, returned, { agentId: 'web-2', decision: 'REJECT', reason: 'TEST_FAILURE', head: SHA_A, digest: 'digest:Page', policy: 'any', note: 'the check fails', reopenFirstRefusalMinutes: 30 });
const dependency = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });
const target = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page', after: [dependency] });
const spare = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Page' });
@@ -928,7 +930,7 @@ test('claim refuses in the declared order, one failure peeled at a time, on a re
store.releaseItemHold(board, target, { agentId: 'coordinator' });
fired.push(claimAs(target, light, 'api'), claimAs(target, light, 'web'), claimAs(target, strong, 'web'));
verdictOn(board, dependency, 'web-2', 'ACCEPT');
- fired.push(claimAs(target, strong, 'web'));
+ fired.push(claimAs(target, strong, 'web'), claimAs(returned, strong, 'web'));
store.editItem(board, target, { agentId: 'coordinator', criterion: 'Pending correction before the lane guard.' });
store.release(board, target, 'web-2');
fired.push(claimAs(target, strong, 'web'));
@@ -940,7 +942,7 @@ test('claim refuses in the declared order, one failure peeled at a time, on a re
store.release(board, spare, strong);
fired.push(claimAs(target, strong, 'web'), claimAs(target, strong, 'web', freeze));
assert.deepEqual(fired, [...declaredBoardOrder('claim'), 'ok']);
- assert.deepEqual(fired, ['NO_ITEM', 'NOT_CLAIMABLE', 'ITEM_HELD', 'WRONG_LANE', 'ROUTE', 'BLOCKED', 'HELD', 'PENDING_REFREEZE', 'LANE_HELD', 'ONE_CLAIM', 'UNKNOWN_SPEC', 'ok']);
+ assert.deepEqual(fired, ['NO_ITEM', 'NOT_CLAIMABLE', 'ITEM_HELD', 'WRONG_LANE', 'ROUTE', 'BLOCKED', 'HELD', 'REOPEN_HELD_FOR_BUILDER', 'PENDING_REFREEZE', 'LANE_HELD', 'ONE_CLAIM', 'UNKNOWN_SPEC', 'ok']);
} finally {
lab.done();
}