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(run): ladders per tier and routing by history [N18]
Corey Olson55855b096dae
diff --git a/src/board.js b/src/board.jsindex 7a99e52b..f8180e34 100644--- a/src/board.js+++ b/src/board.js@@ -511,10 +511,10 @@ export function escalate(board, id, { agentId, note, attempt = '' }) {** @param {any} board* @param {number} id- * @param {{ agentId: string, n: number, seconds: number, result: string }} attempt+ * @param {{ agentId: string, n: number, seconds: number, result: string, rung?: number }} attempt*/-export function recordAttempt(board, id, { agentId, n, seconds, result }) {- logEvent(board, agentId, 'attempt', id, { n, seconds, result });+export function recordAttempt(board, id, { agentId, n, seconds, result, rung = 1 }) {+ logEvent(board, agentId, 'attempt', id, { n, seconds, result, ...(rung > 1 ? { rung } : {}) });}/**diff --git a/src/cli.js b/src/cli.jsindex c4006094..9bff1984 100644--- a/src/cli.js+++ b/src/cli.js@@ -66,7 +66,9 @@ Workbuild routed items unattended in this worktree: the agent command readsthe context pack at $PULLBOARD_PACK (and $PULLBOARD_CHECK, $PULLBOARD_ITEM,$PULLBOARD_ATTEMPT); green work is submitted, red escalated- [--agent-light "..."] [--agent-mid "..."] [--agent-strong "..."] a command per tier+ [--agent-light "..."] [--agent-mid "..."] [--agent-strong "..."] a command per tier; repeat a+ flag for a ladder, cheapest first; --history <file> keeps what each+ rung did, and a rung that keeps failing a kind of item is skippedpullboard list [lane] [--all] [--route light|mid|strong] open and active items; --all adds closed onespullboard show <id> an item, the criterion frozen at claim, its verdictspullboard next [--wait <minutes>] claim the next item in your lane that is free to start@@ -120,9 +122,10 @@ const OPTIONS = {as: { type: 'string' },check: { type: 'string' },agent: { type: 'string' },- 'agent-light': { type: 'string' },- 'agent-mid': { type: 'string' },- 'agent-strong': { type: 'string' },+ 'agent-light': { type: 'string', multiple: true },+ 'agent-mid': { type: 'string', multiple: true },+ 'agent-strong': { type: 'string', multiple: true },+ history: { type: 'string' },attempts: { type: 'string' },minutes: { type: 'string' },items: { type: 'string' },diff --git a/src/run.js b/src/run.jsindex f49329d4..d4d5566d 100644--- a/src/run.js+++ b/src/run.js@@ -11,7 +11,7 @@*/import { spawn, spawnSync } from 'node:child_process';import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';-import { join } from 'node:path';+import { dirname, join, resolve } from 'node:path';import * as store from './board.js';import { briefFiles } from './brief.js';import { COORDINATOR } from './config.js';@@ -263,43 +263,100 @@ function mergeDependencies(ctx, item, deps) {}/**- * Build one claimed item: attempts until the check and the gate pass, then submit; or pin, reset- * and escalate.+ * What kind of item this is, as features a routing history can learn from: the `Kind:` line of its+ * brief when the planner wrote one, or else the rules a sweep listed (`- line 12:3 camelcase: ...`).+ *+ * @param {any} item+ * @returns {string[]}+ */+export function featuresOf(item) {+ const brief = item.item_brief ?? '';+ const named = /^kind:\s*(.+)$/im.exec(brief);+ if (named) return [...new Set(named[1].split(/[\s,+]+/).filter(Boolean))].sort();+ const rules = [...brief.matchAll(/^\s*- line \d+(?::\d+)? ([\w@/-]+):/gm)].map((match) => match[1]);+ return rules.length ? [...new Set(rules)].sort() : ['unlabelled'];+}++/**+ * Which rungs of a tier's ladder to try for an item (N18): every rung, except one that has failed a+ * feature of this item at least twice and never fixed it. The history is what this machine's models+ * did before; routing learns from it instead of from a guess.+ *+ * @param {string[]} ladder - The tier's commands, cheapest first.+ * @param {string[]} features+ * @param {string} tier+ * @param {{ tier: string, command: string, features: string[], result: string }[]} records+ * @returns {{ rung: number, command: string, skip: string }[]}+ */+export function routePlan(ladder, features, tier, records) {+ return ladder.map((command, index) => {+ const mine = records.filter((record) => record.tier === tier && record.command === command);+ const hopeless = features.find((feature) => {+ const seen = mine.filter((record) => record.features.includes(feature));+ return seen.filter((record) => record.result === 'red').length >= 2 && !seen.some((record) => record.result === 'green');+ });+ const failed = hopeless ? mine.filter((record) => record.features.includes(hopeless)).length : 0;+ return { rung: index + 1, command, skip: hopeless ? `it failed ${hopeless} ${failed} times and never fixed it` : '' };+ });+}++/**+ * The routing history kept on this machine: one JSON line per rung tried on an item.+ *+ * @param {string} file+ * @returns {{ records: any[], add: (record: any) => void }}+ */+function routingHistory(file) {+ const records = existsSync(file)+ ? readFileSync(file, 'utf8').split('\n').filter(Boolean).flatMap((line) => {+ try {+ return [JSON.parse(line)];+ } catch {+ return [];+ }+ })+ : [];+ return {+ records,+ add: (record) => {+ mkdirSync(dirname(file), { recursive: true });+ appendFileSync(file, `${JSON.stringify(record)}\n`);+ records.push(record);+ },+ };+}++/**+ * Try one rung of the ladder on an item: up to `attempts` runs of its command, each followed by the+ * check, and on green a commit, the gate and a submit.** @param {any} ctx* @param {any} item* @param {any} options- * @returns {Promise<'submitted' | 'escalated'>}+ * @returns {Promise<{ green: boolean, digest: string, tries: number, seconds: number }>}*/-async function buildItem(ctx, item, { agents, attempts, minutes, deps, me }) {+async function tryRung(ctx, item, { command, rung, attempts, minutes, deps, me, start, inScope, packs, earlier, carried }) {const { root } = ctx.info;const id = item.item_id;- const agent = agents[item.item_route];- mergeDependencies(ctx, item, deps);- const start = headCommit(root) ?? '';- const earlier = deps.withBoard(ctx, (board) => store.events(board, { itemId: id }))- .filter((event) => event.event_kind === 'escalate')- .map((event) => JSON.parse(event.event_detail).note.replace(/\s+/g, ' ').slice(0, 600));- const listed = new Set(briefFiles(item.item_brief));- const inScope = (path) => (!listed.size || listed.has(path)) && !outOfLane(ctx.config, item.item_lane, [path]).length;- const packs = join(ctx.info.gitDir, 'pullboard', 'packs');- mkdirSync(packs, { recursive: true });- let digest = '';+ const tag = rung === 1 ? item.item_route : `${item.item_route}${rung}`;+ let digest = carried;+ let seconds = 0;for (let attempt = 1; attempt <= attempts; attempt += 1) {const fresh = deps.withBoard(ctx, (board) => {store.claim(board, id, { agentId: me.id, lane: me.lane, leaseMs: ctx.config.leaseMs, freeze: deps.freezer(ctx) });return store.getItem(board, id);});- const pack = join(packs, `${id}-${item.item_route}-${attempt}.md`);+ const pack = join(packs, `${id}-${tag}-${attempt}.md`);writeFileSync(pack, packText(root, fresh, { attempt, attempts, digest, earlier }));- ctx.io.say(`#${id} attempt ${attempt}/${attempts}: running the ${item.item_route} agent`);+ ctx.io.say(`#${id} attempt ${attempt}/${attempts}: running the ${item.item_route} agent${rung > 1 ? ` (rung ${rung})` : ''}`);const env = { ...process.env, PULLBOARD_PACK: pack, PULLBOARD_CHECK: item.item_check, PULLBOARD_ITEM: String(id), PULLBOARD_ATTEMPT: String(attempt) };- const built = await runCommand(agent, { cwd: root, env, timeoutMs: minutes * 60_000, log: join(packs, `${id}-${item.item_route}-${attempt}.log`) });+ const built = await runCommand(command, { cwd: root, env, timeoutMs: minutes * 60_000, log: join(packs, `${id}-${tag}-${attempt}.log`) });const outside = changedSince(root, start).filter((path) => !inScope(path));restore(root, start, outside);const reverted = outside.length ? `The runner reverted your changes outside the brief's files: ${outside.join(', ')}.\n` : '';const late = built.timedOut ? `The agent ran out of time after ${minutes} minutes.\n` : '';const checked = await runCommand(item.item_check, { cwd: root, timeoutMs: minutes * 60_000 });+ seconds += built.seconds + checked.seconds;let result = 'green';if (checked.status !== 0) {result = 'red';@@ -324,21 +381,73 @@ async function buildItem(ctx, item, { agents, attempts, minutes, deps, me }) {ctx.io.say(`#${id} attempt ${attempt}: ${result}: ${error.message}`);}}- deps.withBoard(ctx, (board) => store.recordAttempt(board, id, { agentId: me.id, n: attempt, seconds: built.seconds + checked.seconds, result }));- if (result === 'green') return 'submitted';+ deps.withBoard(ctx, (board) => store.recordAttempt(board, id, { agentId: me.id, n: attempt, seconds: built.seconds + checked.seconds, result, rung }));+ if (result === 'green') return { green: true, digest, tries: attempt, seconds };}- const ref = pinAttempt(root, id);- git(root, ['reset', '-q', '--hard', start]);- git(root, ['clean', '-q', '-fd']);+ return { green: false, digest, tries: attempts, seconds };+}++/**+ * Build one claimed item: climb its tier's ladder, cheapest rung first, skipping rungs the routing+ * history says cannot do this kind of item; submit on green, or pin, reset and escalate.+ *+ * @param {any} ctx+ * @param {any} item+ * @param {any} options+ * @returns {Promise<'submitted' | 'escalated'>}+ */+async function buildItem(ctx, item, { agents, attempts, minutes, deps, me, history }) {+ const { root } = ctx.info;+ const id = item.item_id;+ mergeDependencies(ctx, item, deps);+ const start = headCommit(root) ?? '';+ const earlier = deps.withBoard(ctx, (board) => store.events(board, { itemId: id }))+ .filter((event) => event.event_kind === 'escalate')+ .map((event) => JSON.parse(event.event_detail).note.replace(/\s+/g, ' ').slice(0, 600));+ const listed = new Set(briefFiles(item.item_brief));+ const inScope = (path) => (!listed.size || listed.has(path)) && !outOfLane(ctx.config, item.item_lane, [path]).length;+ const packs = join(ctx.info.gitDir, 'pullboard', 'packs');+ mkdirSync(packs, { recursive: true });+ const features = featuresOf(item);+ const plan = routePlan(agents[item.item_route], features, item.item_route, history.records);+ for (const step of plan.filter((entry) => entry.skip)) ctx.io.say(`#${id} skips rung ${step.rung}: ${step.skip}`);+ let digest = '';+ let spent = 0;+ for (const step of plan.filter((entry) => !entry.skip)) {+ const tried = await tryRung(ctx, item, { command: step.command, rung: step.rung, attempts, minutes, deps, me, start, inScope, packs, earlier, carried: digest });+ history.add({ at: new Date().toISOString(), features, tier: item.item_route, command: step.command, result: tried.green ? 'green' : 'red', tries: tried.tries, seconds: tried.seconds });+ if (tried.green) return 'submitted';+ spent += tried.tries;+ digest = tried.digest;+ pinAttempt(root, id);+ git(root, ['reset', '-q', '--hard', start]);+ git(root, ['clean', '-q', '-fd']);+ }+ const ref = plan.some((entry) => !entry.skip) ? latestPin(root, id) : '';+ const why = plan.every((entry) => entry.skip)+ ? `this tier's models failed items like this before (${features.join(', ')}), so it skipped them`+ : `every rung stayed red. Last failure:\n${digest}`;const moved = deps.withBoard(ctx, (board) => {- const result = store.escalate(board, id, { agentId: me.id, note: `${attempts} attempts stayed red. Last failure:\n${digest}`.slice(0, 2000), attempt: ref });- store.shout(board, { from: me.id, to: COORDINATOR, text: `#${id} escalated ${result.from} -> ${result.to} after ${attempts} red attempts; the work is pinned at ${ref}`, lanes: laneNames(ctx.config) });+ const result = store.escalate(board, id, { agentId: me.id, note: `${why}`.slice(0, 2000), attempt: ref });+ const how = spent ? ` after ${spent} red attempts; the work is pinned at ${ref}` : ' without an attempt: this tier failed items like it before';+ store.shout(board, { from: me.id, to: COORDINATOR, text: `#${id} escalated ${result.from} -> ${result.to}${how}`, lanes: laneNames(ctx.config) });return result;});- ctx.io.say(`#${id} escalated ${moved.from} -> ${moved.to}; the attempt is pinned at ${ref}`);+ ctx.io.say(`#${id} escalated ${moved.from} -> ${moved.to}${ref ? `; the attempt is pinned at ${ref}` : ', without spending an attempt'}`);return 'escalated';}+/**+ * The newest attempt pinned for an item, or empty when none was.+ *+ * @param {string} root+ * @param {number} id+ * @returns {string}+ */+function latestPin(root, id) {+ return git(root, ['for-each-ref', '--sort=-creatordate', '--count=1', '--format=%(refname)', `refs/pullboard/attempts/${id}/`]);+}+/*** The runner: claims the items this worktree's agent may take, one at a time, and builds each.*@@ -352,9 +461,8 @@ export async function runItems(io, values, deps) {if (ctx.info.isMain) {throw new Refused('MAIN_IS_COORDINATOR', 'the runner builds lane items, so it runs in a lane worktree: pullboard worktree <lane> --route light, then run it there');}- const agents = Object.fromEntries(- store.ROUTES.map((route) => [route, String(values[`agent-${route}`] ?? values.agent ?? '').trim()]).filter(([, command]) => command),- );+ const ladderFor = (route) => [values[`agent-${route}`] ?? values.agent ?? []].flat().map((command) => String(command).trim()).filter(Boolean);+ const agents = Object.fromEntries(store.ROUTES.map((route) => [route, ladderFor(route)]).filter(([, ladder]) => ladder.length));if (!Object.keys(agents).length) {throw new Refused('USAGE', 'pullboard run --agent "<command>", or --agent-light, --agent-mid, --agent-strong: the command that builds one item from the pack in $PULLBOARD_PACK, such as: opencode run "$(cat "$PULLBOARD_PACK")"');}@@ -367,11 +475,12 @@ export async function runItems(io, values, deps) {throw new Refused('DIRTY', 'the runner starts from a clean worktree; commit or remove your changes first');}const me = deps.withBoard(ctx, (board) => deps.whoAmI(ctx, board));- const above = Object.keys(agents).filter((route) => !store.canTake(me.route, route) && values[`agent-${route}`]);+ const above = Object.keys(agents).filter((route) => !store.canTake(me.route, route) && [values[`agent-${route}`] ?? []].flat().length);if (above.length) {throw new Refused('ROUTE', `this worktree joined on the ${me.route} route, so it cannot take ${above.join(' or ')} items; make one that can: pullboard worktree ${me.lane} --route ${above.at(-1)}`);}const routes = Object.keys(agents).filter((route) => store.canTake(me.route, route));+ const history = routingHistory(values.history ? resolve(io.cwd, values.history) : join(ctx.info.commonDir, 'pullboard', 'routing.jsonl'));const totals = { submitted: 0, escalated: 0 };const deadline = Date.now() + waitMinutes * 60_000;while (totals.submitted + totals.escalated < limit) {@@ -385,7 +494,7 @@ export async function runItems(io, values, deps) {await new Promise((done) => setTimeout(done, 5000));continue;}- totals[await buildItem(ctx, found.item, { agents, attempts, minutes, deps, me })] += 1;+ totals[await buildItem(ctx, found.item, { agents, attempts, minutes, deps, me, history })] += 1;}io.say(`runner done: ${totals.submitted} submitted, ${totals.escalated} escalated`);return 0;