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.

test(core): cover relay and gate resource gaps [A4,Q4,O5,O6]

Corey Olson1864aa3f78ea
diff --git a/test/e2e.test.js b/test/e2e.test.js
index 6d5586b3..a6593677 100644
--- a/test/e2e.test.js
+++ b/test/e2e.test.js
@@ -81,13 +81,12 @@ const SPEC = `# Demo spec
* A repo set up with pullboard, two lanes and a spec, committed through its own hooks, plus a
* worktree joined to the web lane.
*/
-function project() {
- const box = sandbox();
+function project(gate = CONFIG.gate, box = sandbox()) {
const repo = join(box.dir, 'repo');
mkdirSync(repo);
box.git(repo, 'init', '-q', '-b', 'main');
assert.equal(box.run(repo, 'init').code, 0);
- writeFileSync(join(repo, 'pullboard.json'), JSON.stringify(CONFIG, null, 2));
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate }, null, 2));
writeFileSync(join(repo, 'SPEC.md'), SPEC);
box.git(repo, 'add', '-A');
box.git(repo, 'commit', '-q', '-m', 'chore: set up pullboard');
@@ -97,6 +96,53 @@ function project() {
return { ...box, repo, web };
}
+/** Create a private gate that waits only after the test arms it. */
+function holdingGate(box) {
+ const script = join(box.dir, 'holding-gate.cjs');
+ const mode = join(box.dir, 'hold-gate');
+ const release = join(box.dir, 'release-gate');
+ const events = join(box.dir, 'gate-events.log');
+ writeFileSync(script, [
+ "const fs = require('node:fs');",
+ 'const [armed, release, events] = process.argv.slice(2);',
+ 'if (!fs.existsSync(armed)) process.exit(0);',
+ "fs.appendFileSync(events, 'start\\n');",
+ 'const deadline = Date.now() + 15000;',
+ 'while (!fs.existsSync(release) && Date.now() < deadline) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);',
+ 'if (!fs.existsSync(release)) process.exit(23);',
+ "fs.appendFileSync(events, 'end\\n');",
+ ].join('\n'));
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
+ return { command: `node ${quote(script)} ${quote(mode)} ${quote(release)} ${quote(events)}`, mode, release, events };
+}
+
+/** Launch a CLI or Git process while preserving its output for the gate-lock assertion. */
+function launch(box, cwd, command, args) {
+ const child = spawn(command, args, { cwd, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });
+ child.stdoutText = '';
+ child.stderrText = '';
+ child.stdout.setEncoding('utf8').on('data', (chunk) => { child.stdoutText += chunk; });
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { child.stderrText += chunk; });
+ child.closed = new Promise((resolveClose) => child.once('close', (code, signal) => resolveClose({ code, signal })));
+ return child;
+}
+
+/** Wait for a private fixture observation with a bounded failure time. */
+async function waitFor(predicate, description, timeoutMs = 8_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const value = predicate();
+ if (value) return value;
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 20));
+ }
+ throw new Error(`timed out waiting for ${description}`);
+}
+
+/** Read the private gate event sequence without exposing arbitrary gate output. */
+function gateEvents(gate) {
+ return existsSync(gate.events) ? readFileSync(gate.events, 'utf8').trim().split(/\r?\n/u).filter(Boolean) : [];
+}
+
/**
* Write a file in a worktree and commit it, returning git's result so a refusal can be read.
*/
@@ -308,6 +354,65 @@ test('submit needs a clean tree, nothing untracked, and the gate green at HEAD [
assert.equal(box.git(box.repo, 'rev-parse', `refs/pullboard/items/1/${head.slice(0, 12)}`), head, 'submit pins the commit');
});
+test('submit keeps its machine gate slot until the submitted check finishes [V4,Q4]', 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);
+ projectBox.run(projectBox.repo, 'add', 'web', 'Page', '--specs', 'G1');
+ assert.match(projectBox.run(projectBox.web, 'claim', '1').out, /claimed #1/);
+ assert.equal(commitFile(projectBox, projectBox.web, 'web/page.html', 'page', 'feat(web): page [G1]').status, 0);
+ writeFileSync(gate.mode, 'armed');
+ const children = [];
+ try {
+ const submitted = launch(projectBox, projectBox.web, process.execPath, [BIN, 'submit', '1']);
+ children.push(submitted);
+ await waitFor(() => gateEvents(gate).includes('start'), 'submit gate to start and hold its resource');
+ const competitor = launch(projectBox, projectBox.repo, process.execPath, [BIN, 'gate']);
+ children.push(competitor);
+ await waitFor(() => competitor.stdoutText.includes('place 1'), 'another gate to wait behind submit');
+ assert.deepEqual(gateEvents(gate), ['start']);
+ writeFileSync(gate.release, 'released');
+ const [submitResult, competitorResult] = await Promise.all([submitted.closed, competitor.closed]);
+ assert.equal(submitResult.code, 0, submitted.stderrText);
+ assert.match(submitted.stdoutText, /submitted #1/);
+ assert.equal(competitorResult.code, 0, competitor.stderrText);
+ assert.deepEqual(gateEvents(gate), ['start', 'end', 'start', 'end']);
+ } finally {
+ writeFileSync(gate.release, 'released');
+ await Promise.all(children.map((child) => child.closed));
+ }
+});
+
+test('pre-push keeps its machine gate slot until the hook check finishes [C3,Q4]', async () => {
+ const box = sandbox();
+ const gate = holdingGate(box);
+ const projectBox = project(gate.command, box);
+ const remote = join(box.dir, 'remote.git');
+ projectBox.git(box.dir, 'init', '-q', '--bare', remote);
+ projectBox.git(projectBox.repo, 'remote', 'add', 'origin', remote);
+ assert.equal(projectBox.run(projectBox.repo, 'settings', 'gateSlots', '1').code, 0);
+ writeFileSync(gate.mode, 'armed');
+ const children = [];
+ try {
+ const pushed = launch(projectBox, projectBox.repo, 'git', ['push', '-q', 'origin', 'main']);
+ children.push(pushed);
+ await waitFor(() => gateEvents(gate).includes('start'), 'pre-push gate to start and hold its resource');
+ const competitor = launch(projectBox, projectBox.web, process.execPath, [BIN, 'gate']);
+ children.push(competitor);
+ await waitFor(() => competitor.stdoutText.includes('place 1'), 'another gate to wait behind pre-push');
+ assert.deepEqual(gateEvents(gate), ['start']);
+ writeFileSync(gate.release, 'released');
+ const [pushResult, competitorResult] = await Promise.all([pushed.closed, competitor.closed]);
+ assert.equal(pushResult.code, 0, pushed.stderrText);
+ assert.equal(competitorResult.code, 0, competitor.stderrText);
+ assert.deepEqual(gateEvents(gate), ['start', 'end', 'start', 'end']);
+ } finally {
+ writeFileSync(gate.release, 'released');
+ await Promise.all(children.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/relay.test.js b/test/relay.test.js
index e5bec2e8..fdb5fb93 100644
--- a/test/relay.test.js
+++ b/test/relay.test.js
@@ -1,11 +1,12 @@
/** Relay identity, expiry, permission freshness and scoped credential isolation [H8, H1]. */
import assert from 'node:assert/strict';
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { test } from 'node:test';
import { createGitHubClient } from '../relay/github.js';
import { createRelayAuth, ACCESS_WINDOW_MS } from '../relay/auth.js';
+import { serveRelay } from '../relay/service.js';
import { githubFixture } from './relay-fixture.js';
/** Use real private SQLite and an actual HTTP provider with a controllable expiry clock. */
@@ -134,6 +135,63 @@ test('revoking during an awaited GitHub write check refuses the pending write [H
await assert.rejects(pending, { code: 'AUTH_REQUIRED' });
});
+test('revoking a board credential while its upload body is open stores nothing [H8, A4, H7]', async (t) => {
+ const box = await fixture(t);
+ const person = await login(box);
+ const board = 'b'.repeat(32);
+ await box.auth.linkBoard(person.token, board, 'fixture/repository');
+ const agent = await box.auth.issueToken(person.token, { board, agent: 'revoked-during-upload' });
+ const service = await serveRelay({
+ directory: join(dirname(box.database), 'journal'), auth: box.auth, port: 0,
+ publicOrigin: 'http://127.0.0.1:44444', maintenanceMs: 0,
+ });
+ t.after(() => service.close());
+ const origin = `http://127.0.0.1:${service.port}`;
+ const snapshot = await fetch(`${origin}/api/v1/boards/${board}/state`, {
+ method: 'PUT',
+ headers: { authorization: `Bearer ${person.token}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ sequence: 0, sealed: 'AQ' }),
+ });
+ assert.equal(snapshot.status, 200);
+
+ let firstAuthenticationComplete;
+ let signaled = false;
+ const authenticated = new Promise((resolve) => { firstAuthenticationComplete = resolve; });
+ const authenticate = box.auth.authenticate;
+ box.auth.authenticate = async (...args) => {
+ const result = await authenticate(...args);
+ if (!signaled && args[1]?.board === board) {
+ signaled = true;
+ firstAuthenticationComplete();
+ }
+ return result;
+ };
+ let stream;
+ const upload = fetch(`${origin}/api/v1/boards/${board}/moves`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${agent.token}`, 'content-type': 'application/json' },
+ body: new ReadableStream({ start(controller) { stream = controller; controller.enqueue(Buffer.from('{"sequence":1,"sealed":"')); } }),
+ duplex: 'half',
+ });
+ await authenticated;
+ await new Promise((resolve) => setImmediate(resolve));
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ await box.auth.revoke(person.token, agent.id);
+ stream.enqueue(Buffer.from('AQ"}'));
+ stream.close();
+
+ const response = await upload;
+ const refusal = await response.json();
+ assert.equal(response.status, 401, JSON.stringify(refusal));
+ assert.equal(refusal.error.code, 'AUTH_REQUIRED');
+ const events = await fetch(`${origin}/api/v1/boards/${board}/events?after=0`, {
+ headers: { authorization: `Bearer ${person.token}` },
+ });
+ assert.equal(events.status, 200);
+ assert.deepEqual((await events.json()).events, [], 'the revoked upload never appends a move');
+ assert.equal(existsSync(join(dirname(box.database), 'journal', `${board}.journal.sqlite`)), true);
+});
+
test('a deleted and recreated repository cannot inherit the linked board [H8, H1]', async (t) => {
const box = await fixture(t);
const signed = await login(box);
diff --git a/test/resources.test.js b/test/resources.test.js
index dc31b4de..61cb5f90 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -2,7 +2,7 @@
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
import { once } from 'node:events';
-import { chmodSync, existsSync, mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
@@ -14,6 +14,7 @@ import { listResources, setResourceCapacity, takeResource } from '../src/resourc
const TEMP = [];
const CHILDREN = new Set();
const MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/resources.js')).href;
+const GATE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/gate.js')).href;
const PROCESS_INFO_POLICY = '(version 1)(allow default)(deny process-info*)';
const SANDBOX_EXEC = process.platform === 'darwin' && existsSync('/usr/bin/sandbox-exec');
const PERL_FORK = process.platform === 'darwin' && existsSync('/usr/bin/perl');
@@ -488,3 +489,51 @@ test('[Q1] machine scope is shared, repo scope stays local, and board scope name
assert.notEqual(refused.status, 0);
assert.match(refused.stderr, /BOARD_SCOPE_UNAVAILABLE.*relay/i);
});
+
+test('[Q4] a red gate releases its lease before the same process starts another gate', async () => {
+ const box = fixture();
+ const setting = spawnSync(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), 'settings', 'gateSlots', '1'], {
+ cwd: box.first, env: box.env, encoding: 'utf8',
+ });
+ assert.equal(setting.status, 0, setting.stderr);
+ const command = join(box.dir, 'red-then-green.cjs');
+ const counter = join(box.dir, 'gate-count');
+ const eventsFile = join(box.dir, 'gate-runs.log');
+ writeFileSync(command, [
+ "const fs = require('node:fs');",
+ 'const [counter, events] = process.argv.slice(2);',
+ 'const count = Number(fs.existsSync(counter) ? fs.readFileSync(counter, "utf8") : 0);',
+ 'fs.writeFileSync(counter, String(count + 1));',
+ "fs.appendFileSync(events, 'start\\nend\\n');",
+ 'process.exit(count === 0 ? 7 : 0);',
+ ].join('\n'));
+ const gateCommand = `${JSON.stringify(process.execPath)} ${JSON.stringify(command)} ${JSON.stringify(counter)} ${JSON.stringify(eventsFile)}`;
+ const worker = `
+ import { runGate } from ${JSON.stringify(GATE_MODULE)};
+ const first = await runGate(process.cwd(), { gate: process.argv[1] });
+ const second = await runGate(process.cwd(), { gate: process.argv[1] });
+ console.log(JSON.stringify({ firstGreen: first.isGreen, secondGreen: second.isGreen }));
+ `;
+ const child = spawn(process.execPath, ['--input-type=module', '-e', worker, gateCommand], {
+ cwd: box.first, env: box.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8').on('data', (chunk) => { stdout += chunk; });
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });
+ const closed = new Promise((resolveClose) => child.once('close', (code, signal) => resolveClose({ code, signal })));
+ let timer;
+ try {
+ const result = await Promise.race([
+ closed,
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('the red gate kept its lease and blocked the same process')), 5_000); }),
+ ]);
+ assert.equal(result.code, 0, stderr);
+ assert.deepEqual(JSON.parse(stdout.trim()), { firstGreen: false, secondGreen: true });
+ assert.deepEqual(readFileSync(eventsFile, 'utf8').trim().split(/\r?\n/u), ['start', 'end', 'start', 'end']);
+ } finally {
+ clearTimeout(timer);
+ if (child.exitCode === null && child.signalCode === null) process.kill(-child.pid, 'SIGKILL');
+ if (child.exitCode === null && child.signalCode === null) await closed;
+ }
+});
diff --git a/test/settings.test.js b/test/settings.test.js
new file mode 100644
index 00000000..d3690199
--- /dev/null
+++ b/test/settings.test.js
@@ -0,0 +1,36 @@
+/** Machine-wide gate capacity settings through the actual CLI [O5,O6]. */
+import assert from 'node:assert/strict';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { test } from 'node:test';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.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'], {
+ encoding: 'utf8', env: { ...process.env, PULLBOARD_HOME: home },
+ });
+}
+
+test('[O5,O6] gateSlots defaults to two, reads and sets atomically, and refuses invalid saved values', () => {
+ const home = mkdtempSync(join(tmpdir(), 'pullboard-settings-'));
+ try {
+ const initial = settings(home);
+ assert.equal(initial.status, 0, initial.stderr);
+ assert.equal(JSON.parse(initial.stdout).settings.gateSlots, 2);
+
+ const changed = settings(home, 'gateSlots', '3');
+ assert.equal(changed.status, 0, changed.stderr);
+ assert.equal(JSON.parse(changed.stdout).settings.gateSlots, 3);
+ assert.equal(JSON.parse(readFileSync(join(home, 'settings.json'), 'utf8')).gateSlots, 3);
+ assert.equal(JSON.parse(settings(home).stdout).settings.gateSlots, 3);
+
+ writeFileSync(join(home, 'settings.json'), JSON.stringify({ gateSlots: 0 }));
+ const refused = settings(home);
+ assert.equal(refused.status, 1);
+ assert.equal(JSON.parse(refused.stdout).error.code, 'BAD_GATE_SLOTS');
+ } finally { rmSync(home, { recursive: true, force: true }); }
+});