Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(core): prioritize landing gates [Q1,Q2]
Corey Olsonec339479cfcb
diff --git a/src/cli.js b/src/cli.jsindex a7758a93..6042cda1 100644--- a/src/cli.js+++ b/src/cli.js@@ -22,6 +22,7 @@ import {installHooks,preCommitProblems,prePushProblems,+ pushesTrunk,} from './hooks.js';import { initRepo } from './init.js';import { lifecycleHelp, lifecycleMarkdown } from './machine.js';@@ -170,7 +171,7 @@ Role guidespullboard prompt decompose|plan|signoff|review|verify how to do each role; Claude Code gets them as skillsGate and hooks- pullboard gate run the configured gate+ pullboard gate [--landing] run the configured gate; prioritize a trunk landing in the machine queuepullboard hook pre-commit|commit-msg|pre-push git runs these${lifecycleHelp()}@@ -240,6 +241,7 @@ const HELP_FLAG_EXPLANATIONS = {'--brief': 'what a cold agent needs','--check': 'the command that proves it','--family': 'records the family name',+ '--landing': 'prioritizes a trunk landing in the machine gate queue','--json': 'prints one versioned document','--note': 'what was checked stays with the receipt','--note-file': 'keeps quotes, $ and backticks intact',@@ -407,6 +409,7 @@ const OPTIONS = {as: { type: 'string' },check: { type: 'string' },yes: { type: 'boolean' },+ landing: { type: 'boolean' },agent: { type: 'string' },'agent-light': { type: 'string' },'agent-mid': { type: 'string' },@@ -1201,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}` : ''} since ${holder.since}`);- resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${waiter.agent}${waiter.repo ? ` in ${waiter.repo}` : ''}`));+ 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)' : ''}`));}return 0;},@@ -2309,9 +2312,11 @@ async function hookCommand(io, { first, second }) {const message = readFileSync(second ?? '', 'utf8');problems = commitMsgProblems(message, { rules: ctx.config.commits, spec: loadSpec(info.root, ctx.config) });} else if (first === 'pre-push') {- problems = prePushProblems(info.root, await readStdin(io.stdin));+ const refsText = await readStdin(io.stdin);+ problems = prePushProblems(info.root, refsText);if (!problems.length) {- const gate = await runGate(info.root, ctx.config, { onWait: gateWaitReporter(io) });+ const landing = pushesTrunk(refsText, trunkRef(info.root));+ const gate = await runGate(info.root, ctx.config, { landing, onWait: gateWaitReporter(io) });if (gate.isCached) io.say('pre-push: the gate passed on this exact tree; not running it twice');if (!gate.isGreen) problems = [`the gate is red; fix it before pushing. ${gateReport(gate)}`];}@@ -2400,7 +2405,7 @@ async function runCommand(argv, io) {}if (command === 'gate') {const ctx = context(io);- const gate = await runGate(ctx.info.root, mainPolicy(ctx.info.root).config, { onWait: gateWaitReporter(io) });+ const gate = await runGate(ctx.info.root, mainPolicy(ctx.info.root).config, { landing: values.landing, onWait: gateWaitReporter(io) });io.result?.({ green: gate.isGreen, report: gateReport(gate) });io.say(gateReport(gate));return gate.isGreen ? 0 : 1;diff --git a/src/gate.js b/src/gate.jsindex be8bc1b6..8fa76b34 100644--- a/src/gate.js+++ b/src/gate.js@@ -110,10 +110,10 @@ export function runShell(root, command) {** @param {string} root* @param {any} config- * @param {{ trustStamp?: boolean, onWait?: (state: object) => void }} [options]+ * @param {{ trustStamp?: boolean, onWait?: (state: object) => void, landing?: boolean }} [options]* @returns {Promise<{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string }>}*/-export async function runGate(root, config, { trustStamp = true, onWait } = {}) {+export async function runGate(root, config, { trustStamp = true, onWait, landing = false } = {}) {if (!config.gate.trim()) {throw new Refused('NO_GATE', 'no gate configured; set "gate" in pullboard.json, e.g. "npm test"');}@@ -126,6 +126,7 @@ export async function runGate(root, config, { trustStamp = true, onWait } = {})scope: 'machine',root,repo: root,+ landing,allowIdleCapacityUpdate: true,onWait,});diff --git a/src/hooks.js b/src/hooks.jsindex 9d1e2a25..d198e0c2 100644--- a/src/hooks.js+++ b/src/hooks.js@@ -375,6 +375,16 @@ export function prePushProblems(root, refsText) {return problems;}+/** Whether Git's pre-push updates advance the configured trunk rather than another remote branch. */+export function pushesTrunk(refsText, trunk) {+ if (!trunk) return false;+ const remoteTrunk = trunk.startsWith('refs/heads/') ? trunk : `refs/heads/${trunk}`;+ return refsText.split('\n').some((line) => {+ const [, localSha = '', remoteRef = ''] = line.trim().split(/\s+/u);+ return remoteRef === remoteTrunk && !ZERO_SHA.test(localSha);+ });+}+/*** The shell script for one hook: it runs pullboard from this checkout's install, else the main* checkout's, which a fresh agent worktree shares, else the PATH.diff --git a/src/resources.js b/src/resources.jsindex 6a56da81..9973b7a0 100644--- a/src/resources.js+++ b/src/resources.js@@ -32,13 +32,14 @@ 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);+ 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 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);+ 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 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`);}db.exec('COMMIT');transaction = false;@@ -126,18 +127,38 @@ function update(db, action) {/** Current holders and FIFO line for one resource. */function snapshot(db, name) {- const holders = db.prepare('SELECT agent, repo, since FROM holder WHERE name = ? ORDER BY since, token').all(name);- const line = db.prepare('SELECT agent, repo, since FROM waiter WHERE name = ? ORDER BY ticket').all(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 }));return { holders, line };}+/** Count eligible waiters ahead of a ticket; a run holding a slot 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 holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(name);+ const holdsSlot = (waiter) => holders.some((holder) => holder.pid === waiter.pid && holder.agent === waiter.agent && holder.repo === waiter.repo);+ const blockedByLanding = (waiter) => holdsSlot(waiter)+ && waiters.some((other) => other.landing === 1 && other.pid !== waiter.pid);+ const eligible = waiters.filter((waiter) => !blockedByLanding(waiter));+ const current = waiters.find((waiter) => waiter.ticket === ticket);+ if (!current) return eligible.length + 1;+ const currentIndex = eligible.findIndex((waiter) => waiter.ticket === ticket);+ if (currentIndex < 0) return 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;+}+/** 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.*- * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, 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, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options* @returns {Promise<{ name: string, scope: string, token: string, release: () => void, renew: () => void }>}*/export async function takeResource(options) {@@ -151,6 +172,7 @@ 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, () => {@@ -165,24 +187,24 @@ 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) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now());+ 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));});while (true) {const acquired = update(db, () => {- const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);+ const waiter = db.prepare('SELECT ticket, landing 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) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now());+ 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 } };}db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);const spot = snapshot(db, name);- const position = db.prepare('SELECT count(*) AS count FROM waiter WHERE name = ? AND ticket <= ?').get(name, waiter.ticket).count;+ const position = waiterPosition(db, name, waiter.ticket);const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;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) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now());+ 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));return { acquired: true, state: { ...spot, position: 0 } };}return { acquired: false, state: { ...spot, position } };diff --git a/test/e2e.test.js b/test/e2e.test.jsindex 618032be..a2546cdd 100644--- a/test/e2e.test.js+++ b/test/e2e.test.js@@ -426,6 +426,88 @@ test('pre-push keeps its machine gate slot until the hook check finishes [C3,Q4]}});+test('explicit and trunk pre-push landings jump the machine gate line and show in resources [Q1,Q2]', async () => {+ const box = sandbox();+ const gate = holdingGate(box);+ const projectBox = project(gate.command, box);+ assert.equal(projectBox.run(projectBox.repo, 'settings', 'gateSlots', '1').code, 0);+ writeFileSync(gate.mode, 'armed');++ const ordinary = launch(projectBox, projectBox.repo, process.execPath, [BIN, 'gate']);+ const children = [ordinary];+ let explicitLanding;+ try {+ await waitFor(() => gateEvents(gate).length === 1, 'ordinary gate to hold the sole machine slot');+ explicitLanding = launch(projectBox, projectBox.web, process.execPath, [BIN, 'gate', '--landing']);+ children.push(explicitLanding);+ let latestResources = '';+ await waitFor(() => {+ const result = projectBox.run(projectBox.repo, 'resources', '--json');+ assert.equal(result.code, 0, result.err);+ latestResources = result.out;+ const resource = JSON.parse(result.out).resources.find((entry) => entry.scope === 'machine' && entry.name === 'gate');+ return resource?.line.length > 0;+ }, 'explicit gate run to appear in the resource listing').catch((error) => {+ throw new Error(`${error.message}\nresources: ${latestResources}\nlanding stdout: ${explicitLanding.stdoutText}\nlanding stderr: ${explicitLanding.stderrText}\nevents: ${gateEvents(gate).join(',')}`);+ });+ const json = projectBox.run(projectBox.repo, 'resources', '--json');+ assert.equal(json.code, 0, json.err);+ const queued = JSON.parse(json.out).resources.find((resource) => resource.scope === 'machine' && resource.name === 'gate');+ assert.deepEqual(queued.line.map(({ landing }) => landing), [true]);+ const humanQueue = projectBox.run(projectBox.repo, 'resources');+ assert.equal(humanQueue.code, 0, humanQueue.err);+ assert.match(humanQueue.out, /waiting: .* \(landing\)/u);+ writeFileSync(gate.release, 'released');+ const results = await Promise.all(children.map((child) => child.closed));+ assert.deepEqual(results.map(({ code }) => code), [0, 0]);+ assert.deepEqual(gateEvents(gate), ['start', 'end', 'start', 'end']);+ } finally {+ writeFileSync(gate.release, 'released');+ await Promise.all(children.map((child) => child.closed));+ }++ const pushBox = sandbox();+ const pushGate = holdingGate(pushBox);+ const pushProject = project(pushGate.command, pushBox);+ const remote = join(pushBox.dir, 'remote.git');+ pushProject.git(pushBox.dir, 'init', '-q', '--bare', remote);+ pushProject.git(pushProject.repo, 'remote', 'add', 'origin', remote);+ assert.equal(pushProject.run(pushProject.repo, 'settings', 'gateSlots', '1').code, 0);+ writeFileSync(pushGate.mode, 'armed');+ const holder = launch(pushProject, pushProject.web, process.execPath, [BIN, 'gate']);+ const pushChildren = [holder];+ let push;+ try {+ await waitFor(() => gateEvents(pushGate).length === 1, 'gate holder to start before trunk push');+ push = launch(pushProject, pushProject.repo, 'git', ['push', '-q', 'origin', 'main']);+ pushChildren.push(push);+ let latestPushResources = '';+ await waitFor(() => {+ const result = pushProject.run(pushProject.repo, 'resources', '--json');+ assert.equal(result.code, 0, result.err);+ latestPushResources = result.out;+ const resource = JSON.parse(result.out).resources.find((entry) => entry.scope === 'machine' && entry.name === 'gate');+ return resource?.line.length > 0;+ }, 'trunk pre-push gate to appear in the resource listing').catch((error) => {+ throw new Error(`${error.message}\nresources: ${latestPushResources}\npush stdout: ${push.stdoutText}\npush stderr: ${push.stderrText}\nevents: ${gateEvents(pushGate).join(',')}`);+ });+ const json = pushProject.run(pushProject.repo, 'resources', '--json');+ assert.equal(json.code, 0, json.err);+ const queued = JSON.parse(json.out).resources.find((resource) => resource.scope === 'machine' && resource.name === 'gate');+ assert.deepEqual(queued.line.map(({ landing }) => landing), [true], 'the hook marks its trunk update as a landing');+ const humanQueue = pushProject.run(pushProject.repo, 'resources');+ assert.equal(humanQueue.code, 0, humanQueue.err);+ assert.match(humanQueue.out, /waiting: .* \(landing\)/u);+ writeFileSync(pushGate.release, 'released');+ const results = await Promise.all(pushChildren.map((child) => child.closed));+ assert.deepEqual(results.map(({ code }) => code), [0, 0]);+ assert.deepEqual(gateEvents(pushGate), ['start', 'end', 'start', 'end']);+ } finally {+ writeFileSync(pushGate.release, 'released');+ await Promise.all(pushChildren.map((child) => child.closed));+ }+});+test('decisions are asked, listed and answered, and evidence attached, from the command line [B21, B22, B26]', () => {const box = project();box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1');diff --git a/test/resources.test.js b/test/resources.test.jsindex 61cb5f90..47207d00 100644--- a/test/resources.test.js+++ b/test/resources.test.js@@ -20,9 +20,9 @@ const SANDBOX_EXEC = process.platform === 'darwin' && existsSync('/usr/bin/sandbconst PERL_FORK = process.platform === 'darwin' && existsSync('/usr/bin/perl');const WORKER = `import { takeResource } from ${JSON.stringify(MODULE)};-const [name, capacity, scope, root, agent, stallMs] = process.argv.slice(1);+const [name, capacity, scope, root, agent, stallMs, landingText] = process.argv.slice(1);let lastWait = '';-const lease = await takeResource({ name, capacity: Number(capacity), scope, root, agent, onWait: ({position, holders, line, rejoined}) => {+const lease = await takeResource({ name, capacity: Number(capacity), scope, root, agent, landing: landingText === 'true', onWait: ({position, holders, line, rejoined}) => {const state = JSON.stringify({waiting:position, holders, line, rejoined:rejoined ?? false});if (!lastWait || rejoined) { lastWait = state; console.log(state); }} });@@ -101,8 +101,8 @@ function privateList(box, scope = 'machine', root = process.cwd()) {}/** 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, env = {}, sandboxProcessInfo = false }) {- const workerArgs = ['--input-type=module', '-e', WORKER, name, String(capacity), scope, root, agent, String(stallMs)];+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)];const executable = sandboxProcessInfo ? '/usr/bin/sandbox-exec' : process.execPath;const args = sandboxProcessInfo ? ['-p', PROCESS_INFO_POLICY, process.execPath, ...workerArgs] : workerArgs;const child = spawn(executable, args, {@@ -177,6 +177,16 @@ async function waitForProcessState(pid, state, timeoutMs = 5_000) {/** Sleep without blocking the test runner event loop. */function delay(ms) { return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); }+/** Wait for one private queue observation without imposing a longer lease or gate timeout. */+async function waitUntil(predicate, description, timeoutMs = 5_000) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await delay(20);+ }+ assert.fail(`timed out waiting for ${description}`);+}+/** Add an expired holder row to a private fixture database. */function insertExpiredHolder(box, { name, pid, agent, started = '' }) {const db = new DatabaseSync(join(box.home, 'resources.sqlite'));@@ -238,6 +248,144 @@ test('[Q1,Q2] capacity-one takers acquire in strict FIFO arrival order', async (assert.deepEqual(order, ['first', 'second', 'third']);});+test('[Q1,Q2] landing waiters jump ordinary gates but keep FIFO within each class [Q1,Q2]', async () => {+ const box = fixture();+ const holder = worker(box, { agent: 'holder' });+ assert.equal((await event(holder)).acquired, 'holder');+ const ordinaryFirst = worker(box, { agent: 'ordinary-first' });+ assert.equal((await event(ordinaryFirst)).waiting, 1);+ const landingFirst = worker(box, { agent: 'landing-first', landing: true });+ assert.equal((await event(landingFirst)).waiting, 1);+ const ordinarySecond = worker(box, { agent: 'ordinary-second' });+ assert.equal((await event(ordinarySecond)).waiting, 3);+ const landingSecond = worker(box, { agent: 'landing-second', landing: true });+ assert.equal((await event(landingSecond)).waiting, 2);+ const listed = privateList(box)[0].line;+ assert.deepEqual(listed.map(({ agent, landing }) => [agent, landing]), [+ ['landing-first', true], ['landing-second', true], ['ordinary-first', false], ['ordinary-second', false],+ ]);++ await release(holder);+ assert.equal((await event(landingFirst)).acquired, 'landing-first');+ await release(landingFirst);+ assert.equal((await event(landingSecond)).acquired, 'landing-second');+ await release(landingSecond);+ assert.equal((await event(ordinaryFirst)).acquired, 'ordinary-first');+ await release(ordinaryFirst);+ assert.equal((await event(ordinarySecond)).acquired, 'ordinary-second');+ await release(ordinarySecond);+});++test('[Q1,Q2] a waiting landing keeps a current holder from taking the second slot [Q1,Q2]', async () => {+ const box = fixture();+ const firstHolder = worker(box, { capacity: 2, agent: 'same-run' });+ const secondHolder = worker(box, { capacity: 2, agent: 'other-run' });+ assert.equal((await acquired(firstHolder)).acquired, 'same-run');+ assert.equal((await acquired(secondHolder)).acquired, 'other-run');+ const landing = worker(box, { capacity: 2, agent: 'landing', landing: true });+ assert.equal((await event(landing)).waiting, 1);+ const secondSlot = worker(box, { capacity: 2, agent: 'same-run' });+ assert.equal((await event(secondSlot)).waiting, 2);+ assert.deepEqual(privateList(box)[0].line.map(({ agent, landing: isLanding }) => [agent, isLanding]), [['landing', true], ['same-run', false]]);++ await release(secondHolder);+ assert.equal((await event(landing)).acquired, 'landing');+ await assert.rejects(event(secondSlot, 250), /worker timed out/u, 'the holder cannot take its second slot ahead of a waiting landing');+ await release(landing);+ assert.equal((await event(secondSlot)).acquired, 'same-run');+ await release(secondSlot);+ await release(firstHolder);+});++test('[Q1,Q2] a holder cannot queue a landing second slot ahead of another landing [Q1,Q2]', async () => {+ const box = fixture();+ const previousHome = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = box.home;+ let first;+ let second;+ let other;+ let landing;+ let extraLease;+ let extraPromise;+ try {+ first = await takeResource({ name: 'gate', capacity: 2, root: box.first, agent: 'same-run' });+ other = worker(box, { capacity: 2, agent: 'other-run' });+ assert.equal((await acquired(other)).acquired, 'other-run');+ extraPromise = takeResource({ name: 'gate', capacity: 2, root: box.first, agent: 'same-run', landing: true })+ .then((lease) => { extraLease = lease; return lease; });+ await waitUntil(() => privateList(box)[0].line.some(({ agent, landing: isLanding }) => agent === 'same-run' && isLanding), 'the same process second slot to queue');++ landing = worker(box, { capacity: 2, agent: 'next-landing', landing: true });+ assert.equal((await event(landing)).waiting, 1, 'the later landing is the first eligible landing');+ assert.deepEqual(privateList(box)[0].line.map(({ agent, landing: isLanding }) => [agent, isLanding]), [+ ['same-run', true], ['next-landing', true],+ ]);++ await release(other);+ other = null;+ assert.equal((await event(landing)).acquired, 'next-landing', 'a current holder cannot take a second slot ahead of a different landing run');+ const holderAgents = privateList(box)[0].holders.map(({ agent }) => agent).sort();+ assert.deepEqual(holderAgents, ['next-landing', 'same-run']);+ await release(landing);+ landing = null;+ second = await extraPromise;+ assert.deepEqual(privateList(box)[0].holders.map(({ agent }) => agent), ['same-run', 'same-run']);+ } finally {+ if (other && !other.exitResult) await release(other);+ if (landing && !landing.exitResult) {+ first?.release();+ extraLease?.release();+ try { await acquired(landing); } catch { /* Preserve the assertion that led to cleanup. */ }+ if (!landing.exitResult) await release(landing);+ }+ first?.release();+ second?.release();+ extraLease?.release();+ if (extraPromise && !extraLease) {+ await Promise.race([extraPromise.then((lease) => lease.release()), delay(500)]);+ }+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ }+});++test('[Q1,Q2] landing priority preserves tickets while an older resource database migrates [Q1,Q2]', async () => {+ const box = fixture();+ oldSchema(box);+ const oldSince = new Date().toISOString();+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));+ try {+ db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?)').run('gate', 1);+ db.prepare('INSERT INTO holder(token, name, pid, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?)')+ .run('old-holder', 'gate', process.pid, 'old-holder', realpathSync(box.first), oldSince, Date.now());+ for (const [ticket, agent] of [[4, 'old-first'], [9, 'old-second']]) {+ db.prepare('INSERT INTO waiter(ticket, token, name, pid, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')+ .run(ticket, `old-${agent}`, 'gate', process.pid, agent, realpathSync(box.first), oldSince, Date.now());+ }+ } finally { db.close(); }++ assert.deepEqual(privateList(box)[0].line.map(({ agent, landing }) => [agent, landing]), [['old-first', false], ['old-second', false]]);+ const migrated = new DatabaseSync(join(box.home, 'resources.sqlite'));+ try {+ assert.deepEqual(migrated.prepare('SELECT ticket, landing FROM waiter ORDER BY ticket').all().map(({ ticket, landing }) => ({ ticket, landing })), [+ { ticket: 4, landing: 0 }, { ticket: 9, landing: 0 },+ ]);+ } finally { migrated.close(); }++ const landing = worker(box, { agent: 'new-landing', landing: true });+ assert.equal((await event(landing)).waiting, 1);+ assert.deepEqual(privateList(box)[0].line.map(({ agent, landing: isLanding }) => [agent, isLanding]), [+ ['new-landing', true], ['old-first', false], ['old-second', false],+ ]);+ const cleanup = new DatabaseSync(join(box.home, 'resources.sqlite'));+ try {+ cleanup.prepare('DELETE FROM waiter WHERE token IN (?, ?)').run('old-old-first', 'old-old-second');+ cleanup.prepare('DELETE FROM holder WHERE token = ?').run('old-holder');+ } finally { cleanup.close(); }+ assert.equal((await event(landing)).acquired, 'new-landing');+ await release(landing);+});+test('[Q1,Q2] capacity two admits two holders and serves the next waiter', async () => {const box = fixture();const first = worker(box, { name: 'two-slots', capacity: 2, agent: 'first-holder' });