Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(pool): retain item leases while queued [C7,V4]
Corey Olson90864beb39b1
diff --git a/src/cli.js b/src/cli.jsindex 44095191..3eb0f93a 100644--- a/src/cli.js+++ b/src/cli.js@@ -561,7 +561,7 @@ async function bindCheckoutSession(io, positionals, values) {throw new Refused('USAGE', 'pullboard takeover takes no arguments; run pullboard takeover [--json]');}const writes = ['init', 'join', 'worktree', 'hooks', 'hook', 'skills', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',- 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'merged', 'land', 'withdraw', 'refreeze', 'reopen', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];+ 'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'check', 'merged', 'land', 'withdraw', 'refreeze', 'reopen', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];if (!writes.includes(command) && !(command === 'settings' && first) && !(command === 'spec' && first === 'apply') && !(command === 'relay' && ['on', 'off'].includes(first))) return;if (command === 'answer' && values.as === 'person') return;const digest = agentSessionDigest();@@ -569,6 +569,18 @@ async function bindCheckoutSession(io, positionals, values) {if (command === 'takeover') throw new Refused('AGENT_SESSION', 'takeover belongs to an agent session; run pullboard takeover from the agent’s shell');return;}+ if (command === 'check') {+ const ctx = context(io);+ const renewsOwnClaim = withBoard(ctx, (board) => {+ const agentId = ctx.info.isMain ? COORDINATOR : store.agentAt(board, ctx.info.root)?.agent_id;+ const item = first ? store.getItem(board, idArg(first)) : store.listItems(board)+ .find((entry) => entry.item_status === 'claimed' && entry.item_owner === agentId && entry.item_parent_id === null);+ return Boolean(agentId && item?.item_status === 'claimed' && item.item_owner === agentId);+ });+ // A named peer's check remains read-only. An owned check can renew, so acquire checkout+ // authority before joining the gate queue, in the same order as submit and verify.+ if (!renewsOwnClaim) return;+ }const info = repoInfo(io.cwd);let agent = info.isMain ? COORDINATOR : null;if (!info.isMain) {@@ -2110,7 +2122,7 @@ async function submitHere(ctx, id) {withBoard(ctx, (board) => refuseUnverifiedStack(root, board, held, commit, trunk));// Every submit proves its frozen check and reachable tests anew on this exact commit (V4,V16).// A full-gate stamp never substitutes for either proof; only an actual full fallback may stamp.- const gate = await runSubmitGate(root, ctx.config, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), agent: me.id, item: String(id), onWait: gateWaitReporter(ctx.io) });+ const gate = await runSubmitGate(root, ctx.config, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), agent: me.id, item: String(id), onWait: queuedItemLease(ctx, held, me.id, 'build') });if (!gate.isGreen) {const message = `the submission proof is red at ${commit.slice(0, 12)}; fix it, commit, submit again. ${submitGateReport(gate)}`;// No submission can follow this verdict. Read-only main comparisons must not retain the seat's write lease.@@ -2201,7 +2213,7 @@ async function verifyHere(ctx, id, { second, values }) {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);- check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs, gateLease: lease }), { browser: true, agent: me.id, item: String(id), kind: 'review', itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs, gateLease: lease }), { browser: true, agent: me.id, item: String(id), kind: 'review', itemCheck: true, onWait: queuedItemLease(ctx, item, me.id, 'review') });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}` : ''})`}`@@ -2604,7 +2616,7 @@ function workCommands(io, args) {throw new Refused('CHECK_CONFIRM', `the check set by ${authorName} was not run: ${check}; run pullboard check ${item.item_id} --yes after reading the command, or answer yes at the prompt`);}}- const run = await withGateSlot(ctx.info.root, (lease) => runProfiledShell(ctx.info.root, check, { waitMs: lease.waitMs, artifactPrefix: `pullboard-check-${item.item_id}`, persistLog: true, gateLease: lease }), { browser: true, agent: caller, item: String(item.item_id), kind: 'check', itemCheck: true, onWait: gateWaitReporter(io) });+ const run = await withGateSlot(ctx.info.root, (lease) => runProfiledShell(ctx.info.root, check, { waitMs: lease.waitMs, artifactPrefix: `pullboard-check-${item.item_id}`, persistLog: true, gateLease: lease }), { browser: true, agent: caller, item: String(item.item_id), kind: 'check', itemCheck: true, onWait: queuedItemLease(ctx, item, caller, 'build') });io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check, by, report: run.isGreen ? '' : digestOf(run.output) });const timings = timingDigest(run.profile);const compact = timings && !run.profile.files.length@@ -2785,7 +2797,8 @@ function workCommands(io, args) {/** Label the kind and item of a queued run without hiding older queue-class labels. */function resourceRunLabel(entry) {const priority = entry.landing ? 'landing' : entry.itemCheck ? 'item check' : entry.diagnostic ? 'diagnostic' : '';- const details = [entry.kind !== priority ? entry.kind : '', entry.item ? `#${entry.item}` : '', entry.browser ? 'browser' : ''].filter(Boolean);+ const details = [entry.kind !== priority ? entry.kind : '', entry.item ? `#${entry.item}` : '',+ entry.leaseUntil ? `lease until ${entry.leaseUntil}` : '', entry.browser ? 'browser' : ''].filter(Boolean);return `${priority ? ` (${priority})` : ''}${details.length ? ` (${details.join(', ')})` : ''}`;}@@ -2794,6 +2807,48 @@ function resourceAgent(ctx) {return ctx.info.isMain ? COORDINATOR : withBoard(ctx, board => store.agentAt(board, ctx.info.root)?.agent_id);}+/** Keep only this queued command's live item lease, using ordinary ordered board moves. */+function queuedItemLease(ctx, initial, agentId, kind) {+ const report = gateWaitReporter(ctx.io);+ // Naming somebody else's check remains read-only; it never extends their build claim.+ if (kind === 'build' && (initial.item_status !== 'claimed' || initial.item_owner !== agentId)) return report;+ const review = kind === 'review';+ if (review && initial.item_review_by !== agentId) return report;+ const field = review ? 'item_review_until' : 'item_lease_until';+ const owner = review ? 'item_review_by' : 'item_owner';+ const status = review ? 'submitted' : 'claimed';+ const leaseMs = review ? ctx.config.reviewLeaseMs : ctx.config.leaseMs;+ const expected = { digest: initial.item_frozen_digest, commit: initial.item_commit };+ let confirmedLeaseUntil = '';+ return async (state) => {+ if (!state.admitted) report(state);+ const now = ctx.clock.now().getTime();+ // Queue polling is frequent; reopen the board only when renewal is due or admission starts.+ if (!state.admitted && Date.parse(confirmedLeaseUntil) - now > leaseMs / 2) {+ return { leaseUntil: confirmedLeaseUntil };+ }+ return await withBoard(ctx, async (board) => {+ const current = store.getItem(board, initial.item_id);+ const expires = Date.parse(current[field]);+ if (current.item_status !== status || current[owner] !== agentId || !Number.isFinite(expires) || expires <= now+ || current.item_frozen_digest !== expected.digest || current.item_commit !== expected.commit) {+ throw new Refused('ITEM_LEASE_LOST', `the queued ${review ? 'review' : 'build'} lease for #${initial.item_id} changed or expired; claim or reserve the item again before retrying`);+ }+ if (state.admitted || expires - now <= leaseMs / 2) {+ const result = await ordered(ctx, board, review ? 'reserveReview' : 'claim', [initial.item_id, {+ agentId, leaseMs,+ ...(review ? { policy: ctx.config.verify.policy, familyPolicy: ctx.config.verify.family }+ : { lane: current.item_lane, freeze: claimFreezer(ctx), head: headCommit(ctx.info.root) }),+ }]);+ confirmedLeaseUntil = review ? result.item_review_until : result.leaseUntil;+ return { leaseUntil: confirmedLeaseUntil };+ }+ confirmedLeaseUntil = current[field];+ return { leaseUntil: confirmedLeaseUntil };+ });+ };+}+/** Build a de-duplicated queue message for a gate waiting on machine capacity. */function gateWaitReporter(io) {let last = '';diff --git a/src/resources.js b/src/resources.jsindex 635f9dde..a2ffcc0c 100644--- a/src/resources.js+++ b/src/resources.js@@ -86,6 +86,7 @@ function open(file) {if (!columns.includes('browser')) db.exec(`ALTER TABLE ${table} ADD COLUMN browser INTEGER NOT NULL DEFAULT 0`);if (!columns.includes('item')) db.exec(`ALTER TABLE ${table} ADD COLUMN item TEXT NOT NULL DEFAULT ''`);if (!columns.includes('kind')) db.exec(`ALTER TABLE ${table} ADD COLUMN kind TEXT NOT NULL DEFAULT ''`);+ if (!columns.includes('lease_until')) db.exec(`ALTER TABLE ${table} ADD COLUMN lease_until TEXT NOT NULL DEFAULT ''`);}db.exec('COMMIT');transaction = false;@@ -174,14 +175,15 @@ function update(db, action) {/** Current holders and the landing-first line, then every other kind in arrival order. */function snapshot(db, name) {/** Preserve older public entries while naming diagnostics as a distinct queue class. */- const project = ({ diagnostic, browser, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,+ const project = ({ diagnostic, browser, item, kind, leaseUntil, ...entry }) => ({ ...entry, landing: entry.landing === 1,itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),- ...(browser === 1 ? { browser: true } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}) });+ ...(browser === 1 ? { browser: true } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}),+ ...(leaseUntil ? { leaseUntil } : {}) });// Browser is an additional capability on a gate lease, not a second partially held row.const where = name === 'browser' ? 'name = ? AND browser = 1' : 'name = ?';const sourceName = name === 'browser' ? 'gate' : name;- const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM holder WHERE ${where} ORDER BY since, token`).all(sourceName).map(project);- const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);+ const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind, lease_until AS leaseUntil FROM holder WHERE ${where} ORDER BY since, token`).all(sourceName).map(project);+ const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind, lease_until AS leaseUntil FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);return { holders, line };}@@ -216,7 +218,7 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr/*** Join the landing-first queue; every other kind keeps its original FIFO ticket.*- * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => any | Promise<any>, allowIdleCapacityUpdate?: boolean }} options - An awaited wait callback may return {leaseUntil}; it then receives one final {admitted:true} callback before work starts.* @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}*/export async function takeResource(options) {@@ -246,6 +248,20 @@ export async function takeResource(options) {const started = processStarted(pid);const repo = options.repo ?? repoRoot(root);let queuedAt = new Date().toISOString();+ let leaseUntil = '';+ /** Record an item's lease only after its awaited owner renewal succeeds. */+ const keepItemLease = async (state, table) => {+ const result = await options.onWait?.(state);+ if (result?.leaseUntil !== undefined) {+ if (typeof result.leaseUntil !== 'string' || !Number.isFinite(Date.parse(result.leaseUntil))) {+ throw new Refused('BAD_RESOURCE_METADATA', 'the waiting item renewal must return a valid leaseUntil timestamp');+ }+ leaseUntil = result.leaseUntil;+ const changed = update(db, () => db.prepare(`UPDATE ${table} SET lease_until = ? WHERE token = ? AND pid = ? AND started = ?`)+ .run(leaseUntil, token, pid, started));+ if (changed.changes !== 1) throw new Refused('RESOURCE_LEASE_LOST', 'the queued resource lease disappeared during item renewal; retry the command');+ }+ };try {update(db, () => {const currentCapacity = options.capacityProvider?.() ?? capacity;@@ -291,6 +307,15 @@ export async function takeResource(options) {return { acquired: false, state: { ...spot, position: reportPosition } };});if (acquired.acquired) {+ // Only item-lease callbacks opt into admission. Await them so no renewal remains in+ // flight during the run, and restart the ordinary item expiry from this boundary.+ if (leaseUntil) {+ try { await keepItemLease({ ...acquired.state, admitted: true }, 'holder'); }+ catch (error) {+ update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token));+ throw error;+ }+ }let released = false;let lost = false;const heartbeat = setInterval(() => {@@ -321,7 +346,7 @@ export async function takeResource(options) {};return { name, scope, token, pool, browser, waitMs: Math.max(0, Date.now() - requestedAt), release, renew };}- options.onWait?.(acquired.state);+ await keepItemLease(acquired.state, 'waiter');await pause(POLL_MS);}} catch (error) {diff --git a/test/resources.test.js b/test/resources.test.jsindex 08f065b9..7f6c1851 100644--- a/test/resources.test.js+++ b/test/resources.test.js@@ -11,11 +11,23 @@ import { createInterface } from 'node:readline';import { after, test } from 'node:test';import { DatabaseSync } from 'node:sqlite';import { listResources, setResourceCapacity, takeResource } from '../src/resources.js';+import * as store from '../src/board.js';+import { createE2eHelpers } from './e2e-helpers.js';const TEMP = [];const CHILDREN = new Set();const MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/resources.js')).href;const GATE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/gate.js')).href;+const LEASE_HELPERS = createE2eHelpers();+const CLOCKED_CLI = `+import { readFileSync } from 'node:fs';+import { main } from ${JSON.stringify(pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href)};+/** The private test alone controls the board clock; resource liveness still uses real OS time. */+const clock = { now: () => new Date(Number(readFileSync(process.env.PULLBOARD_FIXTURE_CLOCK, 'utf8'))) };+process.exitCode = await main(process.argv.slice(1), {+ cwd: process.cwd(), clock, stdin: process.stdin, stdout: process.stdout, stderr: process.stderr,+});+`;const POOL_MODULE_WORKER = `import { takeResource } from ${JSON.stringify(MODULE)};let announced = false;@@ -131,6 +143,17 @@ function privateList(box, scope = 'machine', root = process.cwd()) {}}+/** Open a real fixture pool before restoring the parent's unrelated machine-home environment. */+function privateTake(box, options) {+ const previous = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_MACHINE_HOME = box.home;+ try { return takeResource({ ...options, root: box.first }); }+ finally {+ if (previous === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previous;+ }+}+/** Launch one independent process that takes a resource and waits for a release command. */function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = box.first, agent, stallMs = 0, landing = false, env = {}, sandboxProcessInfo = false }) {const workerArgs = ['--input-type=module', '-e', WORKER, name, String(capacity), scope, root, agent, String(stallMs), String(landing)];@@ -303,6 +326,241 @@ after(async () => {await Promise.all(running.map((child) => child.finished));for (const child of running) child.lines.close();TEMP.forEach((dir) => rmSync(dir, { recursive: true, force: true }));+ LEASE_HELPERS.cleanup();+});++/** Run the real CLI with a private file-backed board clock and the fixture's ordinary identity. */+function clockedCli(box, cwd, ...args) {+ const result = runFixtureChild(process.execPath, ['--input-type=module', '-e', CLOCKED_CLI, ...args],+ { cwd, env: box.env, encoding: 'utf8' });+ assert.equal(result.status, 0, `${result.stdout}\n${result.failure ?? result.stderr}`);+ return args.includes('--json') ? JSON.parse(result.stdout) : result.stdout;+}++/** Track a waiting real CLI process in the same cleanup registry as the resource workers. */+function leaseCommand(box, cwd, ...args) {+ const child = LEASE_HELPERS.launch(box, cwd, process.execPath, ['--input-type=module', '-e', CLOCKED_CLI, ...args]);+ child.lines = createInterface({ input: child.stdout });+ child.exitResult = null;+ child.finished = child.closed.then((result) => {+ child.exitResult = result;+ CHILDREN.delete(child);+ return result;+ });+ CHILDREN.add(child);+ return child;+}++/** Create genuine submitted/claimed items and independent reviewers before advancing any clock. */+function itemLeaseFixture(t) {+ const box = LEASE_HELPERS.project('true');+ const configFile = join(box.repo, 'pullboard.json');+ const config = JSON.parse(readFileSync(configFile, 'utf8'));+ writeFileSync(configFile, JSON.stringify({ ...config, lease: '1m', reviewLease: '1m' }));+ box.git(box.repo, 'add', 'pullboard.json');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: configure queue lease fixture');+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');+ box.first = box.repo;+ box.home = box.env.PULLBOARD_MACHINE_HOME;+ box.clockFile = join(box.dir, 'board-clock');+ writeFileSync(box.clockFile, String(Date.now()));+ box.env.PULLBOARD_FIXTURE_CLOCK = box.clockFile;+ box.clock = { now: () => new Date(Number(readFileSync(box.clockFile, 'utf8'))) };+ box.advance = (ms) => writeFileSync(box.clockFile, String(box.clock.now().getTime() + ms));+ box.board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'), box.clock);+ t.after(() => store.closeBoard(box.board));+ box.gates = [];+ box.ids = [];+ box.reviewCommits = [];+ for (const number of [1, 2, 3, 4]) {+ const folder = join(box.dir, `item-gate-${number}`);+ mkdirSync(folder);+ const gate = LEASE_HELPERS.holdingGate({ dir: folder });+ const added = clockedCli(box, box.repo, 'add', 'web', `Queued lease ${number}`, '--specs', 'G1',+ '--criterion', 'The queued command retains only its own live item lease.', '--check', gate.command, '--json');+ const id = added.item.item_id;+ box.ids.push(id); box.gates.push(gate);+ if (number < 4) {+ // Each item has independent ancestry: a pending review cannot be another submit's base.+ box.git(box.web, 'switch', '-q', '--detach', 'main');+ clockedCli(box, box.web, 'claim', String(id), '--json');+ mkdirSync(join(box.web, 'web'), { recursive: true });+ writeFileSync(join(box.web, 'web', `queued-${number}.txt`), 'fixture\n');+ box.git(box.web, 'add', 'web');+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): queue lease fixture [G1]');+ if (number < 3) {+ clockedCli(box, box.web, 'submit', String(id), '--json');+ box.reviewCommits.push(box.git(box.web, 'rev-parse', 'HEAD'));+ }+ }+ }+ box.reviewers = [];+ const commit = box.git(box.web, 'rev-parse', 'HEAD');+ for (const number of [1, 2]) {+ const root = join(box.dir, `queue-review-${number}`);+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', root, box.reviewCommits[number - 1]);+ clockedCli(box, root, 'join', 'api', '--json');+ box.reviewers.push(root);+ }+ box.checker = join(box.dir, 'queue-build-check');+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', box.checker, commit);+ clockedCli(box, box.checker, 'join', 'web', '--json');+ clockedCli(box, box.checker, 'claim', String(box.ids[3]), '--json');+ clockedCli(box, box.repo, 'settings', 'gateSlots', '2', '--json');+ return box;+}++test('a review waiting in the pool keeps its lease [C7,V4]', {+ timeout: 120_000, // budget: real private Git/CLI setup and causally controlled queue/run/death phases, never a production lease extension.+}, async (t) => {+ const box = itemLeaseFixture(t);+ const [reviewId, deadId, buildId, checkId] = box.ids;+ const [reviewGate, deadGate, buildGate, checkGate] = box.gates;+ const [reviewer, deadReviewer] = box.reviewers;+ // Readers project expired claims as open with no lease. Observe the retained raw deadline+ // here so admission's normal expiry remains distinguishable from an unwanted renewal.+ const item = (id) => store.itemById(box.board, id);+ const end = (id, kind) => item(id)[kind === 'review' ? 'item_review_until' : 'item_lease_until'];+ const waiting = (id) => privateList(box).find((resource) => resource.name === 'gate')?.line.find((entry) => entry.item === String(id));+ let holder;+ const commands = [];+ try {+ clockedCli(box, reviewer, 'next', '--verify', String(reviewId), '--json');+ const originalReviewEnd = end(reviewId, 'review');+ const originalBuildEnd = end(buildId, 'check');+ const originalCheckEnd = end(checkId, 'check');+ holder = poolWorker(box, { agent: 'lease-test-holder', browser: true });+ await acquired(holder);+ writeFileSync(reviewGate.mode, 'hold'); writeFileSync(buildGate.mode, 'hold'); writeFileSync(checkGate.mode, 'hold');+ const review = leaseCommand(box, reviewer, 'verify', String(reviewId), 'accept',+ '--note', 'Private fixture: waited behind held capacity and ran the frozen check.', '--json');+ commands.push(review);+ await waitUntil(() => waiting(reviewId)?.leaseUntil, 'the real verify waiter and its item lease end');+ const build = leaseCommand(box, box.web, 'submit', String(buildId), '--json');+ commands.push(build);+ await waitUntil(() => waiting(buildId)?.leaseUntil, 'the real submit waiter and its item lease end');+ const check = leaseCommand(box, box.checker, 'check', String(checkId), '--yes', '--json');+ commands.push(check);+ await waitUntil(() => waiting(checkId)?.leaseUntil, 'the independent owned check and its item lease end');+ const listed = clockedCli(box, box.repo, 'resources', '--json').resources.find((resource) => resource.name === 'gate');+ for (const [id, kind] of [[reviewId, 'review'], [buildId, 'submit'], [checkId, 'check']]) {+ const entry = listed.line.find((row) => row.item === String(id));+ assert.equal(entry.kind, kind);+ assert.equal(entry.leaseUntil, end(id, kind), 'resources reports this exact board item lease, not the pool heartbeat');+ }+ assert.match(clockedCli(box, box.repo, 'resources'), /lease until \d{4}-\d{2}-\d{2}T/u);++ box.advance(30_000);+ await waitUntil(() => end(reviewId, 'review') > originalReviewEnd && end(buildId, 'check') > originalBuildEnd+ && end(checkId, 'check') > originalCheckEnd, 'all live queued commands renew before their original expiry');+ const previousReviewEnd = end(reviewId, 'review');+ const previousBuildEnd = end(buildId, 'check');+ const previousCheckEnd = end(checkId, 'check');+ box.advance(31_000);+ await waitUntil(() => end(reviewId, 'review') > previousReviewEnd && end(buildId, 'check') > previousBuildEnd+ && end(checkId, 'check') > previousCheckEnd, 'all leases remain held past their original deadlines');+ assert.ok(box.clock.now().toISOString() > originalReviewEnd);+ assert.ok(end(reviewId, 'review') > box.clock.now().toISOString());+ assert.ok(end(buildId, 'check') > box.clock.now().toISOString());+ assert.ok(end(checkId, 'check') > box.clock.now().toISOString());++ await release(holder); holder = null;+ await waitUntil(() => existsSync(reviewGate.events), 'the admitted verification starts its actual frozen check');+ const runningReviewEnd = end(reviewId, 'review');+ for (const advance of [30_000, 31_000, 1_000]) {+ const beforeBuildEnd = end(buildId, 'check');+ const beforeCheckEnd = end(checkId, 'check');+ box.advance(advance);+ if (advance >= 30_000) await waitUntil(() => end(buildId, 'check') > beforeBuildEnd+ && end(checkId, 'check') > beforeCheckEnd, 'both build waiters renew while the admitted review runs');+ }+ assert.equal(end(reviewId, 'review'), runningReviewEnd, 'admission ends review item renewals');+ assert.ok(runningReviewEnd < box.clock.now().toISOString(), 'the running review resumes ordinary lease expiry');+ assert.ok(waiting(buildId) && waiting(checkId), 'submit and check remain queued behind the review');+ writeFileSync(reviewGate.release, 'release');+ assert.equal((await review.finished).code, 0, `${review.stdoutText}\n${review.stderrText}`);+ await waitUntil(() => existsSync(buildGate.events), 'the admitted real submit starts its frozen check');+ const runningBuildEnd = end(buildId, 'check');+ for (const advance of [30_000, 31_000, 1_000]) {+ const beforeCheckEnd = end(checkId, 'check');+ box.advance(advance);+ if (advance >= 30_000) await waitUntil(() => end(checkId, 'check') > beforeCheckEnd,+ 'the standalone check keeps renewing while submit runs');+ }+ clockedCli(box, box.repo, 'resources', '--json');+ assert.equal(end(buildId, 'check'), runningBuildEnd, 'admission ends build item renewals');+ assert.ok(runningBuildEnd < box.clock.now().toISOString(), 'the running build resumes ordinary lease expiry');+ writeFileSync(buildGate.release, 'release');+ assert.equal((await build.finished).code, 0, `${build.stdoutText}\n${build.stderrText}`);+ assert.equal(item(buildId).item_status, 'submitted', 'the actual queued submit completes its ordinary board move');+ await waitUntil(() => existsSync(checkGate.events), 'the independent owned check starts');+ const runningCheckEnd = end(checkId, 'check');+ box.advance(Date.parse(runningCheckEnd) - box.clock.now().getTime() + 1);+ clockedCli(box, box.repo, 'resources', '--json');+ assert.equal(end(checkId, 'check'), runningCheckEnd, 'admission ends standalone check renewals');+ assert.ok(runningCheckEnd < box.clock.now().toISOString(), 'the standalone check resumes normal expiry');+ writeFileSync(checkGate.release, 'release');+ assert.equal((await check.finished).code, 0, `${check.stdoutText}\n${check.stderrText}`);++ clockedCli(box, deadReviewer, 'next', '--verify', String(deadId), '--json');+ holder = poolWorker(box, { agent: 'dead-waiter-holder', browser: true });+ await acquired(holder);+ const dead = leaseCommand(box, deadReviewer, 'verify', String(deadId), 'accept',+ '--note', 'Private fixture: the queued waiter must not start before its holder releases.', '--json');+ commands.push(dead);+ await waitUntil(() => waiting(deadId)?.leaseUntil, 'the doomed real reviewer is queued with its item lease');+ const beforeDeadEnd = end(deadId, 'review');+ box.advance(30_000);+ await waitUntil(() => end(deadId, 'review') > beforeDeadEnd, 'the reviewer renews while alive');+ assert.equal(existsSync(deadGate.events), false, 'the killed waiter never started its frozen check');+ dead.kill('SIGKILL');+ assert.equal((await dead.finished).signal, 'SIGKILL');+ await waitUntil(() => !waiting(deadId), 'the real dead waiter is pruned');+ const lastDeadEnd = end(deadId, 'review');+ box.advance(Date.parse(lastDeadEnd) - box.clock.now().getTime() + 1);+ assert.equal(end(deadId, 'review'), lastDeadEnd, 'a dead process cannot continue renewing');+ clockedCli(box, reviewer, 'next', '--verify', String(deadId), '--json');+ assert.equal(item(deadId).item_review_by, store.agentAt(box.board, reviewer).agent_id,+ 'another actual reviewer can reserve after the dead waiter lease lapses');++ await t.test('asynchronous renewal finishes outside the queue transaction before admission', async () => {+ const callbackBox = fixture();+ const callbackHolder = await privateTake(callbackBox, { name: 'awaited-renewal', capacity: 1 });+ let enter;+ let finish;+ const entered = new Promise((resolve) => { enter = resolve; });+ const barrier = new Promise((resolve) => { finish = resolve; });+ const refused = new Error('fixture item lease was lost while waiting');+ let completed = false;+ const queued = privateTake(callbackBox, { name: 'awaited-renewal', capacity: 1, onWait: async () => {+ const connection = new DatabaseSync(join(callbackBox.home, 'resources.sqlite'));+ try { connection.exec('BEGIN IMMEDIATE'); connection.exec('ROLLBACK'); }+ finally { connection.close(); }+ enter();+ await barrier;+ completed = true;+ throw refused;+ } }).then((lease) => ({ lease }), (error) => ({ error }));+ await entered;+ callbackHolder.release();+ finish();+ const result = await queued;+ try {+ assert.equal(completed, true);+ assert.equal(result.error, refused, 'a failed awaited renewal refuses admission instead of running stale work');+ const pool = privateList(callbackBox).find((entry) => entry.name === 'awaited-renewal');+ assert.deepEqual(pool.line, [], 'failed renewal removes its waiter');+ assert.deepEqual(pool.holders, [], 'failed renewal never leaves a held resource');+ } finally { result.lease?.release(); }+ });+ } finally {+ for (const gate of box.gates) writeFileSync(gate.release, 'release');+ if (holder && !holder.exitResult) await release(holder);+ // Released gates let each CLI reap its own check workers and private clone before the+ // shared fixture directory is removed. Killing a parent here would strand those workers.+ await Promise.all(commands.map((child) => child.finished));+ for (const child of commands) child.lines.close();+ }});test('[Q1,Q2] capacity-one takers acquire in strict FIFO arrival order', async () => {