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
chore(core): merge main into queued leases [C7,V4,M1,M4]
Corey Olson705f1994da3a
diff --cc src/cli.jsindex 8328c414,062d6c58..86a22bd8--- a/src/cli.js+++ b/src/cli.js@@@ -2148,8 -2202,11 +2214,11 @@@ async function submitHere(ctx, id)withBoard(ctx, (board) => refuseUnverifiedStack(root, board, held, commit, trunk));// Every submit proves its frozen check and reachable tests anew on this exact commit (V4,V16).// A full-gate stamp never substitutes for either proof; only an actual full fallback may stamp.- const submitConfig = { ...ctx.config, submitGate: acceptedMain.config.submitGate };+ const submitConfig = { ...ctx.config, submitGate: acceptedMain.config.submitGate,+ submitInvariants: acceptedMain.config.submitInvariants,+ // The accepted project runner interprets its current invariant files; candidate config cannot replace it.+ ...(acceptedMain.config.submitInvariants.length ? { affectedTests: acceptedMain.config.affectedTests } : {}) };- const gate = await runSubmitGate(root, submitConfig, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), agent: me.id, item: String(id), onWait: gateWaitReporter(ctx.io), onBrowserFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });+ const gate = await runSubmitGate(root, submitConfig, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), agent: me.id, item: String(id), onWait: queuedItemLease(ctx, held, me.id, 'build'), onBrowserFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });if (!gate.isGreen) {const message = `the submission proof is red at ${commit.slice(0, 12)}; fix it, commit, submit again. ${submitGateReport(gate)}`;// No submission can follow this verdict. Read-only main comparisons must not retain the seat's write lease.diff --cc src/resources.jsindex b1237de6,f52a4931..8229281a--- a/src/resources.js+++ b/src/resources.js@@@ -86,8 -96,16 +96,17 @@@ function openQueue(file)if (!columns.includes('browser')) db.exec(`ALTER TABLE ${table} ADD COLUMN browser INTEGER NOT NULL DEFAULT 0`);if (!columns.includes('item')) db.exec(`ALTER TABLE ${table} ADD COLUMN item TEXT NOT NULL DEFAULT ''`);if (!columns.includes('kind')) db.exec(`ALTER TABLE ${table} ADD COLUMN kind TEXT NOT NULL DEFAULT ''`);+ if (!columns.includes('lease_until')) db.exec(`ALTER TABLE ${table} ADD COLUMN lease_until TEXT NOT NULL DEFAULT ''`);+ if (table === 'holder' && !columns.includes('runner')) db.exec("ALTER TABLE holder ADD COLUMN runner TEXT NOT NULL DEFAULT ''");+ if (table === 'waiter' && !columns.includes('remote')) db.exec('ALTER TABLE waiter ADD COLUMN remote INTEGER NOT NULL DEFAULT 0');}+ // Older runner-aware builds stored remote leases as ordinary gate holders. Move them+ // into their host namespace so old readers of name='gate' continue to see local use only.+ db.exec(`INSERT INTO resource(name, capacity)+ SELECT 'runner:' || runner, MAX(1, COUNT(*)) FROM holder+ WHERE name = 'gate' AND runner <> '' GROUP BY runner+ ON CONFLICT(name) DO NOTHING;+ UPDATE holder SET name = 'runner:' || runner WHERE name = 'gate' AND runner <> '';`);db.exec('COMMIT');transaction = false;} catch (error) {@@@ -175,15 -193,18 +194,18 @@@ function update(db, action)/** Current holders and the landing-first line, then every other kind in arrival order. */function snapshot(db, name) {/** Preserve older public entries while naming diagnostics as a distinct queue class. */- const project = ({ diagnostic, browser, item, kind, leaseUntil, ...entry }) => ({ ...entry, landing: entry.landing === 1,- const project = ({ diagnostic, browser, remote, runner, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,++ const project = ({ diagnostic, browser, remote, runner, item, kind, leaseUntil, ...entry }) => ({ ...entry, landing: entry.landing === 1,itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),- ...(browser === 1 ? { browser: true } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}),- ...(leaseUntil ? { leaseUntil } : {}) });+ ...(browser === 1 ? { browser: true } : {}), ...(remote === 1 ? { remote: true } : {}),- ...(runner ? { runner } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}) });++ ...(runner ? { runner } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}), ...(leaseUntil ? { leaseUntil } : {}) });// Browser is an additional capability on a gate lease, not a second partially held row.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, lease_until AS leaseUntil 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, lease_until AS leaseUntil FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);+ const runnerHost = name.startsWith('runner:') ? name.slice('runner:'.length) : '';+ const holderWhere = runnerHost ? 'name = ?' : where;+ const holderValues = [sourceName];- const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, runner, item, kind FROM holder WHERE ${holderWhere} ORDER BY since, token`).all(...holderValues).map(project);- const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);++ const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, runner, item, kind, lease_until AS leaseUntil FROM holder WHERE ${holderWhere} ORDER BY since, token`).all(...holderValues).map(project);++ const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind, lease_until AS leaseUntil FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);return { holders, line };}@@@ -219,8 -348,8 +349,8 @@@ function pause(ms) { return new Promise/*** Join the landing-first queue; every other kind keeps its original FIFO ticket.*- * @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) => any | Promise<any>, allowIdleCapacityUpdate?: boolean }} options - An awaited wait callback may return {leaseUntil}; it then receives one final {admitted:true} callback before work starts.- * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}- * @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, remote?: boolean, runnerProvider?: () => Array<{host:string,slots:number,browser:number}>, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean, _resume?: object }} options - Resource identity, queue class and optional remote executor pool.++ * @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, remote?: boolean, runnerProvider?: () => Array<{host:string,slots:number,browser:number}>, item?: string, kind?: string, onWait?: (state: object) => any | Promise<any>, allowIdleCapacityUpdate?: boolean, _resume?: object }} options - Resource identity, queue class and optional remote executor pool. An awaited wait callback may return {leaseUntil} and then receives a final {admitted:true} callback before work starts.+ * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, runner?: {host:string,slots:number,browser:number}, waitMs: number, release: () => void, renew: () => void, requeueRunner?: () => Promise<object> }>}*/export async function takeResource(options) {const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;@@@ -248,22 -387,9 +388,23 @@@const agent = options.agent ?? process.env.PULLBOARD_AGENT ?? `pid-${pid}`;const started = processStarted(pid);const repo = options.repo ?? repoRoot(root);- let queuedAt = new Date().toISOString();+ let queuedAt = resume?.queuedAt ?? new Date().toISOString();+ let leaseUntil = '';+ /** Record an item's lease only after its awaited owner renewal succeeds. */+ const keepItemLease = async (state, table) => {+ const result = await options.onWait?.(state);+ if (result?.leaseUntil !== undefined) {+ if (typeof result.leaseUntil !== 'string' || !Number.isFinite(Date.parse(result.leaseUntil))) {+ throw new Refused('BAD_RESOURCE_METADATA', 'the waiting item renewal must return a valid leaseUntil timestamp');+ }+ leaseUntil = result.leaseUntil;+ const changed = update(db, () => db.prepare(`UPDATE ${table} SET lease_until = ? WHERE token = ? AND pid = ? AND started = ?`)+ .run(leaseUntil, token, pid, started));+ if (changed.changes !== 1) throw new Refused('RESOURCE_LEASE_LOST', 'the queued resource lease disappeared during item renewal; retry the command');+ }+ };try {+ let initialTicket = resume?.ticket;update(db, () => {const currentCapacity = options.capacityProvider?.() ?? capacity;if (!Number.isSafeInteger(currentCapacity) || currentCapacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');@@@ -319,31 -458,31 +473,40 @@@return { acquired: false, state: { ...spot, position: reportPosition } };});if (acquired.acquired) {+ // Only item-lease callbacks opt into admission. Await them so no renewal remains in+ // flight during the run, and restart the ordinary item expiry from this boundary.+ if (leaseUntil) {+ try { await keepItemLease({ ...acquired.state, admitted: true }, 'holder'); }+ catch (error) {+ update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token));+ throw error;+ }+ }+ const acquiredWaitMs = priorWaitMs + Math.max(0, Date.now() - waitStartedAt);let released = false;+ let transferred = false;let lost = false;- const heartbeat = setInterval(() => {- if (released || lost) return;- try {- const changed = update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token).changes);- if (!changed) { lost = true; clearInterval(heartbeat); }- } catch { /* Lease expiry remains the crash fallback. */ }- }, HEARTBEAT_MS);- heartbeat.unref();- /** Release the resource and close its SQLite handle. */+ let heartbeat;+ /** Keep the active holder lease alive while its executor is running. */+ const startHeartbeat = () => {+ heartbeat = setInterval(() => {+ if (released || transferred || lost) return;+ try {+ const changed = update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token).changes);+ if (!changed) { lost = true; clearInterval(heartbeat); }+ } catch { /* Lease expiry remains the crash fallback. */ }+ }, HEARTBEAT_MS);+ heartbeat.unref();+ };+ startHeartbeat();+ /** Release this holder and close its SQLite handle unless ownership was transferred. */const release = () => {- if (released) return;+ if (released || transferred) return;released = true;clearInterval(heartbeat);- try { update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token)); }+ try {+ update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token));+ }finally { db.close(); }};/** Refresh this lease, or refuse if another process already evicted it. */@@@ -356,9 -495,40 +519,40 @@@throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);}};- return { name, scope, token, pool, browser, waitMs: Math.max(0, Date.now() - requestedAt), release, renew };+ /** Quarantine a failed remote host and retry this exact ticket on another executor. */+ const requeueRunner = async () => {+ if (!acquired.runner) throw new Refused('LOCAL_RUNNER_REQUEUE', 'only a remote lease can be returned to the runner queue');+ if (released || transferred || lost) throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);+ transferred = true;+ clearInterval(heartbeat);+ let requeueTicket = acquired.ticket;+ try {+ update(db, () => {+ db.prepare('INSERT INTO runner_unavailable(host, since, detail) VALUES (?, ?, ?) ON CONFLICT(host) DO UPDATE SET since = excluded.since, detail = excluded.detail')+ .run(acquired.runner.host, new Date().toISOString(), 'TRANSPORT_LOST');+ const holderName = runnerResourceName(acquired.runner.host);+ const holder = db.prepare('SELECT token FROM holder WHERE token = ? AND name = ? AND runner = ?').get(token, holderName, acquired.runner.host);+ if (!holder) throw new Refused('RESOURCE_LEASE_LOST', `remote lease for "${name}" is no longer held`);+ const minimumTicket = db.prepare("SELECT MIN(ticket) AS ticket FROM waiter WHERE name = 'gate' AND landing = ?").get(Number(landing)).ticket;+ requeueTicket = Math.min(0, minimumTicket ?? 0) - 1;+ db.prepare('DELETE FROM holder WHERE token = ?').run(token);+ db.prepare('INSERT INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')+ .run(requeueTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));+ });+ } catch (error) {+ transferred = false;+ startHeartbeat();+ throw error;+ }+ db.close();+ return takeResource({ ...options, _resume: { token, ticket: requeueTicket ?? acquired.ticket,+ queuedAt, requestedAt, priorWaitMs: acquiredWaitMs, waitStartedAt: Date.now() } });+ };+ return { name, scope, token, pool, browser, ...(acquired.runner ? { runner: acquired.runner } : {}),+ waitMs: acquiredWaitMs, release, renew,+ ...(acquired.runner ? { requeueRunner } : {}) };}- options.onWait?.(acquired.state);+ await keepItemLease(acquired.state, 'waiter');await pause(POLL_MS);}} catch (error) {diff --cc test/machine.test.jsindex 34cf542e,985d8fc1..681aee8d--- a/test/machine.test.js+++ b/test/machine.test.js@@@ -487,7 -520,7 +520,10 @@@ test('a broken copy of the code fails t], 'reserve reaches the route check through the reviewer checks it shares with a verdict');const doubleQuoted = editedSource('cli.js', /^const cdTo = .*$/m, "const cdTo = (root) => { if (!root) throw new Refused(\"NO_ROOT\", 'no root'); return 'cd ' + root + ' &&'; };");-- assert.deepEqual(codeProblems(MACHINE, doubleQuoted), ['NO_ROOT is raised by accept and reject but not declared there']);++ assert.deepEqual(codeProblems(MACHINE, doubleQuoted), [++ 'NO_ROOT is raised by submit but not declared there',++ 'NO_ROOT is raised by accept and reject but not declared there',++ ]);});const SHA_A = 'a'.repeat(40);@@@ -803,9 -836,9 +839,9 @@@ test('pullboard help lists each role\'/** Guards checked before the explicit transition: CLI facts and optional roadmap selection. */const PRECHECKED = {claim: ['joined'],-- submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'noUnverifiedStack'],++ submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'queuedItemLease', 'gateGreen', 'treeStillDuringGate', 'noUnverifiedStack'],reserve: ['coordinatorSaysAs', 'joined', 'roadmapReadable'],-- accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'trunkMergeClean', 'itemCheckGreen', 'noUnverifiedStack'],++ accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'trunkMergeClean', 'queuedItemLease', 'itemCheckGreen', 'noUnverifiedStack'],reject: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit'],};