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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(core): add leased resource queues [Q1,Q2,Q3]
Corey Olson847878ae8666
diff --git a/docs/api.md b/docs/api.mdindex 40a88392..8d883508 100644--- a/docs/api.md+++ b/docs/api.md@@ -20,6 +20,7 @@ A successful command returns the fields listed below. `version` is always the nu| `resume` | `version:number`, `me:object`, `all:array`, `requests:array`, `holding:array`, `sentBack:array`, `awaiting:array`, `toVerify:array`, `toMerge:array`, `open:array`, `holds:array`, `unread:number`, `newest:array`, `root:string`, `dirty:number`, `next:string` || `whoami` | `version:number`, `id:string`, `lane:string`, `path:string` || `lanes` | `version:number`, `lanes:object`, `shared:array`, `coordinator:string` |+| `resources` | `version:number`, `resources:array` || `list` | `version:number`, `items:array` || `show` | `version:number`, `item_id:number`, `item_title:string`, `item_lane:string`, `item_status:string`, `verdicts:array` || `status` | `version:number`, `me:object`, `mine:array`, `stats:object`, `unread:number` |diff --git a/src/cli.js b/src/cli.jsindex e18e7813..52bde785 100644--- a/src/cli.js+++ b/src/cli.js@@ -44,6 +44,7 @@ import { renderSpecView } from './view.js';import { tour } from './tour.js';import { commandOutput } from './json.js';import { forgetProject, registerProject } from './projects.js';+import { listResources } from './resources.js';import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';import { serveView } from './serve.js';import { serveApi } from './api.js';@@ -63,7 +64,8 @@ Set uppullboard join <lane> [--route light] [--family <name>] register this worktree as an agent--route sets which work the model can take; --family records its namepullboard whoami | lanes | status who you are, the lanes, the board at a glance- pullboard view [--port N] [--no-open] every project on this machine in your browser: items, shouts, doctrine,+ pullboard resources local resource holders and their FIFO queues+ pullboard view [--port N] [--no-open] every project on this machine in your browser: items, shouts, doctrine,agents and activity, live; add items, shout and hold lanes from itpullboard serve [--port N] local API v1: boards, state, moves, requests and live events,behind the session secret in its printed address@@ -872,6 +874,21 @@ function readCommands(io, { first, second, rest, values }) {io.say(`imported version ${document.version} board tables: ${imported.tables.join(', ')}`);return 0;},+ resources: () => {+ const ctx = context(io);+ 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 });+ if (!resources.length) io.say('no resources have been used');+ for (const resource of resources) {+ io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})`);+ for (const holder of resource.holders) io.say(` held by ${holder.agent}${holder.repo ? ` in ${holder.repo}` : ''} since ${holder.since}`);+ resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${waiter.agent}${waiter.repo ? ` in ${waiter.repo}` : ''}`));+ }+ return 0;+ },resume: () => resumeHere(io),whoami: () => {const ctx = context(io);diff --git a/src/index.js b/src/index.jsindex 6b7d0bec..0a8936ea 100644--- a/src/index.js+++ b/src/index.js@@ -8,4 +8,5 @@ export { laneOf, outOfLane, laneNames } from './lanes.js';export { parseSpec, lintSpec, frozenCriterion, citedIds } from './spec.js';export { commitMsgProblems, secretsIn, blockedPaths } from './hooks.js';export { Refused } from './refused.js';+export { takeResource, listResources } from './resources.js';export { main } from './cli.js';diff --git a/src/json.js b/src/json.jsindex 34ebe148..8fbb7bfb 100644--- a/src/json.js+++ b/src/json.js@@ -18,6 +18,7 @@ export const JSON_SHAPES = {resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', dirty: 'number', next: 'string' }),whoami: shape({ id: 'string', lane: 'string', path: 'string' }),lanes: shape({ lanes: 'object', shared: 'array', coordinator: 'string' }),+ resources: shape({ resources: 'array' }),list: shape({ items: 'array' }),show: shape({ item_id: 'number', item_title: 'string', item_lane: 'string', item_status: 'string', verdicts: 'array' }),status: shape({ me: 'object', mine: 'array', stats: 'object', unread: 'number' }),diff --git a/src/resources.js b/src/resources.jsnew file mode 100644index 00000000..5c5811cd--- /dev/null+++ b/src/resources.js@@ -0,0 +1,139 @@+/** Local machine and repository resource queues with SQLite-backed leases [Q1,Q2,Q3]. */+import { mkdirSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { randomUUID } from 'node:crypto';+import { DatabaseSync } from 'node:sqlite';+import { repoInfo } from './git.js';+import { Refused } from './refused.js';++const LEASE_MS = 20_000;+const HEARTBEAT_MS = 3_000;+const POLL_MS = 40;++/** Resolve the local database for the requested scope. */+function databaseFile(scope, root) {+ if (scope === 'board') throw new Refused('BOARD_SCOPE_UNAVAILABLE', 'board-scoped resources need the relay; run pullboard relay on');+ if (scope === 'machine') return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'resources.sqlite');+ if (scope === 'repo') return join(repoInfo(root).commonDir, 'pullboard', 'resources.sqlite');+ throw new Refused('BAD_RESOURCE_SCOPE', `unknown resource scope "${scope}"; use machine or repo`);+}++/** Open and initialize the small durable queue database. */+function open(file) {+ mkdirSync(dirname(file), { recursive: true });+ const db = new DatabaseSync(file);+ db.exec(`PRAGMA busy_timeout = 10000;+ CREATE TABLE IF NOT EXISTS resource (name TEXT PRIMARY KEY, capacity INTEGER NOT NULL);+ CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL);+ CREATE INDEX IF NOT EXISTS holder_name ON holder(name);+ CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL);+ CREATE INDEX IF NOT EXISTS waiter_name_ticket ON waiter(name, ticket);`);+ return db;+}++/** Treat a process as alive unless the operating system confirms that its PID is gone. */+function alive(pid) {+ try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }+}++/** Run a short serialized database update and discard dead or expired leases. */+function update(db, action) {+ db.exec('BEGIN IMMEDIATE');+ try {+ const cutoff = Date.now() - LEASE_MS;+ for (const row of db.prepare('SELECT token, pid, heartbeat FROM holder').all()) {+ if (row.heartbeat < cutoff || !alive(row.pid)) db.prepare('DELETE FROM holder WHERE token = ?').run(row.token);+ }+ for (const row of db.prepare('SELECT token, pid, heartbeat FROM waiter').all()) {+ if (row.heartbeat < cutoff || !alive(row.pid)) db.prepare('DELETE FROM waiter WHERE token = ?').run(row.token);+ }+ const result = action();+ db.exec('COMMIT');+ return result;+ } catch (error) {+ db.exec('ROLLBACK');+ throw error;+ }+}++/** Current holders and FIFO line for one resource. */+function snapshot(db, name) {+ const holders = db.prepare('SELECT agent, repo, since FROM holder WHERE name = ? ORDER BY since, token').all(name);+ const line = db.prepare('SELECT agent, repo, since FROM waiter WHERE name = ? ORDER BY ticket').all(name);+ return { holders, line };+}++/** Pause briefly between durable queue checks. */+function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); }++/**+ * Join a resource's FIFO queue and resolve with a renewable lease when capacity is available.+ *+ * @param {{ name: string, capacity: number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, onWait?: (state: object) => void }} options+ * @returns {Promise<{ name: string, scope: string, token: string, release: () => void, renew: () => void }>}+ */+export async function takeResource(options) {+ const { name, capacity, scope = 'machine', root = process.cwd() } = options;+ 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');+ const file = databaseFile(scope, root);+ const db = open(file);+ const token = randomUUID();+ const pid = process.pid;+ const agent = options.agent ?? process.env.PULLBOARD_AGENT ?? `pid-${pid}`;+ const repo = options.repo ?? (scope === 'repo' ? repoInfo(root).root : '');+ const since = new Date().toISOString();+ try {+ update(db, () => {+ const row = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name);+ if (row && row.capacity !== capacity) throw new Refused('RESOURCE_CAPACITY_MISMATCH', `resource "${name}" already has capacity ${row.capacity}`);+ db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO NOTHING').run(name, capacity);+ db.prepare('INSERT INTO waiter(token, name, pid, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, agent, repo, since, Date.now());+ });+ while (true) {+ const acquired = update(db, () => {+ db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);+ const spot = snapshot(db, name);+ const position = db.prepare('SELECT count(*) AS count FROM waiter WHERE name = ? AND ticket <= (SELECT ticket FROM waiter WHERE token = ?)').get(name, token).count;+ const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;+ if (position === 1 && spot.holders.length < limit) {+ db.prepare('DELETE FROM waiter WHERE token = ?').run(token);+ db.prepare('INSERT INTO holder(token, name, pid, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, agent, repo, since, Date.now());+ return { acquired: true, state: { ...spot, position: 0 } };+ }+ return { acquired: false, state: { ...spot, position } };+ });+ if (acquired.acquired) {+ let released = false;+ const heartbeat = setInterval(() => {+ if (released) return;+ try { update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token)); } catch { /* Lease expiry remains the crash fallback. */ }+ }, HEARTBEAT_MS);+ heartbeat.unref();+ const release = () => {+ if (released) return;+ released = true;+ clearInterval(heartbeat);+ update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token));+ db.close();+ };+ return { name, scope, token, release, renew: () => update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token)) };+ }+ options.onWait?.(acquired.state);+ await pause(POLL_MS);+ }+ } catch (error) {+ try { update(db, () => db.prepare('DELETE FROM waiter WHERE token = ?').run(token)); } catch { /* Preserve the original error. */ }+ db.close();+ throw error;+ }+}++/** List resources and prune leases whose process died or lease expired. */+export function listResources({ scope = 'machine', root = process.cwd() } = {}) {+ const db = open(databaseFile(scope, root));+ try {+ return update(db, () => db.prepare('SELECT name, capacity FROM resource ORDER BY name').all().map(({ name, capacity }) => ({ name, capacity, ...snapshot(db, name) })));+ } finally { db.close(); }+}diff --git a/test/api.test.js b/test/api.test.jsindex 2e1085e7..63ac4a88 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -170,6 +170,7 @@ test('[A1] command results match the catalog across roots and subcommands', () =json(box, repo, 'hooks');json(box, repo, 'whoami');json(box, repo, 'lanes');+ json(box, repo, 'resources');json(box, repo, 'resume');json(box, repo, 'status');json(box, repo, 'doctor');diff --git a/test/resources.test.js b/test/resources.test.jsnew file mode 100644index 00000000..d7e51a3f--- /dev/null+++ b/test/resources.test.js@@ -0,0 +1,141 @@+/** Real-process resource queue and lease coverage [Q1,Q2,Q3]. */+import assert from 'node:assert/strict';+import { spawn, spawnSync } from 'node:child_process';+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { createInterface } from 'node:readline';+import { once } from 'node:events';+import { after, test } from 'node:test';++const TEMP = [];+const MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/resources.js')).href;+const WORKER = `+import { takeResource } from ${JSON.stringify(MODULE)};+const [name, capacity, scope, root, agent] = process.argv.slice(1);+const lease = await takeResource({ name, capacity: Number(capacity), scope, root, agent, onWait: ({position, holders}) => console.log(JSON.stringify({waiting:position, holders})) });+console.log(JSON.stringify({acquired:agent}));+process.stdin.setEncoding('utf8');+for await (const line of process.stdin) { if (line.trim() === 'release') { lease.release(); break; } }+`;++/** Create isolated machine storage and a pair of real Git repositories. */+function fixture() {+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-resources-'));+ TEMP.push(dir);+ const home = join(dir, 'home');+ const first = join(dir, 'repo-a');+ 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);+ }+ return { dir, home, first, second, env: { ...process.env, PULLBOARD_HOME: home } };+}++/** Launch one independent process that takes a resource and waits for a release command. */+function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = box.first, agent }) {+ const child = spawn(process.execPath, ['--input-type=module', '-e', WORKER, name, String(capacity), scope, root, agent], {+ env: box.env, stdio: ['pipe', 'pipe', 'pipe'],+ });+ child.lines = createInterface({ input: child.stdout });+ child.errors = '';+ child.stderr.setEncoding('utf8').on('data', (chunk) => { child.errors += chunk; });+ return child;+}++/** Read the next worker event, failing promptly with its stderr if it exits unexpectedly. */+async function event(child) {+ const line = await new Promise((resolveLine, reject) => {+ const onLine = (value) => { clearTimeout(timer); child.removeListener('exit', onExit); resolveLine(value); };+ const onExit = (code, signal) => { clearTimeout(timer); child.lines.removeListener('line', onLine); reject(new Error(`worker exited ${code}/${signal}: ${child.errors}`)); };+ const timer = setTimeout(() => { child.lines.removeListener('line', onLine); child.removeListener('exit', onExit); reject(new Error(`worker timed out: ${child.errors}`)); }, 10_000);+ child.lines.once('line', onLine);+ child.once('exit', onExit);+ });+ return JSON.parse(line);+}++/** Ask a holder to release and wait for clean process exit. */+async function release(child) {+ child.stdin.end('release\n');+ const [code] = await once(child, 'exit');+ child.lines.close();+ assert.equal(code, 0, child.errors);+}++after(() => TEMP.forEach((dir) => rmSync(dir, { recursive: true, force: true })));++test('[Q1,Q2] capacity-one takers acquire in strict FIFO arrival order', async () => {+ const box = fixture();+ const holder = worker(box, { agent: 'holder' });+ assert.equal((await event(holder)).acquired, 'holder');+ const waiting = [];+ for (const agent of ['first', 'second', 'third']) {+ const child = worker(box, { agent });+ waiting.push(child);+ const state = await event(child);+ assert.equal(state.waiting, waiting.length, `${agent} reports its FIFO place`);+ assert.equal(state.holders[0].agent, 'holder', `${agent} says who holds the place`);+ }+ const order = [];+ let current = holder;+ for (const [index, child] of waiting.entries()) {+ await release(current);+ assert.equal((await event(child)).acquired, ['first', 'second', 'third'][index]);+ order.push(['first', 'second', 'third'][index]);+ current = child;+ }+ await release(current);+ assert.deepEqual(order, ['first', 'second', 'third']);+});++test('[Q3] SIGKILL of a holder frees its lease for the next process', async () => {+ const box = fixture();+ const holder = worker(box, { agent: 'doomed-holder' });+ assert.equal((await event(holder)).acquired, 'doomed-holder');+ const next = worker(box, { agent: 'successor' });+ const waiting = await event(next);+ assert.equal(waiting.waiting, 1);+ holder.kill('SIGKILL');+ await once(holder, 'exit');+ assert.equal((await event(next)).acquired, 'successor');+ await release(next);+});++test('[Q2,Q3] a SIGKILLed waiter is skipped while the next live waiter advances', async () => {+ const box = fixture();+ const holder = worker(box, { agent: 'holder' });+ assert.equal((await event(holder)).acquired, 'holder');+ const dead = worker(box, { agent: 'dead-waiter' });+ assert.equal((await event(dead)).waiting, 1);+ const live = worker(box, { agent: 'live-waiter' });+ assert.equal((await event(live)).waiting, 2);+ dead.kill('SIGKILL');+ await once(dead, 'exit');+ await release(holder);+ assert.equal((await event(live)).acquired, 'live-waiter');+ await release(live);+});++test('[Q1] machine scope is shared, repo scope stays local, and board scope names relay requirement', async () => {+ const box = fixture();+ const holder = worker(box, { agent: 'repo-a', root: box.first });+ assert.equal((await event(holder)).acquired, 'repo-a');+ const otherRepo = worker(box, { agent: 'repo-b', root: box.second });+ assert.equal((await event(otherRepo)).waiting, 1);+ await release(holder);+ assert.equal((await event(otherRepo)).acquired, 'repo-b');+ await release(otherRepo);+ const localA = worker(box, { name: 'repo-only', scope: 'repo', agent: 'repo-a', root: box.first });+ const localB = worker(box, { name: 'repo-only', scope: 'repo', agent: 'repo-b', root: box.second });+ assert.equal((await event(localA)).acquired, 'repo-a');+ assert.equal((await event(localB)).acquired, 'repo-b');+ await release(localA);+ await release(localB);+ const refused = spawnSync(process.execPath, ['--input-type=module', '-e', `import {takeResource} from ${JSON.stringify(MODULE)}; await takeResource({name:'x',capacity:1,scope:'board'});`], { env: box.env, encoding: 'utf8' });+ assert.notEqual(refused.status, 0);+ assert.match(refused.stderr, /BOARD_SCOPE_UNAVAILABLE.*relay/i);+});