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(runners): account for open windows and browser saturation [C7,O5]

Corey Olson146d60bd5817
diff --git a/src/commands/stats.js b/src/commands/stats.js
index b90a5959..3dd56020 100644
--- a/src/commands/stats.js
+++ b/src/commands/stats.js
@@ -39,12 +39,11 @@ export function run(io, { values }) {
if (windowMinutes !== undefined) board.db.exec('SAVEPOINT stats_window_read');
try {
const stats = proofStats(board, { since: values.since, now });
- return { stats, agents: store.listAgents(board), ...(windowMinutes === undefined ? {} : {
- window: flowStats(store.events(board), null, now, stats, { windowMinutes,
- executionCapacity: readRunnerStage(ctx.info.root, {
- from: new Date(now - windowMinutes * 60_000).toISOString(), to: new Date(now).toISOString(),
- }) }).window,
- }) };
+ // The lifecycle projection validates the date range before capacity reads use its bounds.
+ const window = windowMinutes === undefined ? undefined
+ : flowStats(store.events(board), null, now, stats, { windowMinutes }).window;
+ if (window) window.executionCapacity = readRunnerStage(ctx.info.root, { from: window.since, to: window.until });
+ return { stats, agents: store.listAgents(board), ...(window ? { window } : {}) };
} finally {
if (windowMinutes !== undefined) board.db.exec('RELEASE stats_window_read');
}
diff --git a/src/runner-stage-read.js b/src/runner-stage-read.js
index c103ec80..8697b4d2 100644
--- a/src/runner-stage-read.js
+++ b/src/runner-stage-read.js
@@ -19,8 +19,7 @@ function reportedPlatform(receipts, id) {
}
/** Build current descriptors from validated settings and the live admission databases. */
-function currentRunners(settings, receipts) {
- const machineResources = listResources({ scope: 'machine' });
+function currentRunners(settings, receipts, machineResources) {
const gate = machineResources.find(resource => resource.name === 'gate');
const browserPool = machineResources.find(resource => resource.name === 'browser');
const localCapacity = gate?.capacity ?? settings.gateSlots;
@@ -47,8 +46,28 @@ function currentRunners(settings, receipts) {
/** Read retained physical-run receipts and live capacity for exactly `[from,to)`. */
export function readRunnerStage(root, { from, to }) {
- const receipts = retainedReceipts(root, { from, to });
const settings = loadMachineSettings();
- const runners = currentRunners(settings, receipts);
- return runnerStage(runners, receipts, { from, to });
+ // Bracket the receipt read with physical-holder snapshots. Changed snapshots are unmeasured,
+ // avoiding a finished receipt plus a stale open observation counting the same work twice.
+ const before = listResources({ scope: 'machine' }).find(resource => resource.name === 'gate')?.holders ?? [];
+ const receipts = retainedReceipts(root, { from, to });
+ const resources = listResources({ scope: 'machine' });
+ const holders = resources.find(resource => resource.name === 'gate')?.holders ?? [];
+ const observedUntil = new Date().toISOString();
+ const runners = currentRunners(settings, receipts, resources);
+ const local = runners[0];
+ const live = [];
+ if (JSON.stringify(before) !== JSON.stringify(holders)) {
+ live.push({ ongoing: true, observedUntil, admittedAt: null, runner: local });
+ } else {
+ for (const holder of holders) live.push({ ongoing: true, admittedAt: holder.since, observedUntil,
+ runner: local, timing: holder.timing === true,
+ // A timing bit does not attest the absence of unfenced legacy clients.
+ ...(holder.timing ? { exclusive: null } : {}) });
+ }
+ for (const runner of runners.slice(1)) {
+ // These are controller reservations, not the worker's physical admission timestamps.
+ if (runner.active > 0) live.push({ ongoing: true, admittedAt: null, observedUntil, runner });
+ }
+ return runnerStage(runners, [...receipts, ...live], { from, to });
}
diff --git a/src/runner-stage.js b/src/runner-stage.js
index 81251c3a..6bc18df4 100644
--- a/src/runner-stage.js
+++ b/src/runner-stage.js
@@ -115,6 +115,24 @@ export function runnerStage(runners, receipts, window = {}) {
const waits = [];
for (const receipt of receipts) {
if (!record(receipt) || receipt.inherited === true || receipt.slot?.kind === 'inherited') continue;
+ const ongoing = receipt.ongoing === true;
+ // A live observation is not a completion and never supplies a completed-run wait sample.
+ if (ongoing) {
+ const entry = record(receipt.runner) ? byId.get(receipt.runner.id) : null;
+ if (!entry) continue;
+ const admitted = timestamp(receipt.admittedAt);
+ const observed = timestamp(receipt.observedUntil);
+ const slots = record(receipt.runner.slots) ? receipt.runner.slots.current : null;
+ if (admitted === null || observed === null || observed < admitted || slots !== entry.runner.slots.current
+ || !nonnegativeInteger(slots) || receipt.timing !== undefined && typeof receipt.timing !== 'boolean'
+ || receipt.timing === true && (receipt.exclusive !== true || !Array.isArray(receipt.unfencedClients) || receipt.unfencedClients.length)) {
+ entry.unknownShare = true;
+ continue;
+ }
+ const overlap = Math.min(observed, end) - Math.max(admitted, start);
+ if (overlap > 0) entry.slotMs += overlap * (receipt.timing === true ? slots : 1);
+ continue;
+ }
const legacyAt = timestamp(receipt.at);
const legacyIntervalRelevant = timestamp(receipt.admittedAt) !== null && timestamp(receipt.finishedAt) !== null
&& timestamp(receipt.finishedAt) > start && timestamp(receipt.admittedAt) < end;
@@ -201,6 +219,14 @@ function capabilityMatch(runner, requested) {
return unknown ? 'unknown' : 'yes';
}
+/** Use the same known slot and browser-capacity facts for placement and saturation. */
+function availableCapacity(runner, capabilities) {
+ if (runner.unavailable || runner.draining || runner.active >= runner.slots.current) return false;
+ if (capabilities.browser !== true) return true;
+ if (runner.browserSlots !== undefined) return runner.browserActive < runner.browserSlots;
+ return runner.active === 0;
+}
+
/** Prefer known-compatible, fixed and less-busy available candidates deterministically. */
function candidateOrder(left, right) {
return Number(left.match !== 'yes') - Number(right.match !== 'yes')
@@ -233,12 +259,7 @@ export function placeRunner(stage, request = {}) {
if (new Set(rows.map(runner => runner.id)).size !== rows.length) invalid('runner IDs must be unique');
const candidates = rows.map(runner => ({ runner, match: capabilityMatch(runner, capabilities) }))
.filter(candidate => candidate.match !== 'no');
- const available = candidates.filter(({ runner }) => {
- if (runner.unavailable || runner.draining || runner.active >= runner.slots.current) return false;
- if (capabilities.browser !== true) return true;
- if (runner.browserSlots !== undefined) return runner.browserActive < runner.browserSlots;
- return runner.active === 0;
- }).sort(candidateOrder);
+ const available = candidates.filter(({ runner }) => availableCapacity(runner, capabilities)).sort(candidateOrder);
if (available.length) {
const best = available[0];
if (best.match === 'yes') return { action: 'run', runnerId: best.runner.id };
@@ -248,7 +269,11 @@ export function placeRunner(stage, request = {}) {
const fixed = candidates.filter(({ runner }) => !runner.slots.elastic && !runner.unavailable && !runner.draining);
const elastic = candidates.filter(({ runner, match }) => runner.slots.elastic && match === 'yes' && !runner.unavailable && !runner.draining);
- const fixedBusy = fixed.length > 0 && fixed.every(({ runner }) => runner.active >= runner.slots.current);
+ const fixedBusy = fixed.length > 0 && fixed.every(({ runner }) => {
+ // Unknown browser use may require waiting, but does not establish measured browser saturation.
+ if (capabilities.browser === true && runner.active < runner.slots.current && runner.browserSlots === undefined) return false;
+ return !availableCapacity(runner, capabilities);
+ });
const highWait = stage.slotWait.medianMs !== null && stage.slotWait.medianMs > slotWaitTargetMs;
if (fixedBusy && highWait) {
const expandable = elastic.filter(({ runner }) => runner.slots.current < runner.slots.limit)
diff --git a/test/runner-stage.test.js b/test/runner-stage.test.js
index 540d5092..df63abce 100644
--- a/test/runner-stage.test.js
+++ b/test/runner-stage.test.js
@@ -10,6 +10,8 @@ import { localRunnerDescriptor } from '../src/runner-load.js';
import { recordReceipt } from '../src/gate-receipt.js';
import * as runnerApi from '../src/runners.js';
import { runFixtureGit } from './fixture-child.js';
+import { takeResource } from '../src/resources.js';
+import { readRunnerStage } from '../src/runner-stage-read.js';
/** Capture the actual CLI response while supplying a deterministic observation clock. */
async function run(root, args, clock) {
@@ -90,3 +92,79 @@ test('[C7,O5] legacy receipt timestamps leave runner shares and counts unknown',
assert.deepEqual(stage.runners.map(row => [row.busyShare, row.runsServed]), [[null, null], [null, null]]);
assert.deepEqual(stage.slotWait, { fastQuarterMs: 10, medianMs: 10, slowQuarterMs: 10, worstMs: 10, count: 1 });
});
+
+
+/** Keep a real local admission open while observing a controlled physical interval. */
+test('[C7,O5] an ongoing physical local holder contributes window occupancy without a completion', async t => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-live-runner-stage-')));
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, stdio: 'pipe' });
+ const board = store.openBoard(join(root, '.git', 'pullboard', 'board.sqlite'));
+ const machineHome = join(root, 'machine');
+ mkdirSync(machineHome, { recursive: true });
+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 2, browserSlots: 1 }));
+ const prior = process.env.PULLBOARD_MACHINE_HOME;
+ process.env.PULLBOARD_MACHINE_HOME = machineHome;
+ const now = Date.now();
+ t.mock.timers.enable({ apis: ['Date'], now });
+ let lease;
+ try {
+ lease = await takeResource({ name: 'gate', capacity: 2, scope: 'machine', root,
+ agent: 'private-ongoing-holder', item: 'ongoing', kind: 'check' });
+ t.mock.timers.tick(10_000);
+ const stage = readRunnerStage(root, { from: new Date(now).toISOString(), to: new Date(now + 10_000).toISOString() });
+ const local = stage.runners.find(runner => runner.kind === 'local');
+ assert.equal(local.active, 1);
+ assert.equal(local.busyShare, 0.5, 'one physical admission occupied half of two slots through the observation');
+ assert.equal(local.runsServed, 0, 'the still-held run is not a completion');
+ assert.equal(stage.slotWait.count, 0, 'an open admission does not invent a completed receipt wait');
+ } finally {
+ lease?.release();
+ if (prior === undefined) delete process.env.PULLBOARD_MACHINE_HOME;
+ else process.env.PULLBOARD_MACHINE_HOME = prior;
+ store.closeBoard(board);
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+
+test('[C7,O5] open observations clip occupancy and leave remote admission or timing exclusivity unknown', () => {
+ const window = { from: '2026-10-24T11:00:00.000Z', to: '2026-10-24T12:00:00.000Z' };
+ const local = { id: 'local:open', kind: 'local', slots: { current: 2, limit: 2, elastic: false },
+ capabilities: { os: 'darwin', browser: true }, active: 1 };
+ const remote = { ...local, id: 'ssh:reserved', kind: 'ssh' };
+ const stage = runnerApi.runnerStage([local, remote], [
+ { ongoing: true, runner: local, admittedAt: '2026-10-24T10:30:00.000Z', observedUntil: '2026-10-24T11:30:00.000Z', waitMs: 999 },
+ { ongoing: true, runner: remote, admittedAt: null, observedUntil: '2026-10-24T11:30:00.000Z' },
+ ], window);
+ assert.equal(stage.runners[0].busyShare, 0.25);
+ assert.equal(stage.runners[0].runsServed, 0);
+ assert.equal(stage.runners[1].busyShare, null, 'a controller reservation has no actual worker admitted boundary');
+ assert.equal(stage.runners[1].runsServed, 0);
+ assert.equal(stage.slotWait.count, 0);
+ const timing = runnerApi.runnerStage([local], [{ ongoing: true, runner: local, timing: true,
+ admittedAt: window.from, observedUntil: window.to }], window);
+ assert.equal(timing.runners[0].busyShare, null, 'a timing flag alone cannot attest absence of legacy peers');
+});
+
+
+test('[C7,O5] measured browser saturation scales compatible elastic capacity without blocking ordinary work', () => {
+ const window = { from: '2026-10-24T11:00:00.000Z', to: '2026-10-24T12:00:00.000Z' };
+ const fixed = { id: 'fixed', kind: 'ssh', slots: { current: 2, limit: 2, elastic: false },
+ capabilities: { os: 'darwin', browser: true }, active: 1, browserSlots: 1, browserActive: 1 };
+ const elastic = { id: 'elastic', kind: 'elastic', slots: { current: 0, limit: 4, elastic: true },
+ capabilities: { os: 'darwin', browser: true }, active: 0 };
+ const stage = { ...runnerApi.runnerStage([fixed, elastic], [], window), slotWait: { medianMs: 50 } };
+ const browser = { capabilities: { browser: true }, slotWaitTargetMs: 10 };
+ assert.deepEqual(runnerApi.placeRunner(stage, browser), { action: 'scale', runnerId: 'elastic', slots: 1 });
+ assert.deepEqual(runnerApi.placeRunner(stage, { ...browser, slotWaitTargetMs: 100 }), { action: 'wait' });
+ assert.deepEqual(runnerApi.placeRunner(stage, { capabilities: { browser: false }, slotWaitTargetMs: 10 }), { action: 'run', runnerId: 'fixed' });
+ const full = { ...stage, runners: stage.runners.map(runner => runner.id === 'elastic'
+ ? { ...runner, slots: { ...runner.slots, current: 4 }, active: 4 } : runner) };
+ assert.deepEqual(runnerApi.placeRunner(full, browser), { action: 'request' });
+ const unknown = { ...stage, runners: stage.runners.map(runner => {
+ if (runner.id !== 'fixed') return runner;
+ const { browserSlots, browserActive, ...rest } = runner;
+ return rest;
+ }) };
+ assert.deepEqual(runnerApi.placeRunner(unknown, browser), { action: 'wait' }, 'unknown browser occupancy is not measured saturation');
+});