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(resources): reviews go before submits before focused runs [C7,V4]

Corey Olson6f44a7baade3
diff --git a/src/cli.js b/src/cli.js
index 59023459..bdb1ec1e 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -1821,7 +1821,7 @@ function readCommands(io, { first, second, rest, values }) {
for (const resource of resources) {
io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})`);
for (const holder of resource.holders) io.say(` held by ${agentDisplayName(agents, ctx.config, holder.agent)}${holder.repo ? ` in ${holder.repo}` : ''}${resourceRunLabel(holder)} since ${holder.since}`);
- resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${resourceRunLabel(waiter)}`));
+ resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${resourceRunLabel(waiter)}; class ${waiter.queueClass}${waiter.agedFrom ? `, aged up from ${waiter.agedFrom}` : ''}`));
}
return 0;
},
diff --git a/src/resources.js b/src/resources.js
index 635f9dde..e17bf026 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -1,4 +1,4 @@
-/** Machine and repository queues persist leases; landings go first, then eligible waiters in arrival order [Q1,Q2,Q3]. */
+/** Machine and repository queues persist leases; waiters are admitted by class (landing, review, submit, other), aging up over time, then in arrival order [Q1,Q2,Q3]. */
import { mkdirSync, realpathSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { basename, dirname, join, resolve } from 'node:path';
@@ -171,8 +171,38 @@ function update(db, action) {
}
}
-/** Current holders and the landing-first line, then every other kind in arrival order. */
-function snapshot(db, name) {
+/** Admission classes, most urgent first. */
+export const QUEUE_CLASSES = ['landing', 'review', 'submit', 'other'];
+/** A waiter moves up one class for every this long it has waited, so no class starves. */
+export const QUEUE_AGE_MS = 30 * 60_000;
+
+/**
+ * A waiter's admission class: its declared class from the run it names, and the class it holds now
+ * after aging up one class per QUEUE_AGE_MS waited. Landings come first, then reviews (they unblock
+ * landing), then submits and item checks, then focused, diagnostic and every other run.
+ *
+ * @param {{ landing?: number|boolean, itemCheck?: number|boolean, diagnostic?: number|boolean, kind?: string, since?: string }} entry
+ * @param {number} [now] - The clock reading to age against; injectable so tests need not wait.
+ * @returns {{ base: number, effective: number, name: string, declared: string }}
+ */
+export function queueClass(entry, now = Date.now()) {
+ const kind = entry.kind ?? '';
+ const base = entry.landing === true || entry.landing === 1 ? 0
+ : kind === 'review' ? 1
+ : !(entry.diagnostic === true || entry.diagnostic === 1) && (entry.itemCheck === true || entry.itemCheck === 1 || kind === 'submit' || kind === 'check') ? 2
+ : 3;
+ const waited = Math.max(0, now - (Date.parse(entry.since ?? '') || now));
+ const effective = Math.max(0, base - Math.floor(waited / QUEUE_AGE_MS));
+ return { base, effective, name: QUEUE_CLASSES[effective], declared: QUEUE_CLASSES[base] };
+}
+
+/** Sort waiters by their current class, then by arrival ticket within a class. */
+function byAdmission(now) {
+ return (left, right) => queueClass(left, now).effective - queueClass(right, now).effective || left.ticket - right.ticket;
+}
+
+/** Current holders and the waiting line in admission order, each waiter naming its class. */
+function snapshot(db, name, now = Date.now()) {
/** Preserve older public entries while naming diagnostics as a distinct queue class. */
const project = ({ diagnostic, browser, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,
itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),
@@ -181,14 +211,19 @@ function snapshot(db, name) {
const where = name === 'browser' ? 'name = ? AND browser = 1' : 'name = ?';
const sourceName = name === 'browser' ? 'gate' : name;
const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM holder WHERE ${where} ORDER BY since, token`).all(sourceName).map(project);
- const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);
+ const line = db.prepare(`SELECT ticket, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM waiter WHERE ${where}`).all(sourceName)
+ .sort(byAdmission(now))
+ .map(({ ticket, ...entry }) => {
+ const queued = queueClass(entry, now);
+ return { ...project(entry), queueClass: queued.name, ...(queued.effective < queued.base ? { agedFrom: queued.declared } : {}) };
+ });
return { holders, line };
}
/** Count reported or admissible queue position separately so blocked work cannot distort the visible line. */
-function waiterPosition(db, name, ticket, { eligibleOnly = false } = {}) {
+function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now() } = {}) {
const queueName = name === 'browser' ? 'gate' : name;
- const waiters = db.prepare('SELECT ticket, pid, agent, repo, landing, item_check AS itemCheck, browser FROM waiter WHERE name = ? ORDER BY ticket').all(queueName);
+ const waiters = db.prepare('SELECT ticket, pid, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, kind FROM waiter WHERE name = ? ORDER BY ticket').all(queueName);
const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(queueName);
const browserBusy = db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count > 0;
/** A live process owns its leases even if it changes descriptive agent or repository labels. */
@@ -196,8 +231,8 @@ function waiterPosition(db, name, ticket, { eligibleOnly = false } = {}) {
/** Leave a waiting independent landing a slot before a holder takes another lease. */
const blockedByLanding = (waiter) => holdsSlot(waiter)
&& waiters.some((other) => other.landing === 1 && other.pid !== waiter.pid);
- /** Map queue entries to their declared precedence class. */
- const rank = (waiter) => waiter.landing === 1 ? 0 : 1;
+ /** Map queue entries to their current admission class, aged by how long each has waited. */
+ const rank = (waiter) => queueClass(waiter, now).effective;
const line = name === 'browser' ? waiters.filter((waiter) => waiter.browser === 1) : waiters;
const considered = line.filter((waiter) => !blockedByLanding(waiter)
// Browser availability affects admission only; reported positions retain every browser waiter.
@@ -214,7 +249,7 @@ function waiterPosition(db, name, ticket, { eligibleOnly = false } = {}) {
function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); }
/**
- * Join the landing-first queue; every other kind keeps its original FIFO ticket.
+ * Join the queue in its admission class (landing, review, submit, other), aging up over time; FIFO by ticket within a class.
*
* @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.
* @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}
@@ -264,7 +299,7 @@ export async function takeResource(options) {
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();
}
- // Retain queue metadata for older readers; admission uses landing priority and arrival only.
+ // The kind and flags decide the admission class; the ticket keeps arrival order within it.
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);
});
while (true) {
diff --git a/test/resources.test.js b/test/resources.test.js
index 7d8d81d0..7f06bf1b 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -10,7 +10,7 @@ import { pathToFileURL } from 'node:url';
import { createInterface } from 'node:readline';
import { after, test } from 'node:test';
import { DatabaseSync } from 'node:sqlite';
-import { listResources, setResourceCapacity, takeResource } from '../src/resources.js';
+import { QUEUE_AGE_MS, listResources, queueClass, setResourceCapacity, takeResource } from '../src/resources.js';
import { checkNeedsBrowser } from '../src/browser-admission.js';
const TEMP = [];
@@ -503,7 +503,8 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
const diagnosticOne = poolWorker(orderBox, { agent: 'diagnostic-one', kind: 'diagnostic' });
assert.equal((await event(diagnosticOne)).queued.position, 2);
const laterReview = poolWorker(orderBox, { agent: 'later-review', item: '621', kind: 'review' });
- assert.equal((await event(laterReview)).queued.position, 3);
+ // #651: a review joins ahead of the older focused and diagnostic runs, in its own class.
+ assert.equal((await event(laterReview)).queued.position, 1);
const diagnosticTwo = poolWorker(orderBox, { agent: 'diagnostic-two', kind: 'diagnostic' });
assert.equal((await event(diagnosticTwo)).queued.position, 4);
const laterGate = poolWorker(orderBox, { agent: 'later-gate', kind: 'focused' });
@@ -514,12 +515,12 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
assert.deepEqual(orderedGate.line.map(({ agent, landing, diagnostic, itemCheck, kind }) =>
[agent, landing, diagnostic === true, itemCheck, kind ?? '']), [
['later-landing', true, false, false, ''],
+ ['later-review', false, false, true, 'review'],
['later-focused', false, false, false, 'focused'],
['diagnostic-one', false, true, false, 'diagnostic'],
- ['later-review', false, false, true, 'review'],
['diagnostic-two', false, true, false, 'diagnostic'],
['later-gate', false, false, false, 'focused'],
- ], 'landing moves ahead while all other kinds retain their arrival order');
+ ], 'landing, then the review, then focused and diagnostic runs in their arrival order (#651)');
await release(otherHolder);
assert.equal((await acquired(laterLanding)).acquired, 'later-landing',
@@ -528,16 +529,16 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
assert.ok(orderedGate.holders.some(({ agent, landing }) => agent === 'later-landing' && landing));
await release(laterLanding);
+ assert.equal((await acquired(laterReview)).acquired, 'later-review',
+ 'a later review is admitted ahead of older focused and diagnostic runs (#651)');
+ await release(laterReview);
assert.equal((await acquired(laterFocused)).acquired, 'later-focused',
- 'the oldest eligible non-landing waiter acquires next');
+ 'the oldest focused or diagnostic waiter acquires after the review');
await release(laterFocused);
assert.equal((await acquired(diagnosticOne)).acquired, 'diagnostic-one');
await release(diagnosticOne);
- assert.equal((await acquired(laterReview)).acquired, 'later-review',
- 'a diagnostic does not yield its older ticket to a later item check');
- await release(laterReview);
assert.equal((await acquired(diagnosticTwo)).acquired, 'diagnostic-two',
- 'diagnostics keep their FIFO place around a later item check');
+ 'diagnostics keep their FIFO place among focused runs');
await release(diagnosticTwo);
assert.equal((await acquired(laterGate)).acquired, 'later-gate',
'a diagnostic does not yield its older ticket to later ordinary gate work');
@@ -596,6 +597,77 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
await release(secondReview);
});
+test('the pool admits reviews before submits before focused runs, and waiting runs age up [C7,V4]', async () => {
+ const queuedAt = Date.parse('2026-10-15T19:37:00.000Z');
+ const at = (minutes) => queuedAt + minutes * 60_000;
+ const since = new Date(queuedAt).toISOString();
+ assert.equal(QUEUE_AGE_MS, 30 * 60_000, 'a waiter moves up one class every 30 minutes');
+ assert.deepEqual([0, 29, 30, 60, 90, 300].map((minutes) => queueClass({ kind: 'focused', since }, at(minutes)).name),
+ ['other', 'other', 'submit', 'review', 'landing', 'landing'], 'a focused run ages up one class per 30 minutes waited');
+ assert.equal(queueClass({ kind: 'review', since }, at(30)).name, 'landing');
+ assert.equal(queueClass({ kind: 'main-red', diagnostic: 1, itemCheck: 1, since }, at(0)).name, 'other', 'a diagnostic is optional work');
+ assert.equal(queueClass({ kind: 'check', itemCheck: 1, since }, at(0)).name, 'submit', 'an item check ranks with submits');
+ assert.equal(queueClass({ landing: 1, since }, at(0)).name, 'landing');
+
+ const box = fixture();
+ const holders = [poolWorker(box, { agent: 'holder-one' }), poolWorker(box, { agent: 'holder-two' })];
+ for (const holder of holders) await acquired(holder);
+ const waiting = new Map();
+ const positions = {};
+ for (const [agent, options] of [
+ ['focused-one', { kind: 'focused' }],
+ ['diagnostic-one', { kind: 'diagnostic' }],
+ ['submit-one', { kind: 'submit', item: '650' }],
+ ['review-one', { kind: 'review', item: '651' }],
+ ['landing-one', { landing: true }],
+ ['focused-two', { kind: 'focused' }],
+ ]) {
+ const child = poolWorker(box, { agent, ...options });
+ waiting.set(agent, child);
+ positions[agent] = (await event(child)).queued.position;
+ }
+ assert.deepEqual(positions, { 'focused-one': 1, 'diagnostic-one': 2, 'submit-one': 1, 'review-one': 1, 'landing-one': 1, 'focused-two': 6 },
+ 'each arrival takes its place by class, behind earlier runs of its own class');
+ const line = () => privateList(box).find(({ name }) => name === 'gate').line
+ .map(({ agent, queueClass: listed, agedFrom }) => [agent, listed, agedFrom ?? '']);
+ assert.deepEqual(line(), [
+ ['landing-one', 'landing', ''],
+ ['review-one', 'review', ''],
+ ['submit-one', 'submit', ''],
+ ['focused-one', 'other', ''],
+ ['diagnostic-one', 'other', ''],
+ ['focused-two', 'other', ''],
+ ], 'landing, then reviews, then submits, then focused and other runs, first come first served within each');
+
+ // Waiting time is the only input to aging; backdating the queued time stands in for the clock.
+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));
+ try {
+ const backdate = db.prepare('UPDATE waiter SET since = ? WHERE agent = ?');
+ backdate.run(new Date(Date.now() - 2 * QUEUE_AGE_MS - 60_000).toISOString(), 'focused-two');
+ backdate.run(new Date(Date.now() - QUEUE_AGE_MS - 60_000).toISOString(), 'diagnostic-one');
+ } finally { db.close(); }
+ assert.deepEqual(line(), [
+ ['landing-one', 'landing', ''],
+ ['review-one', 'review', ''],
+ ['focused-two', 'review', 'other'],
+ ['diagnostic-one', 'submit', 'other'],
+ ['submit-one', 'submit', ''],
+ ['focused-one', 'other', ''],
+ ], 'a run waiting an hour ranks with reviews and one waiting half an hour with submits, keeping its arrival place there');
+
+ const order = [];
+ let releasing = [...holders];
+ for (const agent of ['landing-one', 'review-one', 'focused-two', 'diagnostic-one', 'submit-one', 'focused-one']) {
+ await release(releasing.shift());
+ const child = waiting.get(agent);
+ assert.equal((await acquired(child)).acquired, agent, `${agent} is admitted next`);
+ order.push(agent);
+ releasing.push(child);
+ }
+ for (const child of releasing) await release(child);
+ assert.deepEqual(order, ['landing-one', 'review-one', 'focused-two', 'diagnostic-one', 'submit-one', 'focused-one']);
+});
+
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' });