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(gate): queue machine gate runs [Q4,O5,O6]

Corey Olsonc71478796bf8
diff --git a/docs/api.md b/docs/api.md
index 15138f89..5635dae1 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -8,6 +8,8 @@ Decision shouts without a recipient go to the agent's coordinator, or to `person
A successful command returns the fields listed below. `version` is always the number `1`. The catalog lists required top-level fields; nested objects and arrays are command data, and optional top-level fields may be added.
+`pullboard settings` reads machine-wide settings from `~/.pullboard/settings.json`; `pullboard settings gateSlots <n>` changes the gate queue capacity, which defaults to `2`. Capacity changes are refused while a gate is running or waiting, so existing holders and FIFO order remain intact.
+
<!-- api-command-shapes:start -->
| Command | Required top-level fields |
| --- | --- |
@@ -21,6 +23,7 @@ A successful command returns the fields listed below. `version` is always the nu
| `whoami` | `version:number`, `id:string`, `lane:string`, `path:string` |
| `lanes` | `version:number`, `lanes:object`, `shared:array`, `coordinator:string` |
| `resources` | `version:number`, `resources:array` |
+| `settings` | `version:number`, `settings:object` |
| `list` | `version:number`, `items:array` |
| `show` | `version:number`, `item_id:number`, `item_title:string`, `item_lane:string`, `item_status:string`, `verdicts:array` |
| `status` | `version:number`, `me:object`, `mine:array`, `stats:object`, `unread:number` |
diff --git a/src/cli.js b/src/cli.js
index d9fc60d3..e83903c4 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -51,6 +51,7 @@ import { serveView } from './serve.js';
import { serveApi } from './api.js';
import { doctorProblems } from './doctor.js';
import { exportBoard, importBoard } from './exchange.js';
+import { loadMachineSettings, setGateSlots } from './settings.js';
const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
export const VERSION = PACKAGE.version;
@@ -66,6 +67,7 @@ Set up
--route sets which work the model can take; --family records its name
pullboard whoami | lanes | status who you are, the lanes, the board at a glance
pullboard resources local resource holders and their FIFO queues
+ pullboard settings [gateSlots <n>] view or set this machine's gate slots (default 2)
pullboard view [--port N] [--no-open] every project on this machine in your browser: items, shouts, doctrine,
agents and activity, live; add items, shout and hold lanes from it
pullboard serve [--port N] local API v1: boards, state, moves, requests and live events,
@@ -1056,9 +1058,9 @@ function readCommands(io, { first, second, rest, values }) {
*
* @param {any} ctx
* @param {number} id
- * @returns {number}
+ * @returns {Promise<number>}
*/
-function submitHere(ctx, id) {
+async function submitHere(ctx, id) {
const { root } = ctx.info;
const { me, claimHead } = withBoard(ctx, (board) => {
const who = whoAmI(ctx, board);
@@ -1094,7 +1096,7 @@ function submitHere(ctx, id) {
// Submit runs the gate itself, every time: a stamp from an earlier run is a file any agent can
// write, so it never stands in for this run (V16). It starts on the commit submitted, and must end
// on it too. What the gate's own code does in between is the submitted tree's, under review.
- const gate = runGate(root, ctx.config, { trustStamp: false });
+ const gate = await runGate(root, ctx.config, { trustStamp: false, onWait: gateWaitReporter(ctx.io) });
if (!gate.isGreen) throw new Refused('GATE_RED', `the gate is red at ${commit.slice(0, 12)}; fix it, commit, submit again. ${gateReport(gate)}`);
if (headCommit(root) !== commit || !isClean(root)) {
throw new Refused(
@@ -1399,8 +1401,8 @@ function workCommands(io, args) {
io.say(review ? `released the review of #${first}; the review is free again` : `released #${first}`);
return 0;
}),
- submit: () => submitHere(context(io), idArg(first)),
- done: () => submitHere(context(io), idArg(first)),
+ submit: async () => submitHere(context(io), idArg(first)),
+ done: async () => submitHere(context(io), idArg(first)),
verify: () => verifyHere(context(io), idArg(first), args),
merged: () => act((ctx, board, me) => {
const commit = resolveCommit(ctx.info.root, second ?? '');
@@ -1455,6 +1457,36 @@ function workCommands(io, args) {
};
}
+/** Build a de-duplicated queue message for a gate waiting on machine capacity. */
+function gateWaitReporter(io) {
+ let last = '';
+ return ({ holders, position }) => {
+ const repos = holders.map(({ repo }) => repo).filter(Boolean);
+ const message = `gate waiting: ${holders.length} running${repos.length ? ` in ${repos.join(', ')}` : ''}; place ${position}`;
+ if (message !== last) {
+ io.say(message);
+ last = message;
+ }
+ };
+}
+
+/** Read or update machine-wide gate capacity. */
+function settingsCommand(io, { first, second, rest }) {
+ if (!first && !second && !rest.length) {
+ const settings = loadMachineSettings();
+ io.result?.({ settings });
+ io.say(`gateSlots: ${settings.gateSlots}`);
+ return 0;
+ }
+ if (first !== 'gateSlots' || !second || rest.length || !/^[1-9]\d*$/u.test(second) || !Number.isSafeInteger(Number(second))) {
+ throw new Refused('USAGE', 'pullboard settings gateSlots <positive integer>');
+ }
+ const settings = setGateSlots(Number(second));
+ io.result?.({ settings });
+ io.say(`gateSlots set to ${settings.gateSlots}`);
+ return 0;
+}
+
/**
* Every spec id something cites (S8): commit headers since the spec's first commit, and every item
* on the board, open or closed. Each must still be in the spec. The board is shared by every
@@ -1648,7 +1680,7 @@ async function hookCommand(io, { first, second }) {
} else if (first === 'pre-push') {
problems = prePushProblems(info.root, await readStdin(io.stdin));
if (!problems.length) {
- const gate = runGate(info.root, ctx.config);
+ const gate = await runGate(info.root, ctx.config, { 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)}`];
}
@@ -1724,9 +1756,10 @@ async function runCommand(argv, io) {
return 0;
}
if (command === 'hook') return await hookCommand(io, args);
+ if (command === 'settings') return settingsCommand(io, args);
if (command === 'gate') {
const ctx = context(io);
- const gate = runGate(ctx.info.root, ctx.config);
+ const gate = await runGate(ctx.info.root, ctx.config, { onWait: gateWaitReporter(io) });
io.result?.({ green: gate.isGreen, report: gateReport(gate) });
io.say(gateReport(gate));
return gate.isGreen ? 0 : 1;
@@ -1763,6 +1796,6 @@ export function resultCommands() {
...Object.keys(setupCommands({}, args)),
...Object.keys(readCommands({}, args)),
...Object.keys(workCommands({}, args)),
- 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'forget', 'spec', 'prompt', 'hook', 'gate',
+ 'help', 'version', 'tour', 'lifecycle', 'view', 'serve', 'forget', 'spec', 'prompt', 'hook', 'gate', 'settings',
])].sort();
}
diff --git a/src/gate.js b/src/gate.js
index a8cf2ee3..be8bc1b6 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -8,6 +8,8 @@ import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { gitChildEnv, gitPath, headTree, isClean, untracked } from './git.js';
import { Refused } from './refused.js';
+import { takeResource } from './resources.js';
+import { loadMachineSettings } from './settings.js';
const STAMP = 'pullboard-gate-green';
const LOG = 'pullboard-gate.log';
@@ -108,22 +110,38 @@ export function runShell(root, command) {
*
* @param {string} root
* @param {any} config
- * @param {{ trustStamp?: boolean }} [options]
- * @returns {{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string }}
+ * @param {{ trustStamp?: boolean, onWait?: (state: object) => void }} [options]
+ * @returns {Promise<{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string }>}
*/
-export function runGate(root, config, { trustStamp = true } = {}) {
+export async function runGate(root, config, { trustStamp = true, onWait } = {}) {
if (!config.gate.trim()) {
throw 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 before = committedTree(root);
- const { isGreen, output, seconds } = runShell(root, config.gate);
- const log = gitPath(root, LOG);
- writeFileSync(log, output);
- if (isGreen && before !== null && committedTree(root) === before) {
- writeFileSync(gitPath(root, STAMP), `${before}\n`);
+ const capacityProvider = () => loadMachineSettings().gateSlots;
+ const lease = await takeResource({
+ name: 'gate',
+ capacity: capacityProvider(),
+ capacityProvider,
+ scope: 'machine',
+ root,
+ repo: root,
+ allowIdleCapacityUpdate: true,
+ onWait,
+ });
+ try {
+ 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);
+ const log = gitPath(root, LOG);
+ writeFileSync(log, output);
+ if (isGreen && before !== null && committedTree(root) === before) {
+ writeFileSync(gitPath(root, STAMP), `${before}\n`);
+ }
+ return { isGreen, isCached: false, output, seconds, log };
+ } finally {
+ lease.release();
}
- return { isGreen, isCached: false, output, seconds, log };
}
/**
diff --git a/src/json.js b/src/json.js
index 8fbb7bfb..9ca70027 100644
--- a/src/json.js
+++ b/src/json.js
@@ -19,6 +19,7 @@ export const JSON_SHAPES = {
whoami: shape({ id: 'string', lane: 'string', path: 'string' }),
lanes: shape({ lanes: 'object', shared: 'array', coordinator: 'string' }),
resources: shape({ resources: 'array' }),
+ settings: shape({ settings: 'object' }),
list: shape({ items: 'array' }),
show: shape({ item_id: 'number', item_title: 'string', item_lane: 'string', item_status: 'string', verdicts: 'array' }),
status: shape({ me: 'object', mine: 'array', stats: 'object', unread: 'number' }),
diff --git a/src/resources.js b/src/resources.js
index d35a8265..6a56da81 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -137,11 +137,11 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr
/**
* Join a resource's FIFO queue and resolve with a renewable lease when capacity is available.
*
- * @param {{ name: string, capacity: number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, onWait?: (state: object) => void }} options
+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options
* @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() } = 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 file = databaseFile(scope, root);
@@ -154,9 +154,17 @@ export async function takeResource(options) {
let queuedAt = new Date().toISOString();
try {
update(db, () => {
+ const currentCapacity = options.capacityProvider?.() ?? capacity;
+ if (!Number.isSafeInteger(currentCapacity) || currentCapacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');
const row = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name);
- if (row && row.capacity !== capacity) throw new Refused('RESOURCE_CAPACITY_MISMATCH', `resource "${name}" already has capacity ${row.capacity}`);
- db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO NOTHING').run(name, capacity);
+ if (row && row.capacity !== currentCapacity) {
+ const state = snapshot(db, name);
+ if (!allowIdleCapacityUpdate || state.holders.length || state.line.length) {
+ throw new Refused('RESOURCE_CAPACITY_MISMATCH', `resource "${name}" already has capacity ${row.capacity}`);
+ }
+ 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());
});
while (true) {
@@ -220,6 +228,24 @@ export async function takeResource(options) {
}
}
+/** Change a resource's capacity only while its queue is empty, persisting related settings under the same lock. */
+export function setResourceCapacity({ name, capacity, scope = 'machine', root = process.cwd(), persist = () => {} }) {
+ 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 db = open(databaseFile(scope, root));
+ try {
+ return update(db, () => {
+ const state = snapshot(db, name);
+ if (state.holders.length || state.line.length) {
+ throw new Refused('RESOURCE_BUSY', `resource "${name}" has ${state.holders.length} holder(s) and ${state.line.length} waiter(s); wait for it to become idle, then retry pullboard settings gateSlots ${capacity}`);
+ }
+ persist();
+ db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET capacity = excluded.capacity').run(name, capacity);
+ return { name, capacity };
+ });
+ } finally { db.close(); }
+}
+
/** List resources and prune leases whose process died or lease expired. */
export function listResources({ scope = 'machine', root = process.cwd() } = {}) {
const db = open(databaseFile(scope, root));
diff --git a/src/run.js b/src/run.js
index 4ba49067..d7ba0ef3 100644
--- a/src/run.js
+++ b/src/run.js
@@ -21,6 +21,19 @@ import { contains, git, headCommit, isClean, tryGit, untracked } from './git.js'
import { laneNames, outOfLane } from './lanes.js';
import { Refused } from './refused.js';
+/** Report changing machine queue state while an unattended item waits for a gate slot. */
+function gateWaitReporter(io) {
+ let last = '';
+ return ({ holders, position }) => {
+ const repos = holders.map(({ repo }) => repo).filter(Boolean);
+ const message = `gate waiting: ${holders.length} running${repos.length ? ` in ${repos.join(', ')}` : ''}; place ${position}`;
+ if (message !== last) {
+ io.say(message);
+ last = message;
+ }
+ };
+}
+
const FILE_CHARS = 32_000;
const PACK_FILE_CHARS = 96_000;
@@ -293,7 +306,7 @@ async function tryItem(ctx, item, { command, attempts, minutes, deps, me, start,
} else {
const isDirty = !isClean(root) || untracked(root).length > 0;
const committed = isDirty ? commitWork(root, item, ctx.config, changedSince(root, start)) : { ok: true, output: '' };
- const gate = committed.ok ? runGate(root, ctx.config) : { isGreen: false, output: committed.output };
+ const gate = committed.ok ? await runGate(root, ctx.config, { onWait: gateWaitReporter(ctx.io) }) : { isGreen: false, output: committed.output };
if (!gate.isGreen) {
result = committed.ok ? 'gate-red' : 'commit-refused';
digest = `${reverted}The check passed, but ${committed.ok ? "the repo's gate" : 'the commit'} failed:\n${digestOf(gate.output)}`;
@@ -302,7 +315,7 @@ async function tryItem(ctx, item, { command, attempts, minutes, deps, me, start,
ctx.io.say(`#${id} attempt ${attempt}: ${result} (agent ${built.seconds}s, check ${checked.seconds}s)`);
if (result === 'green') {
try {
- deps.submitHere(ctx, id);
+ await deps.submitHere(ctx, id);
} catch (error) {
if (!(error instanceof Refused)) throw error;
result = 'submit-refused';
diff --git a/src/settings.js b/src/settings.js
new file mode 100644
index 00000000..bb693ea1
--- /dev/null
+++ b/src/settings.js
@@ -0,0 +1,51 @@
+/** Machine-wide settings shared by every Pullboard checkout on this machine. */
+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { setResourceCapacity } from './resources.js';
+import { Refused } from './refused.js';
+
+const DEFAULT_GATE_SLOTS = 2;
+
+/** Resolve the separate machine settings file. */
+export function machineSettingsFile() {
+ return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'settings.json');
+}
+
+/** Read and validate machine settings, preserving any unrelated settings. */
+export function loadMachineSettings() {
+ const file = machineSettingsFile();
+ if (!existsSync(file)) return { gateSlots: DEFAULT_GATE_SLOTS };
+ let value;
+ try { value = JSON.parse(readFileSync(file, 'utf8')); }
+ catch { throw new Refused('BAD_MACHINE_SETTINGS', `cannot read ${file}; fix its JSON before running Pullboard`); }
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Refused('BAD_MACHINE_SETTINGS', `settings in ${file} must be a JSON object; fix it before running Pullboard`);
+ }
+ const gateSlots = value.gateSlots ?? DEFAULT_GATE_SLOTS;
+ if (!Number.isSafeInteger(gateSlots) || gateSlots < 1) {
+ throw new Refused('BAD_GATE_SLOTS', `gateSlots in ${file} must be a positive integer; run pullboard settings gateSlots <n>`);
+ }
+ return { ...value, gateSlots };
+}
+
+/** Atomically replace machine settings without exposing a partial JSON file. */
+function writeMachineSettings(settings) {
+ const file = machineSettingsFile();
+ mkdirSync(dirname(file), { recursive: true });
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
+ try {
+ writeFileSync(temporary, `${JSON.stringify(settings, null, 2)}\n`, { mode: 0o600 });
+ renameSync(temporary, file);
+ } finally { rmSync(temporary, { force: true }); }
+}
+
+/** Set machine gate capacity only when its durable holder and waiter lists are empty. */
+export function setGateSlots(capacity) {
+ if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_GATE_SLOTS', 'gateSlots must be a positive integer; run pullboard settings gateSlots <n>');
+ const current = loadMachineSettings();
+ const next = { ...current, gateSlots: capacity };
+ setResourceCapacity({ name: 'gate', capacity, scope: 'machine', persist: () => writeMachineSettings(next) });
+ return next;
+}
diff --git a/test/api.test.js b/test/api.test.js
index bc38f455..5302f22e 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -171,6 +171,12 @@ test('[A1] command results match the catalog across roots and subcommands', () =
json(box, repo, 'whoami');
json(box, repo, 'lanes');
json(box, repo, 'resources');
+ assert.equal(json(box, repo, 'settings').settings.gateSlots, 2);
+ assert.equal(json(box, repo, 'settings', ['gateSlots', '1']).settings.gateSlots, 1);
+ assert.equal(json(box, repo, 'settings').settings.gateSlots, 1);
+ const machineSettings = join(box.env.PULLBOARD_HOME, 'settings.json');
+ assert.equal(JSON.parse(readFileSync(machineSettings, 'utf8')).gateSlots, 1);
+ assert.equal(existsSync(join(box.env.PULLBOARD_HOME, 'config.json')), false, 'machine settings use the separate settings.json file');
json(box, repo, 'resume');
json(box, repo, 'status');
json(box, repo, 'doctor');
diff --git a/test/gate-resource.test.js b/test/gate-resource.test.js
new file mode 100644
index 00000000..51683055
--- /dev/null
+++ b/test/gate-resource.test.js
@@ -0,0 +1,158 @@
+/** Real CLI gate processes share the machine FIFO, skip cached trees and release after a crash [Q4,O5,O6]. */
+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 { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { after, test } from 'node:test';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const TEMP = [];
+const CHILDREN = new Set();
+
+/** Quote a fixture path for the gate shell command. */
+function quote(value) { return `'${value.replaceAll("'", "'\\''")}'`; }
+
+/** Create one private machine home, event file and isolated Git environment. */
+function fixture() {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-gate-queue-')));
+ TEMP.push(dir);
+ const events = join(dir, 'events.log');
+ const env = {
+ ...process.env,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Queue Test',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Queue Test',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ PULLBOARD_HOME: join(dir, 'home'),
+ };
+ return { dir, events, env };
+}
+
+/** Create a real clean repository whose gate records its start and end around a delay. */
+function gateRepo(box, name, delay = 0.25) {
+ const root = join(box.dir, name);
+ mkdirSync(root);
+ const git = (...args) => spawnSync('git', args, { cwd: root, env: box.env, encoding: 'utf8' });
+ assert.equal(git('init', '-q', '-b', 'main').status, 0);
+ const command = `printf '${name} start\\n' >> ${quote(box.events)}; sleep ${delay}; printf '${name} end\\n' >> ${quote(box.events)}`;
+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ gate: command }));
+ writeFileSync(join(root, 'SPEC.md'), '# Queue fixture\n');
+ assert.equal(git('add', '-A').status, 0);
+ assert.equal(git('commit', '-q', '-m', 'chore: queue fixture').status, 0);
+ return root;
+}
+
+/** 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'] });
+ child.stdoutText = '';
+ child.stderrText = '';
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => { child.stdoutText += chunk; });
+ child.stderr.on('data', (chunk) => { child.stderrText += chunk; });
+ CHILDREN.add(child);
+ child.closed = new Promise((resolveClose) => child.once('close', (code, signal) => {
+ CHILDREN.delete(child);
+ resolveClose({ code, signal });
+ }));
+ return child;
+}
+
+/** Wait until an observable fixture state is reached, or fail with a useful timeout. */
+async function waitFor(predicate, description, timeoutMs = 10_000) {
+ const until = Date.now() + timeoutMs;
+ while (Date.now() < until) {
+ const value = predicate();
+ if (value) return value;
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 20));
+ }
+ throw new Error(`timed out waiting for ${description}`);
+}
+
+/** Read the current private event log. */
+function events(box) {
+ return existsSync(box.events) ? readFileSync(box.events, 'utf8').trim().split(/\r?\n/u).filter(Boolean) : [];
+}
+
+after(async () => {
+ const running = [...CHILDREN];
+ for (const child of running) {
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { /* The fixture process already ended. */ }
+ }
+ await Promise.all(running.map((child) => child.closed));
+ TEMP.forEach((dir) => rmSync(dir, { recursive: true, force: true }));
+});
+
+test('[Q4,O5,O6] gate processes run one at a time in FIFO order when machine slots are one', async () => {
+ const box = fixture();
+ const roots = ['first', 'second', 'third'].map((name) => gateRepo(box, name, name === 'first' ? 1.5 : 0.2));
+ const setting = spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '1', '--json'], { cwd: roots[0], env: box.env, encoding: 'utf8' });
+ assert.equal(setting.status, 0, setting.stderr);
+ assert.equal(JSON.parse(setting.stdout).settings.gateSlots, 1);
+ const first = launch(box, roots[0]);
+ await waitFor(() => events(box).includes('first start'), 'first gate to start');
+ const second = launch(box, roots[1]);
+ await waitFor(() => second.stdoutText.includes('place 1'), 'second gate to enter the FIFO line');
+ assert.match(second.stdoutText, /1 running/);
+ assert.ok(second.stdoutText.includes(roots[0]), 'wait report names the repo holding the slot');
+ const third = launch(box, roots[2]);
+ await waitFor(() => third.stdoutText.includes('place 2'), 'third gate to enter behind the second');
+ const results = await Promise.all([first.closed, second.closed, third.closed]);
+ assert.deepEqual(results.map(({ code }) => code), [0, 0, 0], `${first.stderrText}${second.stderrText}${third.stderrText}`);
+ const starts = events(box).filter((line) => line.endsWith(' start')).map((line) => line.split(' ')[0]);
+ assert.deepEqual(starts, ['first', 'second', 'third']);
+ let running = 0;
+ let maximum = 0;
+ for (const line of events(box)) {
+ if (line.endsWith(' start')) running += 1;
+ else running -= 1;
+ maximum = Math.max(maximum, running);
+ }
+ assert.equal(maximum, 1);
+});
+
+test('[Q4] an exact-tree cached gate starts while another machine gate holds the only slot', async () => {
+ const box = fixture();
+ const cachedRoot = gateRepo(box, 'cached', 0.1);
+ const holderRoot = gateRepo(box, 'holder', 2);
+ assert.equal(spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '1'], { cwd: holderRoot, env: box.env }).status, 0);
+ const warm = spawnSync(process.execPath, [BIN, 'gate'], { cwd: cachedRoot, env: box.env, encoding: 'utf8' });
+ assert.equal(warm.status, 0, warm.stderr);
+ const priorCount = events(box).filter((line) => line.startsWith('cached ')).length;
+ const holder = launch(box, holderRoot);
+ await waitFor(() => events(box).includes('holder start'), 'uncached holder gate to start');
+ const refusedChange = spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '2', '--json'], { cwd: cachedRoot, env: box.env, encoding: 'utf8' });
+ assert.equal(refusedChange.status, 1);
+ assert.equal(JSON.parse(refusedChange.stdout).error.code, 'RESOURCE_BUSY');
+ assert.equal(JSON.parse(readFileSync(join(box.env.PULLBOARD_HOME, 'settings.json'), 'utf8')).gateSlots, 1);
+ const started = Date.now();
+ const cached = spawnSync(process.execPath, [BIN, 'gate'], { cwd: cachedRoot, env: box.env, encoding: 'utf8', timeout: 1_000 });
+ assert.equal(cached.status, 0, cached.stderr);
+ assert.match(cached.stdout, /already passed/);
+ assert.ok(Date.now() - started < 1_000, 'cached gate bypasses the occupied machine slot');
+ assert.equal(events(box).filter((line) => line.startsWith('cached ')).length, priorCount, 'cached gate command did not run again');
+ assert.equal((await holder.closed).code, 0, holder.stderrText);
+});
+
+test('[Q4] SIGKILL during a gate releases its machine slot for the next process', async () => {
+ const box = fixture();
+ const deadRoot = gateRepo(box, 'dead', 20);
+ const nextRoot = gateRepo(box, 'next', 0.1);
+ assert.equal(spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '1'], { cwd: deadRoot, env: box.env }).status, 0);
+ const dead = launch(box, deadRoot);
+ await waitFor(() => events(box).includes('dead start'), 'gate to hold a slot before it is killed');
+ const next = launch(box, nextRoot);
+ await waitFor(() => next.stdoutText.includes('place 1'), 'successor gate to queue');
+ process.kill(-dead.pid, 'SIGKILL');
+ assert.equal((await dead.closed).signal, 'SIGKILL');
+ const result = await Promise.race([
+ next.closed,
+ new Promise((_, reject) => setTimeout(() => reject(new Error('successor did not acquire the freed slot')), 5_000)),
+ ]);
+ assert.equal(result.code, 0, next.stderrText);
+ assert.ok(events(box).includes('next start'));
+});
diff --git a/test/resources.test.js b/test/resources.test.js
index 8192b426..dc31b4de 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -9,7 +9,7 @@ import { pathToFileURL } from 'node:url';
import { createInterface } from 'node:readline';
import { after, test } from 'node:test';
import { DatabaseSync } from 'node:sqlite';
-import { listResources } from '../src/resources.js';
+import { listResources, setResourceCapacity, takeResource } from '../src/resources.js';
const TEMP = [];
const CHILDREN = new Set();
@@ -439,6 +439,36 @@ test('[Q2,Q3] a SIGKILLed waiter is skipped while the next live waiter advances'
await release(live);
});
+test('[Q4] machine capacity changes atomically refuse an occupied or queued resource', async () => {
+ const box = fixture();
+ const oldHome = process.env.PULLBOARD_HOME;
+ process.env.PULLBOARD_HOME = box.home;
+ const holder = worker(box, { agent: 'capacity-holder' });
+ try {
+ assert.equal((await event(holder)).acquired, 'capacity-holder');
+ const waiter = worker(box, { agent: 'capacity-waiter' });
+ assert.equal((await event(waiter)).waiting, 1);
+ let persisted = false;
+ assert.throws(() => setResourceCapacity({ name: 'gate', capacity: 3, persist: () => { persisted = true; } }), (error) => error.code === 'RESOURCE_BUSY');
+ assert.equal(persisted, false, 'settings remain unchanged while a holder and waiter exist');
+ await release(holder);
+ assert.equal((await event(waiter)).acquired, 'capacity-waiter');
+ assert.throws(() => setResourceCapacity({ name: 'gate', capacity: 3, persist: () => { persisted = true; } }), (error) => error.code === 'RESOURCE_BUSY');
+ await release(waiter);
+ const changed = setResourceCapacity({ name: 'gate', capacity: 3, persist: () => { persisted = true; } });
+ assert.deepEqual(changed, { name: 'gate', capacity: 3 });
+ assert.equal(persisted, true, 'settings persist under the same queue lock as the capacity');
+ assert.equal(privateList(box)[0].capacity, 3);
+ const lease = await takeResource({ name: 'gate', capacity: 3, capacityProvider: () => 4, allowIdleCapacityUpdate: true, root: box.first, agent: 'fresh-capacity' });
+ assert.equal(privateList(box)[0].capacity, 4, 'a queued gate reads the latest setting after taking the SQLite lock');
+ lease.release();
+ } finally {
+ if (!holder.exitResult) await release(holder);
+ if (oldHome === undefined) delete process.env.PULLBOARD_HOME;
+ else process.env.PULLBOARD_HOME = oldHome;
+ }
+});
+
test('[Q1] machine scope is shared, repo scope stays local, and board scope names relay requirement', async () => {
const box = fixture();
const holder = worker(box, { agent: 'repo-a', root: box.first });