Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(core): queue item checks behind gates [Q1,Q2,V18]
Corey Olsondee72f29c4a7
diff --git a/src/cli.js b/src/cli.jsindex 6042cda1..ba0c59e1 100644--- a/src/cli.js+++ b/src/cli.js@@ -13,7 +13,7 @@ import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';import { doctrineHistory, loadDoctrine } from './doctrine.js';import { requirePersonChannel } from './person.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';-import { digestOf, gateReport, runGate, runShell } from './gate.js';+import { digestOf, gateReport, runGate, runShell, withGateSlot } from './gate.js';import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, mainCheckout, repoInfo, resolveCommit, tryGit, untracked } from './git.js';import {FIX_NOTE,@@ -1204,8 +1204,8 @@ function readCommands(io, { first, second, rest, values }) {if (!resources.length) io.say('no resources have been used');for (const resource of resources) {io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})`);- for (const holder of resource.holders) io.say(` held by ${holder.agent}${holder.repo ? ` in ${holder.repo}` : ''}${holder.landing ? ' (landing)' : ''} since ${holder.since}`);- resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${waiter.agent}${waiter.repo ? ` in ${waiter.repo}` : ''}${waiter.landing ? ' (landing)' : ''}`));+ for (const holder of resource.holders) io.say(` held by ${holder.agent}${holder.repo ? ` in ${holder.repo}` : ''}${holder.landing ? ' (landing)' : holder.itemCheck ? ' (item check)' : ''} since ${holder.since}`);+ resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${waiter.agent}${waiter.repo ? ` in ${waiter.repo}` : ''}${waiter.landing ? ' (landing)' : waiter.itemCheck ? ' (item check)' : ''}`));}return 0;},@@ -1558,7 +1558,7 @@ async function verifyHere(ctx, id, { second, values }) {if (decision === 'ACCEPT') {if (digest !== item.item_frozen_digest) throw new Refused('CRITERIA_CHANGED', 'the criterion changed; ask the coordinator to refreeze this item before checking it');requireTrunkMerge(root, commit);- check = checkAtCommit(root, item);+ check = await withGateSlot(root, () => checkAtCommit(root, item), { itemCheck: true, onWait: gateWaitReporter(ctx.io) });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, ' ')}`);if (check.state === 'red') throw new Refused('CHECK_RED', `the frozen item check is red at the submitted commit; 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, ' ')}`);@@ -1928,7 +1928,7 @@ function workCommands(io, args) {throw new Refused('CHECK_CONFIRM', `the check set by ${by} was not run: ${check}; run pullboard check ${item.item_id} --yes after reading the command, or answer yes at the prompt`);}}- const run = runShell(ctx.info.root, check);+ const run = await withGateSlot(ctx.info.root, () => runShell(ctx.info.root, check), { itemCheck: true, onWait: gateWaitReporter(io) });io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check, by, report: run.isGreen ? '' : digestOf(run.output) });io.say(`check ${run.isGreen ? 'green' : 'red'} in ${run.seconds}s: ${check}`);if (!run.isGreen) io.say(digestOf(run.output).replace(/^/gm, ' '));diff --git a/src/gate.js b/src/gate.jsindex 8fa76b34..ff91eccb 100644--- a/src/gate.js+++ b/src/gate.js@@ -1,5 +1,5 @@/**- * The gate (V4, C3): the repo's own check command, run before submit and before every push. A green+ * The gate (V4, C3, Q1, Q2, V18): the repo's check command and shared queue for gates and item checks. A green* run over a committed tree, with nothing untracked and nothing changed while it ran, leaves that* tree's id in the git dir, so the same tree is never checked twice. An agent sees a digest of the* run, not the run (V10): a passing suite's output costs tokens and says nothing.@@ -100,6 +100,34 @@ export function runShell(root, command) {return { isGreen: result.status === 0, output: `${result.stdout ?? ''}${result.stderr ?? ''}`, seconds: Math.round((Date.now() - started) / 1000) };}+/** Run work under the machine gate queue, keeping landing gates ahead of ordinary gates and item checks last.+ *+ * @param {string} root - Checkout used to locate the machine resource database.+ * @param {() => any | Promise<any>} action - Work to perform while holding a slot.+ * @param {{ landing?: boolean, itemCheck?: boolean, onWait?: (state: object) => void }} [options] - Queue class and progress reporter.+ * @returns {Promise<any>} The action's result after releasing its lease.+ */+export async function withGateSlot(root, action, { landing = false, itemCheck = false, onWait } = {}) {+ const capacityProvider = () => loadMachineSettings().gateSlots;+ const lease = await takeResource({+ name: 'gate',+ capacity: capacityProvider(),+ capacityProvider,+ scope: 'machine',+ root,+ repo: root,+ landing,+ itemCheck,+ allowIdleCapacityUpdate: true,+ onWait,+ });+ try {+ return await action();+ } finally {+ lease.release();+ }+}+/*** Run the configured gate in the repo, unless this exact tree already passed. Its output, both* streams in order, is kept whole in the git dir and returned for a digest.@@ -118,19 +146,7 @@ export async function runGate(root, config, { trustStamp = true, onWait, landingthrow new Refused('NO_GATE', 'no gate configured; set "gate" in pullboard.json, e.g. "npm test"');}if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };- const capacityProvider = () => loadMachineSettings().gateSlots;- const lease = await takeResource({- name: 'gate',- capacity: capacityProvider(),- capacityProvider,- scope: 'machine',- root,- repo: root,- landing,- allowIdleCapacityUpdate: true,- onWait,- });- try {+ return await withGateSlot(root, () => {if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };const before = committedTree(root);const { isGreen, output, seconds } = runShell(root, config.gate);@@ -140,9 +156,7 @@ export async function runGate(root, config, { trustStamp = true, onWait, landingwriteFileSync(gitPath(root, STAMP), `${before}\n`);}return { isGreen, isCached: false, output, seconds, log };- } finally {- lease.release();- }+ }, { landing, onWait });}/**diff --git a/src/resources.js b/src/resources.jsindex 47116d7c..8c1beff7 100644--- a/src/resources.js+++ b/src/resources.js@@ -1,4 +1,4 @@-/** Local machine and repository resource queues with SQLite-backed leases [Q1,Q2,Q3]. */+/** Machine and repository queues persist leases; landings, gates, and item checks run by priority [Q1,Q2,Q3,V18]. */import { mkdirSync } from 'node:fs';import { execFileSync } from 'node:child_process';import { homedir } from 'node:os';@@ -32,14 +32,15 @@ function open(file) {db.exec('BEGIN IMMEDIATE');transaction = true;db.exec(`CREATE TABLE IF NOT EXISTS resource (name TEXT PRIMARY KEY, capacity INTEGER NOT NULL);- CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0);+ CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS holder_name ON holder(name);- CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0);+ CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS waiter_name_ticket ON waiter(name, ticket);`);for (const table of ['holder', 'waiter']) {const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(({ name }) => name);if (!columns.includes('started')) db.exec(`ALTER TABLE ${table} ADD COLUMN started TEXT NOT NULL DEFAULT ''`);if (!columns.includes('landing')) db.exec(`ALTER TABLE ${table} ADD COLUMN landing INTEGER NOT NULL DEFAULT 0`);+ if (!columns.includes('item_check')) db.exec(`ALTER TABLE ${table} ADD COLUMN item_check INTEGER NOT NULL DEFAULT 0`);}db.exec('COMMIT');transaction = false;@@ -125,18 +126,18 @@ function update(db, action) {}}-/** Current holders and the landing-first line, with FIFO within each class. */+/** Current holders and the landing-first line, then ordinary gates, then item checks. */function snapshot(db, name) {- const holders = db.prepare('SELECT agent, repo, since, landing FROM holder WHERE name = ? ORDER BY since, token').all(name)- .map((holder) => ({ ...holder, landing: holder.landing === 1 }));- const line = db.prepare('SELECT agent, repo, since, landing FROM waiter WHERE name = ? ORDER BY landing DESC, ticket').all(name)- .map((waiter) => ({ ...waiter, landing: waiter.landing === 1 }));+ const holders = db.prepare('SELECT agent, repo, since, landing, item_check AS itemCheck FROM holder WHERE name = ? ORDER BY since, token').all(name)+ .map((holder) => ({ ...holder, landing: holder.landing === 1, itemCheck: holder.itemCheck === 1 }));+ const line = db.prepare('SELECT agent, repo, since, landing, item_check AS itemCheck FROM waiter WHERE name = ? ORDER BY landing DESC, item_check, ticket').all(name)+ .map((waiter) => ({ ...waiter, landing: waiter.landing === 1, itemCheck: waiter.itemCheck === 1 }));return { holders, line };}-/** Count eligible waiters ahead of a ticket; a run holding a slot cannot monopolize a landing. */+/** Count eligible waiters ahead of a ticket by priority and FIFO order; a holder cannot monopolize a landing. */function waiterPosition(db, name, ticket) {- const waiters = db.prepare('SELECT ticket, pid, agent, repo, landing FROM waiter WHERE name = ? ORDER BY ticket').all(name);+ const waiters = db.prepare('SELECT ticket, pid, agent, repo, landing, item_check AS itemCheck FROM waiter WHERE name = ? ORDER BY ticket').all(name);const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(name);/** A live process owns its leases even if it changes descriptive agent or repository labels. */const holdsSlot = (waiter) => holders.some((holder) => holder.pid === waiter.pid);@@ -148,25 +149,28 @@ function waiterPosition(db, name, ticket) {if (!current) return eligible.length + 1;const currentIndex = eligible.findIndex((waiter) => waiter.ticket === ticket);if (currentIndex < 0) return Math.max(2, eligible.length + 1);- if (current.landing === 1) return eligible.slice(0, currentIndex + 1).filter((waiter) => waiter.landing === 1).length;- const landings = eligible.filter((waiter) => waiter.landing === 1).length;- const earlierOrdinary = eligible.filter((waiter) => waiter.landing !== 1 && waiter.ticket <= ticket).length;- return landings + earlierOrdinary;+ /** Map queue entries to their declared precedence class. */+ const rank = (waiter) => waiter.landing === 1 ? 0 : waiter.itemCheck === 1 ? 2 : 1;+ const currentRank = rank(current);+ return eligible.filter((waiter) => rank(waiter) < currentRank || (rank(waiter) === currentRank && waiter.ticket <= ticket)).length;}/** Pause briefly between durable queue checks. */function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); }/**- * Join a resource's FIFO queue and resolve with a renewable lease when capacity is available.+ * Join the queue, preserving FIFO within landing, ordinary-gate, and item-check classes.*- * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.* @returns {Promise<{ name: string, scope: string, token: string, release: () => void, renew: () => void }>}*/export async function takeResource(options) {const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;if (typeof name !== 'string' || !name.trim() || name.trim() !== name) throw new Refused('BAD_RESOURCE_NAME', 'resource name must be nonempty trimmed text');if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');+ const landing = options.landing === true;+ const itemCheck = options.itemCheck === true;+ if (landing && itemCheck) throw new Refused('BAD_RESOURCE_PRIORITY', 'a gate slot cannot be both a landing and an item check');const file = databaseFile(scope, root);const db = open(file);const token = randomUUID();@@ -174,7 +178,6 @@ export async function takeResource(options) {const agent = options.agent ?? process.env.PULLBOARD_AGENT ?? `pid-${pid}`;const started = processStarted(pid);const repo = options.repo ?? repoRoot(root);- const landing = options.landing === true;let queuedAt = new Date().toISOString();try {update(db, () => {@@ -189,15 +192,15 @@ export async function takeResource(options) {db.prepare('UPDATE resource SET capacity = ? WHERE name = ?').run(currentCapacity, name);}db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO NOTHING').run(name, currentCapacity);- db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing));+ db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck));});while (true) {const acquired = update(db, () => {- const waiter = db.prepare('SELECT ticket, landing FROM waiter WHERE token = ?').get(token);+ const waiter = db.prepare('SELECT ticket, landing, item_check AS itemCheck FROM waiter WHERE token = ?').get(token);if (!waiter) {queuedAt = new Date().toISOString();- db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing));- return { acquired: false, state: { ...snapshot(db, name), position: db.prepare('SELECT count(*) AS count FROM waiter WHERE name = ?').get(name).count, rejoined: true } };+ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck));+ return { acquired: false, state: { ...snapshot(db, name), position: waiterPosition(db, name, Number(rejoined.lastInsertRowid)), rejoined: true } };}db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);const spot = snapshot(db, name);@@ -206,7 +209,7 @@ export async function takeResource(options) {if (position === 1 && spot.holders.length < limit) {db.prepare('DELETE FROM waiter WHERE token = ?').run(token);const acquiredAt = new Date().toISOString();- db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing));+ db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck));return { acquired: true, state: { ...spot, position: 0 } };}return { acquired: false, state: { ...spot, position } };diff --git a/test/gate-resource.test.js b/test/gate-resource.test.jsindex a36149ea..484d841d 100644--- a/test/gate-resource.test.js+++ b/test/gate-resource.test.js@@ -1,7 +1,7 @@-/** Real CLI gate processes share the machine FIFO, skip cached trees and release after a crash [Q4,O5,O6]. */+/** Real gates and item checks share the machine queue; landing priority and lease behavior stay intact [Q1,Q2,Q4,O5,O6,V18]. */import assert from 'node:assert/strict';import { spawn, spawnSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { after, test } from 'node:test';@@ -47,8 +47,8 @@ function gateRepo(box, name, delay = 0.25, releaseFile = null) {}/** Launch a real gate CLI in its own process group and collect its output. */-function launch(box, root) {- const child = spawn(process.execPath, [BIN, 'gate'], { cwd: root, env: box.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+function launch(box, root, args = ['gate']) {+ const child = spawn(process.execPath, [BIN, ...args], { cwd: root, env: box.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });child.stdoutText = '';child.stderrText = '';child.stdout.setEncoding('utf8');@@ -63,6 +63,38 @@ function launch(box, root) {return child;}+/** Create a real claimed item with a failing-at-baseline check that leaves an execution marker. */+function checkProject(box) {+ const root = join(box.dir, 'check-project');+ const runner = join(box.dir, 'check-runner');+ const script = join(box.dir, 'item-check.cjs');+ const shims = join(box.dir, 'bin');+ mkdirSync(shims);+ writeFileSync(join(shims, 'pullboard'), `#!/bin/sh\nexec "${process.execPath}" "${BIN}" "$@"\n`);+ chmodSync(join(shims, 'pullboard'), 0o755);+ box.env.PATH = `${shims}:${box.env.PATH}`;+ mkdirSync(root);+ assert.equal(spawnSync('git', ['init', '-q', '-b', 'main'], { cwd: root, env: box.env }).status, 0);+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({+ gate: 'true',+ lanes: { web: { owns: ['web/'], specs: ['G1'] }, api: { owns: ['api/'], specs: ['G2'] } },+ }));+ writeFileSync(join(root, 'SPEC.md'), '# Queue fixture\n\n## G · Goals\n- G1 [approved, must] The check runs. | gate: test -f web/result.txt\n- G2 [approved, must] The API responds. | gate: test -f api/result.txt\n');+ assert.equal(spawnSync('git', ['add', '-A'], { cwd: root, env: box.env }).status, 0);+ assert.equal(spawnSync('git', ['commit', '-q', '-m', 'chore: queue fixture'], { cwd: root, env: box.env }).status, 0);+ const initialized = spawnSync(process.execPath, [BIN, 'init'], { cwd: root, env: box.env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.stderr);+ assert.equal(spawnSync('git', ['worktree', 'add', '-q', runner, '-b', 'web/runner'], { cwd: root, env: box.env }).status, 0);+ const joined = spawnSync(process.execPath, [BIN, 'join', 'web'], { cwd: runner, env: box.env, encoding: 'utf8' });+ assert.equal(joined.status, 0, joined.stderr);+ writeFileSync(script, `const fs = require('node:fs'); fs.appendFileSync(${JSON.stringify(box.events)}, 'item check\\n'); process.exitCode = fs.existsSync('web/result.txt') ? 0 : 1;\n`);+ const added = spawnSync(process.execPath, [BIN, 'add', 'web', 'Check item', '--specs', 'G1', '--route', 'light', '--criterion', 'the item check runs', '--check', `node '${script}'`, '--brief', 'Files: web/result.txt\nTest: run the item check and observe its result.'], { cwd: root, env: box.env, encoding: 'utf8' });+ assert.equal(added.status, 0, added.stderr);+ assert.equal(spawnSync(process.execPath, [BIN, 'claim', '1'], { cwd: runner, env: box.env }).status, 0);+ writeFileSync(box.events, '');+ return { root, runner };+}+/** Wait until an observable fixture state is reached, or fail with a useful timeout. */async function waitFor(predicate, description, timeoutMs = 30_000) {const until = Date.now() + timeoutMs;@@ -162,3 +194,71 @@ test('[Q4] SIGKILL during a gate releases its machine slot for the next process'assert.equal(result.code, 0, next.stderrText);assert.ok(events(box).includes('next start'));});++test('[Q1,Q2,V18] item checks wait for a gate slot and ordinary gates precede them', async () => {+ const box = fixture();+ const release = join(box.dir, 'release-holder');+ const firstRoot = gateRepo(box, 'slot-holder', 0.1, release);+ const nextRoot = gateRepo(box, 'ordinary-gate', 0.15);+ const { root, runner } = checkProject(box);+ assert.equal(spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '1'], { cwd: firstRoot, env: box.env }).status, 0);++ const first = launch(box, firstRoot);+ await waitFor(() => events(box).includes('slot-holder start') && !events(box).includes('slot-holder end'), 'the first gate to hold the only slot');+ const check = launch(box, runner, ['check', '1', '--yes']);+ await waitFor(() => check.stdoutText.includes('place 1') || check.exitCode !== null, 'the item check to queue behind the running gate');+ assert.ok(check.stdoutText.includes('place 1'), 'the item check prints its queued gate-slot position');+ assert.match(check.stdoutText, /gate waiting:/);+ assert.deepEqual(events(box), ['slot-holder start'], 'the item check command has not started while the gate holds the slot');+ const ordinary = launch(box, nextRoot);+ await waitFor(() => /place [12]/u.test(ordinary.stdoutText), 'the later ordinary gate to enter the queue');+ assert.ok(ordinary.stdoutText.includes('place 1'), 'the ordinary gate is granted priority over the queued item check');+ assert.deepEqual(events(box), ['slot-holder start'], 'neither queued command runs before the holder releases');++ writeFileSync(release, 'release\n');+ await waitFor(() => events(box).includes('ordinary-gate start'), 'the waiting ordinary gate to acquire the released slot');+ assert.equal(events(box).includes('item check'), false, 'the ordinary gate starts before the lower-priority item check');+ await waitFor(() => events(box).includes('ordinary-gate end'), 'the ordinary gate to finish');+ const [firstResult, ordinaryResult, checkResult] = await Promise.all([first.closed, ordinary.closed, check.closed]);+ assert.equal(firstResult.code, 0);+ assert.equal(ordinaryResult.code, 0, ordinary.stderrText);+ assert.equal(checkResult.code, 1, check.stderrText);+ assert.deepEqual(events(box), ['slot-holder start', 'slot-holder end', 'ordinary-gate start', 'ordinary-gate end', 'item check']);++ mkdirSync(join(runner, 'web'));+ writeFileSync(join(runner, 'web', 'result.txt'), 'ready\n');+ assert.equal(spawnSync('git', ['add', 'web/result.txt'], { cwd: runner, env: box.env }).status, 0);+ const commit = spawnSync('git', ['commit', '-q', '-m', 'feat(web): queue item proof [G1]'], { cwd: runner, env: box.env, encoding: 'utf8' });+ assert.equal(commit.status, 0, commit.stderr);+ const submitted = spawnSync(process.execPath, [BIN, 'submit', '1'], { cwd: runner, env: box.env, encoding: 'utf8' });+ assert.equal(submitted.status, 0, submitted.stderr);+ const review = join(box.dir, 'check-review');+ const itemCommit = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: runner, env: box.env, encoding: 'utf8' }).stdout.trim();+ assert.equal(spawnSync('git', ['worktree', 'add', '-q', '--detach', review, itemCommit], { cwd: root, env: box.env }).status, 0);+ const reviewer = spawnSync(process.execPath, [BIN, 'join', 'api'], { cwd: review, env: box.env, encoding: 'utf8' });+ assert.equal(reviewer.status, 0, reviewer.stderr);++ writeFileSync(box.events, '');+ const verifyRelease = join(box.dir, 'release-verify-holder');+ const verifyHolderRoot = gateRepo(box, 'verify-holder', 0.1, verifyRelease);+ const verifyNextRoot = gateRepo(box, 'verify-next-gate', 0.15);+ const verifyHolder = launch(box, verifyHolderRoot);+ await waitFor(() => events(box).includes('verify-holder start') && !events(box).includes('verify-holder end'), 'a gate to hold the slot before accepting an item');+ const verify = launch(box, review, ['verify', '1', 'accept', '--note', 'queue fixture']);+ await waitFor(() => verify.stdoutText.includes('place 1') || verify.exitCode !== null, 'verify accept to queue for the gate slot');+ assert.ok(verify.stdoutText.includes('place 1'), 'verify accept prints its queued gate-slot position');+ assert.match(verify.stdoutText, /gate waiting:/);+ const verifyNext = launch(box, verifyNextRoot);+ await waitFor(() => /place [12]/u.test(verifyNext.stdoutText), 'the ordinary gate to enter the queue ahead of accept');+ assert.ok(verifyNext.stdoutText.includes('place 1'), 'the ordinary gate is granted priority over the queued accept check');+ assert.equal(events(box).includes('item check'), false);+ writeFileSync(verifyRelease, 'release\n');+ await waitFor(() => events(box).includes('verify-next-gate start'), 'the waiting ordinary gate to acquire before accept');+ assert.equal(events(box).includes('item check'), false);+ await waitFor(() => events(box).includes('verify-next-gate end'), 'the ordinary gate before accept to finish');+ const [verifyHolderResult, verifyNextResult, verifyResult] = await Promise.all([verifyHolder.closed, verifyNext.closed, verify.closed]);+ assert.equal(verifyHolderResult.code, 0);+ assert.equal(verifyNextResult.code, 0, verifyNext.stderrText);+ assert.equal(verifyResult.code, 0, `${verify.stderrText}${verify.stdoutText}`);+ assert.deepEqual(events(box), ['verify-holder start', 'verify-holder end', 'verify-next-gate start', 'verify-next-gate end', 'item check']);+});