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(settings): configure machine browser slots [C7]

Corey Olson5be24230d9a7
diff --git a/src/cli.js b/src/cli.js
index d421104b..0fff5b6d 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -77,7 +77,7 @@ import { flowLines, flowAlertLine } from './stats-flow.js';
import { releaseHeadlinesBetween } from './changelog.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
-import { loadMachineSettings, setGateSlots } from './settings.js';
+import { loadMachineSettings, setBrowserSlots, setGateSlots } from './settings.js';
import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';
import { autoLinkProject, relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';
import { readRelayMachine } from './relay-machine.js';
@@ -1811,11 +1811,13 @@ function readCommands(io, { first, second, rest, values }) {
resources: () => {
const ctx = context(io);
const agents = withBoard(ctx, (board) => store.listAgents(board));
+ const browserSlots = loadMachineSettings().browserSlots;
const resources = [
...listResources({ scope: 'machine' }).map((resource) => ({ ...resource, scope: 'machine' })),
...listResources({ scope: 'repo', root: ctx.info.root }).map((resource) => ({ ...resource, scope: 'repo' })),
];
- io.result?.({ resources });
+ io.result?.({ resources, browserSlots });
+ io.say(`browserSlots (machine setting): ${browserSlots}`);
if (!resources.length) io.say('no resources have been used');
for (const resource of resources) {
io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})`);
@@ -2836,14 +2838,18 @@ function settingsCommand(io, { first, second, rest }) {
const settings = loadMachineSettings();
io.result?.({ settings });
io.say(`gateSlots: ${settings.gateSlots}`);
+ io.say(`browserSlots: ${settings.browserSlots}`);
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>');
+ if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {
+ throw new Refused('USAGE', 'pullboard settings gateSlots <n> | browserSlots <n>');
}
- const settings = setGateSlots(Number(second));
+ if (!/^[1-9]\d*$/u.test(second) || !Number.isSafeInteger(Number(second))) {
+ throw new Refused(first === 'browserSlots' ? 'BAD_BROWSER_SLOTS' : 'BAD_GATE_SLOTS', `${first} must be a positive integer; run pullboard settings ${first} <n>`);
+ }
+ const settings = first === 'browserSlots' ? setBrowserSlots(Number(second)) : setGateSlots(Number(second));
io.result?.({ settings });
- io.say(`gateSlots set to ${settings.gateSlots}`);
+ io.say(`${first} set to ${settings[first]}`);
return 0;
}
diff --git a/src/gate.js b/src/gate.js
index 7a0f2ccd..924af6da 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -274,11 +274,13 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =
try { return await action(inherited); }
finally { inherited.release(); }
}
- const capacityProvider = () => loadMachineSettings().gateSlots;
+ const settingsProvider = () => loadMachineSettings();
+ const capacityProvider = () => settingsProvider().gateSlots;
const lease = await takeResource({
name: 'gate',
capacity: capacityProvider(),
capacityProvider,
+ browserCapacityProvider: () => settingsProvider().browserSlots,
scope: 'machine',
root,
repo: root,
diff --git a/src/resources.js b/src/resources.js
index 635f9dde..671cbcd9 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -216,7 +216,7 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr
/**
* Join the landing-first queue; every other kind keeps its original FIFO ticket.
*
- * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.
+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, browserCapacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.
* @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}
*/
export async function takeResource(options) {
@@ -259,10 +259,20 @@ 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);
- if (browser) {
+ if (name === 'gate' && scope === 'machine') {
+ const browserCapacity = options.browserCapacityProvider?.() ?? 1;
+ if (!Number.isSafeInteger(browserCapacity) || browserCapacity < 1 || browserCapacity > currentCapacity) {
+ throw new Refused('BAD_BROWSER_SLOTS', `browser capacity must be a positive integer no greater than gate capacity (${currentCapacity}); run pullboard settings browserSlots <n>`);
+ }
const browserResource = db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get();
- if (browserResource && browserResource.capacity !== 1) throw new Refused('RESOURCE_CAPACITY_MISMATCH', 'resource "browser" has fixed capacity 1');
- db.prepare("INSERT INTO resource(name, capacity) VALUES ('browser', 1) ON CONFLICT(name) DO NOTHING").run();
+ if (browserResource && browserResource.capacity !== browserCapacity) {
+ const state = snapshot(db, 'browser');
+ if (!allowIdleCapacityUpdate || state.holders.length || state.line.length) {
+ throw new Refused('RESOURCE_CAPACITY_MISMATCH', `resource "browser" already has capacity ${browserResource.capacity}`);
+ }
+ db.prepare("UPDATE resource SET capacity = ? WHERE name = 'browser'").run(browserCapacity);
+ }
+ db.prepare("INSERT INTO resource(name, capacity) VALUES ('browser', ?) ON CONFLICT(name) DO NOTHING").run(browserCapacity);
}
// Retain queue metadata for older readers; admission uses landing priority and arrival only.
db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
@@ -282,7 +292,8 @@ export async function takeResource(options) {
const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;
const browserAdmissionPosition = browser ? waiterPosition(db, 'browser', waiter.ticket, { eligibleOnly: true }) : 0;
const browserHolders = browser ? db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count : 0;
- if (admissionPosition === 1 && spot.holders.length < limit && (!browser || (browserAdmissionPosition === 1 && browserHolders < 1))) {
+ const browserLimit = browser ? db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get().capacity : 0;
+ if (admissionPosition === 1 && spot.holders.length < limit && (!browser || (browserAdmissionPosition === 1 && browserHolders < browserLimit))) {
db.prepare('DELETE FROM waiter WHERE token = ?').run(token);
const acquiredAt = new Date().toISOString();
db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
@@ -361,13 +372,12 @@ export function inheritedGateSlot({ root = process.cwd(), browser = false } = {}
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');
- if (name === 'browser' && capacity !== 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'browser resource capacity is fixed at 1');
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}`);
+ 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 ${name === 'browser' ? 'browserSlots' : 'gateSlots'} ${capacity}`);
}
persist();
db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET capacity = excluded.capacity').run(name, capacity);
diff --git a/src/settings.js b/src/settings.js
index 0c5f6c51..7dc7904d 100644
--- a/src/settings.js
+++ b/src/settings.js
@@ -7,6 +7,7 @@ import { setResourceCapacity } from './resources.js';
import { Refused } from './refused.js';
const DEFAULT_GATE_SLOTS = 2;
+const DEFAULT_BROWSER_SLOTS = 1;
/** Resolve the separate machine settings file. */
export function machineSettingsFile() {
@@ -16,7 +17,7 @@ export function machineSettingsFile() {
/** Read and validate machine settings, preserving any unrelated settings. */
export function loadMachineSettings() {
const file = machineSettingsFile();
- if (!existsSync(file)) return { gateSlots: DEFAULT_GATE_SLOTS };
+ if (!existsSync(file)) return { gateSlots: DEFAULT_GATE_SLOTS, browserSlots: DEFAULT_BROWSER_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`); }
@@ -27,7 +28,11 @@ export function loadMachineSettings() {
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 };
+ const browserSlots = value.browserSlots ?? DEFAULT_BROWSER_SLOTS;
+ if (!Number.isSafeInteger(browserSlots) || browserSlots < 1 || browserSlots > gateSlots) {
+ throw new Refused('BAD_BROWSER_SLOTS', `browserSlots in ${file} must be a positive integer no greater than gateSlots (${gateSlots}); run pullboard settings browserSlots <n>`);
+ }
+ return { ...value, gateSlots, browserSlots };
}
/** Atomically replace machine settings without exposing a partial JSON file. */
@@ -44,8 +49,25 @@ function writeMachineSettings(settings) {
/** 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) });
+ let next;
+ setResourceCapacity({ name: 'gate', capacity, scope: 'machine', persist: () => {
+ const current = loadMachineSettings();
+ if (capacity < current.browserSlots) throw new Refused('BAD_GATE_SLOTS', `gateSlots cannot be lower than browserSlots (${current.browserSlots}); first run pullboard settings browserSlots <n>`);
+ next = { ...current, gateSlots: capacity };
+ writeMachineSettings(next);
+ } });
+ return next;
+}
+
+/** Set machine browser capacity only when its browser holders and waiters are empty. */
+export function setBrowserSlots(capacity) {
+ if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_BROWSER_SLOTS', 'browserSlots must be a positive integer; run pullboard settings browserSlots <n>');
+ let next;
+ setResourceCapacity({ name: 'browser', capacity, scope: 'machine', persist: () => {
+ const current = loadMachineSettings();
+ if (capacity > current.gateSlots) throw new Refused('BAD_BROWSER_SLOTS', `browserSlots cannot exceed gateSlots (${current.gateSlots}); run pullboard settings gateSlots <n> first`);
+ next = { ...current, browserSlots: capacity };
+ writeMachineSettings(next);
+ } });
return next;
}
diff --git a/test/resources.test.js b/test/resources.test.js
index 08f065b9..db759c86 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -16,12 +16,16 @@ 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 SETTINGS_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/settings.js')).href;
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
const POOL_MODULE_WORKER = `
import { takeResource } from ${JSON.stringify(MODULE)};
+import { loadMachineSettings } from ${JSON.stringify(SETTINGS_MODULE)};
let announced = false;
const [root, agent, browserText, item, kind, landingText] = process.argv.slice(1);
const lease = await takeResource({
name: 'gate', capacity: 2, scope: 'machine', root, agent,
+ browserCapacityProvider: () => loadMachineSettings().browserSlots,
browser: browserText === 'true', item, kind, itemCheck: kind === 'review',
diagnostic: kind === 'diagnostic', landing: landingText === 'true',
onWait: (state) => {
@@ -218,6 +222,13 @@ function poolWorker(box, { agent, browser = false, item = '', kind = '', landing
return child;
}
+/** Configure browser slots through the public CLI in this fixture's private machine home. */
+function configureBrowserSlots(box, slots) {
+ return runFixtureChild(process.execPath, [BIN, 'settings', 'browserSlots', String(slots), '--json'], {
+ cwd: box.first, env: box.env, encoding: 'utf8',
+ });
+}
+
/** Read the next worker event, failing promptly with its stderr if it exits unexpectedly. */
async function event(child, timeoutMs = 10_000) {
if (child.pendingLines.length) return JSON.parse(child.pendingLines.shift());
@@ -305,6 +316,42 @@ after(async () => {
TEMP.forEach((dir) => rmSync(dir, { recursive: true, force: true }));
});
+/** Prove the machine setting changes real browser admission while retaining the single-slot default [C7]. */
+test('browserSlots admits that many browser runs and no more [C7]', async () => {
+ const defaults = fixture();
+ const defaultSettings = runFixtureChild(process.execPath, [BIN, 'settings', '--json'], {
+ cwd: defaults.first, env: defaults.env, encoding: 'utf8',
+ });
+ assert.equal(defaultSettings.status, 0, defaultSettings.stderr);
+ assert.equal(JSON.parse(defaultSettings.stdout).settings.browserSlots, 1, 'an unset machine keeps the existing single browser slot');
+
+ const box = fixture();
+ const configured = configureBrowserSlots(box, 2);
+ assert.equal(configured.status, 0, configured.stderr);
+ assert.equal(JSON.parse(configured.stdout).settings.browserSlots, 2);
+ const invalid = configureBrowserSlots(box, 3);
+ assert.equal(invalid.status, 1);
+ assert.equal(JSON.parse(invalid.stdout).error.code, 'BAD_BROWSER_SLOTS');
+ assert.match(JSON.parse(invalid.stdout).error.message, /pullboard settings gateSlots/u);
+
+ const first = poolWorker(box, { agent: 'browser-one', browser: true });
+ assert.equal((await acquired(first)).acquired, 'browser-one');
+ const second = poolWorker(box, { agent: 'browser-two', browser: true });
+ assert.equal((await acquired(second)).acquired, 'browser-two', 'the configured second browser lease starts while the first is held');
+ const third = poolWorker(box, { agent: 'browser-three', browser: true });
+ assert.equal((await event(third)).queued.position, 1, 'the next browser run waits for a configured slot');
+ const browser = privateList(box).find(({ name }) => name === 'browser');
+ assert.equal(browser.capacity, 2, 'resource listing reflects the machine browserSlots setting');
+ assert.equal(browser.holders.length, 2);
+ assert.deepEqual(browser.holders.map(({ agent }) => agent).sort(), ['browser-one', 'browser-two']);
+ assert.deepEqual(browser.line.map(({ agent }) => agent), ['browser-three']);
+
+ await release(first);
+ assert.equal((await acquired(third)).acquired, 'browser-three', 'a released browser lease admits the oldest waiting browser run');
+ await release(second);
+ await release(third);
+});
+
test('[Q1,Q2] capacity-one takers acquire in strict FIFO arrival order', async () => {
const box = fixture();
const holder = worker(box, { agent: 'holder' });