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.

fix(core): share gate slots across private homes [Q4]

Corey Olson77e542c37165
diff --cc docs/api.md
index 1819b6c9,daa7eff2..96f5af9d
--- a/docs/api.md
+++ b/docs/api.md
@@@ -8,8 -8,18 +8,18 @@@ Decision shouts without a recipient go
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.
+`pullboard settings` reads machine-wide settings from the OS account's `~/.pullboard/settings.json`; the gate queue database is beside it. This location does not follow `HOME` or `PULLBOARD_HOME`, so agents with private board homes still share one machine gate limit. Set `PULLBOARD_MACHINE_HOME` to an explicit directory only when a separate private machine settings and gate pool is intended; tests use this override. `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.
+ When `add` or `edit` supplies a new nonempty check, it records the item before measuring that check in a background temporary checkout of the captured `main` commit. Use `--wait` to wait for the measurement before returning, or `args.wait: true` for an HTTP add/edit move. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, request?, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `pending`, `green`, `red`, or `unavailable`. A background request carries an opaque `request` identity; an older completion cannot overwrite a newly edited or cleared check.
+
+ The board-state API's item projection includes `check` and, when recorded, `checkBaseline` with the same observation fields. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when showing or reserving the item for review, and when filing it with `--wait`. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. Captured observations and completions travel through ordered board moves, so replicas store results without executing commands. A completed result awaiting relay delivery stays on the measuring device and is retried by the next normal CLI command.
+
+ `pullboard stats [--since <date>] --json` returns `{version: 1, stats: {...}}` from the append-only event log. `submissions` and `rejections` count moves, including repeated attempts; `rejectionShare` is rejections divided by submissions (zero when the window has no submissions). `merged` counts distinct items with a merge move; `mergedWithoutAccept` counts those whose merge lacks an earlier acceptance of the latest submitted commit. That audit uses earlier history even when the acceptance falls before the selected window. Current item and verdict rows do not replace event evidence.
+
+ `firstEventAt` and `lastEventAt` are the first and latest dates in the selected window, or `null` when it is empty. `since` is the inclusive boundary as an ISO UTC timestamp, or `null` for the full history. Dates accept `YYYY-MM-DD` or an ISO UTC timestamp ending in `Z`; invalid dates return `BAD_SINCE` with repair guidance.
+
+ `agentCount` counts distinct event actors other than `board` and `person`; the coordinator and join moves are included. `agents` lists `{id, moves, families}` for each actor. `families` lists `{name, agents, moves}` by recorded family label, and `familyCount` counts these buckets, including `unknown`. Labels are not inferred from a model name or current agent, item, or verdict rows. A family's first recorded event snapshot applies to that move and following moves, until another snapshot changes or clears it; earlier unattributed moves remain `unknown`. Date windows preserve earlier recorded declarations but count only selected moves. Arrays are sorted by identifier or label. Local HTTP board state carries the same full-history object as `state.proofStats`.
+
<!-- api-command-shapes:start -->
| Command | Required top-level fields |
| --- | --- |
diff --cc src/resources.js
index 0059f533,8c1beff7..38d058ac
--- a/src/resources.js
+++ b/src/resources.js
@@@ -1,6 -1,7 +1,6 @@@
- /** 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';
import { dirname, join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
diff --cc test/api.test.js
index de63cbd8,46df3d18..e4e01c44
--- a/test/api.test.js
+++ b/test/api.test.js
@@@ -61,10 -66,10 +66,11 @@@ function sandbox()
GIT_COMMITTER_NAME: 'API Test',
GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(dir, 'home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'home'),
};
- const git = (cwd, ...args) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
- const run = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });
+ for (const marker of SSH_SHELL_MARKERS) delete env[marker];
+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env, encoding: 'utf8', stdio: 'pipe' });
+ const run = (cwd, ...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });
return { dir, env, git, run };
}
diff --cc test/check.test.js
index 00000000,860f604a..f556eb28
mode 000000,100644..100644
--- a/test/check.test.js
+++ b/test/check.test.js
@@@ -1,0 -1,232 +1,233 @@@
+ /** Coordinator-owned check commands and explicit caller consent [V2,N23]. */
+ import assert from 'node:assert/strict';
+ import { runFixtureExecFile as execFileSync, startFixtureChild as spawn, runFixtureChild as spawnSync, runFixtureChild, runFixtureGit } from './fixture-child.js';
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+ import { tmpdir } from 'node:os';
+ import { join, resolve } from 'node:path';
+ import { DatabaseSync } from 'node:sqlite';
+ import { after, test } from 'node:test';
+ import { removeFixtureDirectory } from './cleanup-diagnostics.js';
+
+ const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+ const TEMP_DIRS = [];
+ const SPEC = `# Check ownership fixture
+
+ ## G · Goals
+ - G1 [approved, must] The fixture keeps its board. | gate: true
+ `;
+
+ after(() => {
+ for (const dir of TEMP_DIRS) removeFixtureDirectory(dir);
+ });
+
+ /** Quote a literal executable path for the fixture hook's POSIX shim. */
+ function shellWord(value) {
+ return `'${value.replaceAll("'", "'\\''")}'`;
+ }
+
+ /** Create an isolated Git fixture with a real CLI process runner. */
+ function sandbox() {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-check-owner-'));
+ TEMP_DIRS.push(dir);
+ const bin = join(dir, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);
+ chmodSync(join(bin, 'pullboard'), 0o755);
+ const env = {
+ ...process.env,
+ PATH: `${bin}:${process.env.PATH}`,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Check owner test',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Check owner test',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ PULLBOARD_HOME: join(dir, 'pullboard-home'),
++ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
+ };
+ /** Run Git with private fixture identity and config. */
+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env });
+ /** Run the production CLI in a separate process, optionally with piped stdin. */
+ const run = (cwd, args, input) => runFixtureChild(process.execPath, [BIN, ...args], {
+ cwd, env, encoding: 'utf8', ...(input === undefined ? {} : { input }),
+ });
+ return { dir, env, git, run };
+ }
+
+ /** Initialize the board and register a real worktree joined to the web lane. */
+ function project() {
+ const box = sandbox();
+ const repo = join(box.dir, 'repo');
+ mkdirSync(repo);
+ box.git(repo, 'init', '-q', '-b', 'main');
+ const initialized = box.run(repo, ['init']);
+ assert.equal(initialized.status, 0, initialized.stderr);
+ const configPath = join(repo, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, `${JSON.stringify({
+ ...config,
+ gate: 'true',
+ spec: 'SPEC.md',
+ lanes: { web: { owns: ['web/'], specs: ['G1'] } },
+ shared: [],
+ }, null, 2)}\n`);
+ writeFileSync(join(repo, 'SPEC.md'), SPEC);
+ box.git(repo, 'add', '-A');
+ box.git(repo, 'commit', '-q', '-m', 'chore: set up check ownership fixture');
+ const web = join(box.dir, 'web-1');
+ box.git(repo, 'worktree', 'add', '-q', web, '-b', 'web/one');
+ const joined = box.run(web, ['join', 'web']);
+ assert.equal(joined.status, 0, joined.stderr);
+ return { ...box, repo, web };
+ }
+
+ /** Open the actual board database read-only and run one scalar query. */
+ function queryBoard(box, sql, ...params) {
+ const db = new DatabaseSync(join(box.repo, '.git', 'pullboard', 'board.sqlite'), { readOnly: true });
+ try {
+ return db.prepare(sql).get(...params);
+ } finally {
+ db.close();
+ }
+ }
+
+ /** Build a harmless project check that writes a distinct marker in its cwd. */
+ function markerCheck(filename) {
+ const source = `require('node:fs').writeFileSync(${JSON.stringify(filename)}, 'ran')`;
+ return `${shellWord(process.execPath)} -e ${shellWord(source)}`;
+ }
+
+ /** Add a check-bearing item as the coordinator and return its persisted id. */
+ function addCheckedItem(box, title, command) {
+ const result = box.run(box.repo, ['add', 'coordinator', title, '--check', command, '--json']);
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout).item.item_id;
+ }
+
+ /** Prompt the spawned agent CLI only after capturing its setter and exact command text. */
+ async function confirmInteractively(box, itemId, command, markerFile, json = false) {
+ const child = spawn(process.execPath, [BIN, 'check', String(itemId), ...(json ? ['--json'] : [])], {
+ cwd: box.web,
+ env: box.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ let sent = false;
+ let promptResolve;
+ let promptReject;
+ const prompt = new Promise((resolvePrompt, rejectPrompt) => {
+ promptResolve = resolvePrompt;
+ promptReject = rejectPrompt;
+ });
+ /** Send consent only after both the command attribution and its question are visible. */
+ function answerPrompt() {
+ const notice = json ? stderr : stdout;
+ if (sent || !/set by coordinator/iu.test(notice) || !notice.includes(command) || !/Run this check\?/u.test(stderr)) return;
+ sent = true;
+ try {
+ assert.equal(existsSync(markerFile), false, 'the check has not run before the setter, command and consent question are displayed');
+ promptResolve();
+ child.stdin.end('yes\n');
+ } catch (error) { promptReject(error); child.kill('SIGKILL'); }
+ }
+ child.stdout.setEncoding('utf8').on('data', (chunk) => { stdout += chunk; answerPrompt(); });
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; answerPrompt(); });
+ child.once('error', promptReject);
+ const closed = new Promise((resolveClose, rejectClose) => {
+ child.once('close', (code, signal) => {
+ if (!sent) promptReject(new Error(child.fixtureFailure ?? 'check exited before its prompt'));
+ resolveClose({ code, signal, failure: child.fixtureFailure });
+ });
+ child.once('error', rejectClose);
+ });
+ try {
+ await prompt;
+ const result = await closed;
+ assert.equal(result.signal, null);
+ return { ...result, stdout, stderr };
+ } catch (error) {
+ child.kill('SIGKILL');
+ await Promise.race([closed, new Promise((resolveClose) => setTimeout(resolveClose, 1_000))]);
+ throw error;
+ }
+ }
+
+ test('[V2,N23] only the coordinator sets checks and agents confirm them before execution', async () => {
+ const box = project();
+ const itemCountBefore = queryBoard(box, 'SELECT COUNT(*) AS count FROM item').count;
+ const eventCountBefore = queryBoard(box, 'SELECT COUNT(*) AS count FROM event').count;
+ const forbiddenCreate = box.run(box.web, ['add', 'web', 'Agent supplied check', '--check', 'true', '--json']);
+ assert.equal(forbiddenCreate.status, 1, forbiddenCreate.stderr);
+ assert.equal(JSON.parse(forbiddenCreate.stdout).error.code, 'COORDINATOR_CHECK');
+ assert.equal(queryBoard(box, 'SELECT COUNT(*) AS count FROM item').count, itemCountBefore, 'refusal adds no item');
+ assert.equal(queryBoard(box, 'SELECT COUNT(*) AS count FROM event').count, eventCountBefore, 'refusal adds no event');
+
+ const ordinary = box.run(box.web, ['add', 'web', 'Agent ordinary item', '--json']);
+ assert.equal(ordinary.status, 0, ordinary.stderr);
+ const ordinaryId = JSON.parse(ordinary.stdout).item.item_id;
+ const rowBefore = queryBoard(box, 'SELECT item_title, item_check, item_updated_at FROM item WHERE item_id = ?', ordinaryId);
+ const eventsBeforeEdit = queryBoard(box, 'SELECT COUNT(*) AS count FROM event').count;
+ const forbiddenEdit = box.run(box.web, ['edit', String(ordinaryId), '--check', 'true', '--json']);
+ assert.equal(forbiddenEdit.status, 1, forbiddenEdit.stderr);
+ assert.equal(JSON.parse(forbiddenEdit.stdout).error.code, 'COORDINATOR_CHECK');
+ assert.deepEqual(queryBoard(box, 'SELECT item_title, item_check, item_updated_at FROM item WHERE item_id = ?', ordinaryId), rowBefore);
+ assert.equal(queryBoard(box, 'SELECT COUNT(*) AS count FROM event').count, eventsBeforeEdit, 'refused edit changes no event');
+
+ for (const args of [
+ ['add', 'web', 'Empty agent check', '--check', '', '--json'],
+ ['edit', String(ordinaryId), '--check', '', '--json'],
+ ]) {
+ const refused = box.run(box.web, args);
+ assert.equal(refused.status, 1, 'explicitly setting or clearing an empty check also belongs to the coordinator');
+ assert.equal(JSON.parse(refused.stdout).error.code, 'COORDINATOR_CHECK');
+ }
+
+ const coordinatorCommand = markerCheck('check-ran-coordinator.txt');
+ const coordinatorId = addCheckedItem(box, 'Coordinator check', coordinatorCommand);
+ const coordinatorResult = box.run(box.repo, ['check', String(coordinatorId)]);
+ assert.equal(coordinatorResult.status, 0, coordinatorResult.stderr);
+ assert.match(coordinatorResult.stdout, /set by coordinator/iu, 'even the setter sees the command attribution');
+ assert.ok(coordinatorResult.stdout.includes(coordinatorCommand), 'the exact command is printed before execution');
+ assert.doesNotMatch(coordinatorResult.stderr, /Run this check/iu, 'the setter needs no consent prompt');
+ assert.equal(readFileSync(join(box.repo, 'check-ran-coordinator.txt'), 'utf8'), 'ran');
+
+ const interactiveCommand = markerCheck('check-ran-interactive.txt');
+ const interactiveId = ordinaryId;
+ const authored = box.run(box.repo, ['edit', String(interactiveId), '--check', interactiveCommand, '--json']);
+ assert.equal(authored.status, 0, authored.stdout + authored.stderr);
+ assert.equal(queryBoard(box, 'SELECT item_created_by FROM item WHERE item_id = ?', interactiveId).item_created_by, 'web-1',
+ 'the check setter is derived from the edit, independently of the item creator');
+ const eofRefusal = box.run(box.web, ['check', String(interactiveId), '--json'], '');
+ assert.equal(eofRefusal.status, 1, eofRefusal.stderr);
+ assert.equal(JSON.parse(eofRefusal.stdout).error.code, 'CHECK_CONFIRM');
+ assert.ok(eofRefusal.stderr.includes(interactiveCommand), 'JSON mode prints the exact command before requesting consent');
+ assert.match(eofRefusal.stderr, /set by coordinator[\s\S]*Run this check\?/u);
+ const interactiveMarker = join(box.web, 'check-ran-interactive.txt');
+ assert.equal(existsSync(interactiveMarker), false,
+ 'EOF refusal runs no check command');
+ const declined = box.run(box.web, ['check', String(interactiveId), '--json'], 'no\n');
+ assert.equal(declined.status, 1);
+ assert.equal(JSON.parse(declined.stdout).error.code, 'CHECK_CONFIRM');
+ assert.equal(existsSync(interactiveMarker), false, 'declining the prompt also executes no command');
+
+ const confirmed = await confirmInteractively(box, interactiveId, interactiveCommand, interactiveMarker);
+ assert.equal(confirmed.code, 0, `${confirmed.stdout}${confirmed.stderr}`);
+ assert.match(confirmed.stdout, /set by coordinator/iu);
+ assert.ok(confirmed.stdout.includes(interactiveCommand), 'the prompt shows the exact command before confirmation');
+ assert.equal(readFileSync(interactiveMarker, 'utf8'), 'ran');
+
+ rmSync(interactiveMarker);
+ const jsonConfirmed = await confirmInteractively(box, interactiveId, interactiveCommand, interactiveMarker, true);
+ assert.equal(jsonConfirmed.code, 0, jsonConfirmed.stderr);
+ assert.equal(JSON.parse(jsonConfirmed.stdout).by, 'coordinator', 'JSON remains one document while consent notices print immediately on stderr');
+ assert.equal(readFileSync(interactiveMarker, 'utf8'), 'ran');
+
+ const yesCommand = markerCheck('check-ran-yes.txt');
+ const yesId = addCheckedItem(box, 'Confirmed by flag', yesCommand);
+ const yesResult = box.run(box.web, ['check', String(yesId), '--yes', '--json']);
+ assert.equal(yesResult.status, 0, yesResult.stderr);
+ assert.equal(JSON.parse(yesResult.stdout).by, 'coordinator', 'JSON retains check attribution');
+ assert.equal(JSON.parse(yesResult.stdout).check, yesCommand);
+ assert.equal(readFileSync(join(box.web, 'check-ran-yes.txt'), 'utf8'), 'ran');
+ });
diff --cc test/gate-resource.test.js
index c8b075b6,d4f46d84..5e4de8fc
--- a/test/gate-resource.test.js
+++ b/test/gate-resource.test.js
@@@ -117,64 -151,6 +152,68 @@@ test('[Q4,O5,O6] gate processes run on
assert.equal(maximum, 1);
});
+test('[Q4] gates with different PULLBOARD_HOME values share the machine pool unless explicitly separated', async () => {
+ const shared = fixture();
+ const releaseShared = join(shared.dir, 'release-shared');
+ const firstRoot = gateRepo(shared, 'shared-first', 0, releaseShared);
+ const otherBoardHome = { ...shared, env: { ...shared.env, PULLBOARD_HOME: join(shared.dir, 'other-board-home') } };
+ const secondRoot = gateRepo(otherBoardHome, 'shared-second', 0, releaseShared);
+ const setting = spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '1'], { cwd: firstRoot, env: shared.env, encoding: 'utf8' });
+ assert.equal(setting.status, 0, setting.stderr);
+ const first = launch(shared, firstRoot);
+ let second;
+ try {
+ await waitFor(() => events(shared).includes('shared-first start'), 'first shared-pool gate to start');
+ second = launch(otherBoardHome, secondRoot);
- await waitFor(() => second.stdoutText.includes('place 1'), 'gate with another board home to queue on the same machine pool');
++ await waitFor(
++ () => second.stdoutText.includes('place 1') || events(shared).includes('shared-second start'),
++ 'gate with another board home to queue or start on the shared machine pool',
++ );
++ assert.ok(second.stdoutText.includes('place 1'), 'the other board home is queued behind the first gate');
+ assert.deepEqual(events(shared), ['shared-first start']);
+ writeFileSync(releaseShared, 'release');
+ const results = await Promise.all([first.closed, second.closed]);
+ assert.deepEqual(results.map(({ code }) => code), [0, 0], `${first.stderrText}${second.stderrText}`);
+ assert.deepEqual(events(shared), ['shared-first start', 'shared-first end', 'shared-second start', 'shared-second end']);
+ } finally {
+ writeFileSync(releaseShared, 'release');
+ await Promise.all([first, second].filter(Boolean).map((child) => child.closed));
+ }
+
+ const separated = fixture();
+ const releaseSeparated = join(separated.dir, 'release-separated');
+ const firstPool = { ...separated, env: { ...separated.env, PULLBOARD_MACHINE_HOME: join(separated.dir, 'machine-first') } };
+ const secondPool = {
+ ...separated,
+ env: {
+ ...separated.env,
+ PULLBOARD_MACHINE_HOME: join(separated.dir, 'machine-second'),
+ },
+ };
+ const isolatedFirstRoot = gateRepo(firstPool, 'isolated-first', 0, releaseSeparated);
+ const isolatedSecondRoot = gateRepo(secondPool, 'isolated-second', 0, releaseSeparated);
+ for (const [box, root] of [[firstPool, isolatedFirstRoot], [secondPool, isolatedSecondRoot]]) {
+ const configured = spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '1'], { cwd: root, env: box.env, encoding: 'utf8' });
+ assert.equal(configured.status, 0, configured.stderr);
+ }
+ const isolatedFirst = launch(firstPool, isolatedFirstRoot);
+ let isolatedSecond;
+ try {
+ await waitFor(() => events(separated).includes('isolated-first start'), 'first isolated-pool gate to start');
+ isolatedSecond = launch(secondPool, isolatedSecondRoot);
+ await waitFor(() => events(separated).includes('isolated-second start'), 'explicit private pool to acquire while the first pool is occupied');
+ assert.deepEqual(events(separated), ['isolated-first start', 'isolated-second start']);
+ writeFileSync(releaseSeparated, 'release');
+ const results = await Promise.all([isolatedFirst.closed, isolatedSecond.closed]);
+ assert.deepEqual(results.map(({ code }) => code), [0, 0], `${isolatedFirst.stderrText}${isolatedSecond.stderrText}`);
+ assert.deepEqual(events(separated).slice(0, 2), ['isolated-first start', 'isolated-second start']);
+ assert.deepEqual(events(separated).slice(2).sort(), ['isolated-first end', 'isolated-second end']);
+ } finally {
+ writeFileSync(releaseSeparated, 'release');
+ await Promise.all([isolatedFirst, isolatedSecond].filter(Boolean).map((child) => child.closed));
+ }
+});
+
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);
@@@ -188,14 -165,15 +228,15 @@@
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);
+ assert.equal(JSON.parse(readFileSync(join(box.env.PULLBOARD_MACHINE_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 });
+ const cached = runFixtureChild(process.execPath, [BIN, 'gate'], { cwd: cachedRoot, env: box.env, encoding: 'utf8' });
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.ok(events(box).includes('holder start') && !events(box).includes('holder end'), 'cached gate returned while the other machine gate still held its slot');
assert.equal(events(box).filter((line) => line.startsWith('cached ')).length, priorCount, 'cached gate command did not run again');
+ writeFileSync(releaseHolder, 'release\n');
assert.equal((await holder.closed).code, 0, holder.stderrText);
+ assert.ok(events(box).includes('holder end'), 'the holder exits only after the test releases it');
});
test('[Q4] SIGKILL during a gate releases its machine slot for the next process', async () => {
diff --cc test/gate.test.js
index 0ee0e28f,e6d5c53f..479a089e
--- a/test/gate.test.js
+++ b/test/gate.test.js
@@@ -36,10 -39,9 +39,10 @@@ function repoWithGate(gate, check = ''
GIT_COMMITTER_NAME: 'Test Agent',
GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(dir, 'home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'home'),
};
- const git = (...args) => execFileSync('git', args, { cwd: repo, env, encoding: 'utf8', stdio: 'pipe' }).trim();
- const run = (...args) => spawnSync(process.execPath, [BIN, ...args], { cwd: repo, env, encoding: 'utf8', timeout: 60_000 });
+ const git = (...args) => runFixtureGit(args, { cwd: repo, env });
+ const run = (...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd: repo, env, encoding: 'utf8' });
git('init', '-q', '-b', 'main');
writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: `echo run >> ../runs.log; ${gate}` }));
writeFileSync(join(repo, 'SPEC.md'), '# Demo\n\n## G · Goals\n- G1 [approved, must] It works. | gate: test\n');
diff --cc test/machine.test.js
index 3003902c,12f060d4..d5e657d9
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@@ -1002,11 -1030,10 +1030,11 @@@ test('next --verify reserves the revie
GIT_COMMITTER_NAME: 'Test Agent',
GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(dir, 'home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'home'),
};
- const git = (cwd, ...args) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
- // A command that never returns fails the test after a minute instead of holding the gate open.
- const run = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 60_000 });
+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env, encoding: 'utf8', stdio: 'pipe' });
+ // The test runner's per-test timeout bounds hangs without killing this CLI early under load.
+ const run = (cwd, ...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });
const repo = join(dir, 'repo');
mkdirSync(repo);
git(repo, 'init', '-q', '-b', 'main');
diff --cc test/release.test.js
index 96baadb4,72f79bb5..dc264505
--- a/test/release.test.js
+++ b/test/release.test.js
@@@ -44,12 -44,11 +44,12 @@@ test('a packed release installs with n
GIT_COMMITTER_NAME: 'Test Agent',
GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(dir, 'home'),
+ PULLBOARD_MACHINE_HOME: join(dir, 'home'),
};
- const git = (cwd, ...args) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();
+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env });
/** Run the installed pullboard and require it to succeed. */
const pullboard = (cwd, ...args) => {
- const result = spawnSync(bin, args, { cwd, env, encoding: 'utf8', timeout: 120_000 });
+ const result = runFixtureChild(bin, args, { cwd, env, encoding: 'utf8' });
assert.equal(result.status, 0, `pullboard ${args.join(' ')}: ${result.stderr}${result.stdout}`);
return result.stdout;
};
diff --cc test/resources.test.js
index 8ace3655,225492c5..01a6d6c0
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@@ -50,10 -58,10 +58,10 @@@ function fixture()
const second = join(dir, 'repo-b');
for (const repo of [first, second]) {
mkdirSync(repo);
- const result = spawnSync('git', ['init', '-q', repo], { encoding: 'utf8' });
- assert.equal(result.status, 0, result.stderr);
+ const result = runFixtureChild('git', ['init', '-q', repo], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.failure);
}
- return { dir, home, first, second, env: { ...process.env, PULLBOARD_HOME: home } };
+ return { dir, home, first, second, env: { ...process.env, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: home } };
}
/** Create the previous private queue schema so simultaneous openers exercise its migration. */
@@@ -242,6 -274,205 +278,213 @@@ test('[Q1,Q2] capacity-one takers acqui
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;
++ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;
+ process.env.PULLBOARD_HOME = box.home;
++ process.env.PULLBOARD_MACHINE_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.second, agent: 'second-label', landing: true })
+ .then((lease) => { extraLease = lease; return lease; });
+ await waitUntil(() => privateList(box)[0].line.some(({ agent, landing: isLanding }) => agent === 'second-label' && 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]), [
+ ['second-label', 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', 'second-label']);
+ } 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;
++ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;
++ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;
+ }
+ });
+
+ /** A capacity-three queue must not grant an empty slot to holders queued for their own second slot. */
+ test('[Q1,Q2] landing holders leave an empty slot for the next eligible landing [Q1,Q2]', async () => {
+ const box = fixture();
+ const previousHome = process.env.PULLBOARD_HOME;
++ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;
+ process.env.PULLBOARD_HOME = box.home;
++ process.env.PULLBOARD_MACHINE_HOME = box.home;
+ let firstA;
+ let secondA;
+ let holderB;
+ let holderC;
+ let secondAPromise;
+ let secondAAcquired = false;
+ try {
+ firstA = await takeResource({ name: 'gate', capacity: 3, root: box.first, agent: 'holder-a' });
+ holderB = worker(box, { capacity: 3, agent: 'holder-b' });
+ holderC = worker(box, { capacity: 3, agent: 'holder-c' });
+ assert.equal((await acquired(holderB)).acquired, 'holder-b');
+ assert.equal((await acquired(holderC)).acquired, 'holder-c');
+
+ secondAPromise = takeResource({ name: 'gate', capacity: 3, root: box.first, agent: 'holder-a', landing: true })
+ .then((lease) => { secondAAcquired = true; secondA = lease; return lease; });
+ await waitUntil(() => privateList(box)[0].line.some(({ agent, landing }) => agent === 'holder-a' && landing), 'holder A second landing to queue');
+ holderB.stdin.write('second\n');
+ await waitUntil(() => privateList(box)[0].line.filter(({ landing }) => landing).length === 2, 'holder B second landing to join');
+
+ await release(holderC);
+ holderC = null;
+ await delay(300);
+ assert.deepEqual(privateList(box)[0].holders.map(({ agent }) => agent).sort(), ['holder-a', 'holder-b'], 'neither holder takes the free third slot while the other holder landing waits');
+ assert.equal(secondAAcquired, false, 'A second slot remains queued');
+ assert.deepEqual(holderB.pendingLines.filter((line) => line.includes('secondAcquired')), [], 'B second slot remains queued');
+
+ firstA.release();
+ firstA = null;
+ await secondAPromise;
+ assert.ok(secondAAcquired, 'releasing A first makes its landing the next eligible landing');
+ assert.equal((await event(holderB)).secondAcquired, 'holder-b', 'B can finish after A no longer waits');
+ holderB.stdin.end('release\n');
+ assert.equal((await holderB.finished).code, 0, holderB.errors);
+ holderB.lines.close();
+ holderB = null;
+ secondA.release();
+ secondA = null;
+ } finally {
+ for (const child of [holderB, holderC]) if (child && !child.exitResult) child.kill('SIGKILL');
+ await Promise.all([holderB, holderC].filter(Boolean).map((child) => child.finished));
+ for (const child of [holderB, holderC]) child?.lines.close();
+ firstA?.release();
+ secondA?.release();
+ privateList(box); // Purge any dead child holder/waiter rows before dropping the private database.
+ if (secondAPromise && !secondA) {
+ await secondAPromise;
+ }
+ secondA?.release();
+ privateList(box);
+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;
+ else process.env.PULLBOARD_HOME = previousHome;
++ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;
++ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;
+ }
+ });
+
+ 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(); }
+
+ let retainedLine;
+ assert.doesNotThrow(() => { retainedLine = privateList(box)[0].line; }, 'the previous queue schema opens without losing its waiting runs');
+ assert.deepEqual(retainedLine.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' });
diff --cc test/settings.test.js
index f769de37,68bc9496..71b34dc5
--- a/test/settings.test.js
+++ b/test/settings.test.js
@@@ -1,18 -1,17 +1,19 @@@
/** Machine-wide gate capacity settings through the actual CLI [O5,O6]. */
import assert from 'node:assert/strict';
++import { spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { tmpdir, userInfo } from 'node:os';
import { join, resolve } from 'node:path';
- import { spawnSync } from 'node:child_process';
import { test } from 'node:test';
+ import { runFixtureChild } from './fixture-child.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const MACHINE_HOME_MODULE = resolve(import.meta.dirname, '../src/machine-home.js');
/** Run settings in an isolated machine home, returning its structured CLI result. */
function settings(home, ...args) {
- return spawnSync(process.execPath, [BIN, 'settings', ...args, '--json'], {
+ return runFixtureChild(process.execPath, [BIN, 'settings', ...args, '--json'], {
- encoding: 'utf8', env: { ...process.env, PULLBOARD_HOME: home },
+ encoding: 'utf8', env: { ...process.env, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: home },
});
}
diff --cc test/spec.test.js
index e0cc9a4f,89de2f9f..a5d79b62
--- a/test/spec.test.js
+++ b/test/spec.test.js
@@@ -126,10 -193,9 +193,10 @@@ test('a grammar-1 repair can commit aft
GIT_COMMITTER_NAME: 'Test Agent',
GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(root, '.home'),
+ PULLBOARD_MACHINE_HOME: join(root, '.home'),
};
- const git = (...args) => execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: 'pipe' });
- const command = (...args) => spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args], { cwd: root, env, encoding: 'utf8' });
+ const git = (...args) => runFixtureGit(args, { cwd: root, env, encoding: 'utf8', stdio: 'pipe' });
+ const command = (...args) => runFixtureChild(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args], { cwd: root, env, encoding: 'utf8' });
git('init', '-q', '-b', 'main');
git('config', 'user.name', 'Test Agent');
git('config', 'user.email', '[email protected]');
@@@ -283,10 -365,12 +366,13 @@@ function specBox(t, { specName = 'SPEC.
GIT_AUTHOR_NAME: 'Test Agent', GIT_AUTHOR_EMAIL: '[email protected]',
GIT_COMMITTER_NAME: 'Test Agent', GIT_COMMITTER_EMAIL: '[email protected]',
PULLBOARD_HOME: join(root, '.home'),
+ PULLBOARD_MACHINE_HOME: join(root, '.home'),
};
- const git = (...args) => execFileSync('git', args, { cwd: root, env, stdio: 'pipe', encoding: 'utf8' });
- const command = (...args) => spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args], { cwd: root, env, encoding: 'utf8' });
+ delete env.PULLBOARD_RELAY_TOKEN;
+ // These isolated signoff fixtures model the same person terminal as the suite runner.
+ for (const marker of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete env[marker];
+ const git = (...args) => runFixtureGit(args, { cwd: root, env, stdio: 'pipe', encoding: 'utf8' });
+ const command = (...args) => runFixtureChild(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args], { cwd: root, env, encoding: 'utf8' });
const run = (...args) => command('spec', ...args);
git('init', '-q', '-b', 'main');
git('config', 'user.name', 'Test Agent');
diff --cc test/test-runner.test.js
index 1c60949b,ab1c5aeb..380302ae
--- a/test/test-runner.test.js
+++ b/test/test-runner.test.js
@@@ -17,8 -21,10 +21,11 @@@ test('tests run without inherited Git i
assert.equal(process.env.GIT_AUTHOR_EMAIL, undefined);
assert.equal(process.env.GIT_COMMITTER_NAME, undefined);
assert.equal(process.env.GIT_COMMITTER_EMAIL, undefined);
+ assert.equal(process.env.SSH_CONNECTION, undefined);
+ assert.equal(process.env.SSH_CLIENT, undefined);
+ assert.equal(process.env.SSH_TTY, undefined);
assert.equal(process.env.HOME, process.env.PULLBOARD_HOME);
+ assert.ok(process.env.PULLBOARD_MACHINE_HOME.startsWith(join(process.env.TMPDIR, 'machine')));
assert.ok(process.env.PULLBOARD_TEST_FILE.endsWith('test/test-runner.test.js'));
const root = mkdtempSync(join(tmpdir(), 'pullboard-runner-git-'));