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: tiers, escalation, runner, fixers at commit [B13,B14,B15,N14,C5]
Corey Olsond2a669b629d3
diff --git a/skills/pullboard-plan/SKILL.md b/skills/pullboard-plan/SKILL.mdindex 505560fd..3ed2e3c6 100644--- a/skills/pullboard-plan/SKILL.md+++ b/skills/pullboard-plan/SKILL.md@@ -13,8 +13,24 @@ You turn approved rows into items builders can claim. You do not build.- sits in the lane that owns its files- cites with `--specs` only the rows it meets in full; a verifier rejects an item that cites a row it does not meet- has a `--criterion` a stranger could check without asking you, with the exact command, input and expected output- - has a `--brief` (or `--brief-file`) when a builder starting cold would need more than the criterion: the files to touch, the contract to follow, the pattern to copy, the command that proves it. The criterion says what; the brief says how.-4. **Route the mechanical work light.** When the brief says exactly what to change, where, and how to prove it, a lighter model can build it: `--route light`. Leave on the default strong route anything that needs judgment: a shared contract, a design choice, an edge the brief cannot settle. Agents that join with `--route light` take only light items; strong agents take strong items first.+ - has a `--brief` (or `--brief-file`) when a builder starting cold would need more than the criterion. The criterion says what; the brief says how. Write it in four labelled parts:++ ```+ Files:+ - src/store.js+ - test/store.test.js+ Change:+ - add(text) returns the new task's number; numbers start at 1 and are never reused+ Test:+ - in test/store.test.js, two adds return 1 and 2, and a remove then an add returns 3+ Out of scope: every other file; no git commands; no new dependencies+ ```+ - has a `--check` when it can: the one command that proves it, such as `node --test test/store.test.js`.+4. **Route each item to the cheapest model that can build it.** Every item an expensive model builds that a cheaper one could have is waste.+ - `--route light`: a small or local model can build it from the brief alone. Mechanical work: wiring, a field through three files, a test for a stated case, a rename.+ - `--route mid`: a capable model such as Haiku or Sonnet: a small feature, a bug with a known cause.+ - Leave on the default strong route what needs judgment: a shared contract, a design choice, an edge the brief cannot settle.+ - Below strong, an item needs `--criterion`, `--check`, and a brief whose Files sit in the item's lane and whose Test says what it asserts; `add` refuses it otherwise. Agents take their own tier first, then lighter ones; a builder that cannot get an item green escalates it one tier up.5. **Order with `--after`.** An item that needs another's result waits for it. Keep the chains short; parallel lanes are the point.6. **Simplest version first.** Plan the smallest thing that meets the rows. Every addition needs a row that asks for it.7. **Real inputs early.** If the project has real inputs (files, an API, data), plan an early item that runs on them, so surprises surface before everything else is built.diff --git a/src/board.js b/src/board.jsindex 2a2b7d54..407513e6 100644--- a/src/board.js+++ b/src/board.js@@ -9,17 +9,29 @@import { mkdirSync } from 'node:fs';import { dirname } from 'node:path';import { DatabaseSync } from 'node:sqlite';+import { briefFiles, briefSections } from './brief.js';import { COORDINATOR } from './config.js';import { Refused } from './refused.js';export const ACCEPT_REASON = 'CRITERION_MET';/**- * Who can take an item (B11): `strong` needs a frontier model's judgment; `light` is work any model- * can build from its brief. An agent's route is set when it joins.+ * Who can take an item (B13), as tiers in order of the model an item needs: `light` is work a small+ * or local model can build from its brief, `mid` needs a capable model such as Haiku or Sonnet, and+ * `strong` needs a frontier model's judgment. An agent's route is set when it joins; it takes items+ * at its tier and below.*/-export const ROUTES = ['strong', 'light'];+export const ROUTES = ['light', 'mid', 'strong'];const BRIEF_LIMIT = 8000;++/**+ * True when an agent on `agentRoute` may build or verify an item routed `itemRoute`.+ *+ * @param {string} agentRoute+ * @param {string} itemRoute+ * @returns {boolean}+ */+export const canTake = (agentRoute, itemRoute) => ROUTES.indexOf(itemRoute) <= ROUTES.indexOf(agentRoute);export const REJECT_REASONS = ['TEST_FAILURE','BEHAVIOR_MISMATCH',@@ -52,6 +64,7 @@ const SCHEMA = `item_after TEXT NOT NULL DEFAULT '',item_brief TEXT NOT NULL DEFAULT '',item_route TEXT NOT NULL DEFAULT 'strong',+ item_check TEXT NOT NULL DEFAULT '',item_status TEXT NOT NULL DEFAULT 'open',item_owner TEXT,item_lease_until TEXT,@@ -129,6 +142,7 @@ function migrate(db) {['item', 'item_after', "TEXT NOT NULL DEFAULT ''"],['item', 'item_brief', "TEXT NOT NULL DEFAULT ''"],['item', 'item_route', "TEXT NOT NULL DEFAULT 'strong'"],+ ['item', 'item_check', "TEXT NOT NULL DEFAULT ''"],['agent', 'agent_route', "TEXT NOT NULL DEFAULT 'strong'"],];for (const [table, column, type] of added) {@@ -256,8 +270,8 @@ export function agentAt(board, path) {/*** Register a worktree as an agent (B3): the main checkout as the one coordinator, any other- * worktree as the next agent in its lane (`web-1`, `web-2`, ...), on a route: strong, or light for- * a model that takes only items routed light (B11). Registering again is a no-op.+ * worktree as the next agent in its lane (`web-1`, `web-2`, ...), on a route: the tier of model+ * behind it, which decides the items it may take (B13). Registering again is a no-op.** @param {any} board* @param {{ lane: string, path: string, route?: string }} who@@ -333,23 +347,31 @@ export function listAgents(board) {*/function checkRoute(route) {if (!ROUTES.includes(route)) {- throw new Refused('BAD_ROUTE', `route "${route}" is strong (needs a frontier model) or light (any model can build it from the brief)`);+ throw new Refused('BAD_ROUTE', `route "${route}" is light (a small or local model can build it from the brief), mid (a capable model) or strong (a frontier model)`);}}/**- * Refuse a brief that cannot do its job (B10): too long to read cold, or missing on an item routed- * light, where the brief is all a light model has to go on.+ * Refuse an item a lighter model could not build cold (B10, B14). Any brief stays short enough to+ * read. Below the strong route the item needs all of it: a criterion, a check command that proves+ * it, and a brief naming the files and the test.*- * @param {string} brief- * @param {string} route+ * @param {{ brief: string, route: string, criterion: string, check: string }} item*/-function checkBrief(brief, route) {+function checkRouted({ brief, route, criterion, check }) {if (brief.length > BRIEF_LIMIT) {throw new Refused('BRIEF_TOO_LONG', `the brief is ${brief.length} characters; keep it under ${BRIEF_LIMIT} and point to longer docs by path`);}- if (route === 'light' && !brief.trim()) {- throw new Refused('NO_BRIEF', 'an item routed light carries a brief: the files, the contract, the pattern to copy and the command that proves it (--brief or --brief-file)');+ if (route === 'strong') return;+ const sections = briefSections(brief);+ const missing = [+ ...(briefFiles(brief).length ? [] : ['a brief with a Files: section naming the paths to touch']),+ ...(sections.test?.length ? [] : ['a Test: section saying what the test asserts']),+ ...(criterion.trim() ? [] : ['--criterion, saying when it is done']),+ ...(check.trim() ? [] : ['--check, the command that proves it']),+ ];+ if (missing.length) {+ throw new Refused('NO_BRIEF', `an item routed ${route} must be buildable cold; it needs ${missing.join(', ')}`);}}@@ -373,11 +395,11 @@ function routeOf(board, agentId) {* @param {{ by: string, lane: string, title: string, criterion?: string, specIds?: string[], parentId?: number | null, after?: number[], brief?: string, route?: string }} item* @returns {number} The new item's id.*/-export function addItem(board, { by, lane, title, criterion = '', specIds = [], parentId = null, after = [], brief = '', route = 'strong' }) {+export function addItem(board, { by, lane, title, criterion = '', specIds = [], parentId = null, after = [], brief = '', route = 'strong', check = '' }) {const cleanTitle = title.trim();if (!cleanTitle) throw new Refused('NO_TITLE', 'an item needs a title');checkRoute(route);- checkBrief(brief.trim(), route);+ checkRouted({ brief: brief.trim(), route, criterion, check });return atomic(board, () => {if (parentId !== null) {const parent = itemById(board, parentId);@@ -397,10 +419,10 @@ export function addItem(board, { by, lane, title, criterion = '', specIds = [],const result = board.db.prepare(`INSERT INTO item (item_parent_id, item_lane, item_title, item_criterion, item_spec_ids,- item_after, item_brief, item_route, item_created_by, item_created_at, item_updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ item_after, item_brief, item_route, item_check, item_created_by, item_created_at, item_updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,)- .run(parentId, lane, cleanTitle, criterion.trim(), specIds.join(','), after.join(','), brief.trim(), route, by, at, at);+ .run(parentId, lane, cleanTitle, criterion.trim(), specIds.join(','), after.join(','), brief.trim(), route, check.trim(), by, at, at);const id = Number(result.lastInsertRowid);logEvent(board, by, 'add', id, { lane, specIds, after, route });return id;@@ -408,17 +430,19 @@ export function addItem(board, { by, lane, title, criterion = '', specIds = [],}/**- * Change an item's brief or route (B10, B11): how to build it and who can, never what it must do;- * the criterion moves only by refreeze. The coordinator or the agent that added it may edit, until- * it is verified or withdrawn; the route only while nobody holds it.+ * Change an item's brief, route, criterion or check (B10, B13, B14). The brief says how to build it+ * and may change until the item is verified or withdrawn. The route, the criterion and the check+ * change only while nobody holds the item; changing the criterion or the check drops the frozen+ * bar, so the next claim freezes the new one, in the log for anyone to see. The coordinator or the+ * agent that added the item may edit it.** @param {any} board* @param {number} id- * @param {{ agentId: string, brief?: string, route?: string }} change+ * @param {{ agentId: string, brief?: string, route?: string, criterion?: string, check?: string }} change*/-export function editItem(board, id, { agentId, brief, route }) {- if (brief === undefined && route === undefined) {- throw new Refused('USAGE', 'say what changes: --brief "...", --brief-file <file> or --route strong|light');+export function editItem(board, id, { agentId, brief, route, criterion, check }) {+ if ([brief, route, criterion, check].every((value) => value === undefined)) {+ throw new Refused('USAGE', 'say what changes: --brief "...", --brief-file <file>, --route light|mid|strong, --criterion "..." or --check "<command>"');}atomic(board, () => {const item = current(board, itemById(board, id));@@ -428,21 +452,71 @@ export function editItem(board, id, { agentId, brief, route }) {if (['verified', 'withdrawn'].includes(item.item_status)) {throw new Refused('CLOSED', `item #${id} is ${item.item_status}`);}- const nextRoute = route ?? item.item_route;- const nextBrief = brief === undefined ? item.item_brief : brief.trim();- checkRoute(nextRoute);- if (nextRoute !== item.item_route && item.item_status !== 'open') {- throw new Refused('HELD', `item #${id} is ${item.item_status}; change its route only while it is open`);+ const next = {+ item_brief: brief === undefined ? item.item_brief : brief.trim(),+ item_route: route ?? item.item_route,+ item_criterion: criterion === undefined ? item.item_criterion : criterion.trim(),+ item_check: check === undefined ? item.item_check : check.trim(),+ };+ checkRoute(next.item_route);+ const moved = ['item_route', 'item_criterion', 'item_check'].filter((key) => next[key] !== item[key]);+ if (moved.length && item.item_status !== 'open') {+ throw new Refused('HELD', `item #${id} is ${item.item_status}; change its route, criterion or check only while it is open`);}- checkBrief(nextBrief, nextRoute);- setItem(board, id, { item_brief: nextBrief, item_route: nextRoute });+ checkRouted({ brief: next.item_brief, route: next.item_route, criterion: next.item_criterion, check: next.item_check });+ const unfreeze = next.item_criterion !== item.item_criterion || next.item_check !== item.item_check;+ setItem(board, id, { ...next, ...(unfreeze ? { item_frozen: null, item_frozen_digest: null } : {}) });logEvent(board, agentId, 'edit', id, {- ...(nextBrief !== item.item_brief ? { brief: `${nextBrief.length} characters` } : {}),- ...(nextRoute !== item.item_route ? { route: nextRoute } : {}),+ ...(next.item_brief !== item.item_brief ? { brief: `${next.item_brief.length} characters` } : {}),+ ...(next.item_route !== item.item_route ? { route: next.item_route } : {}),+ ...(next.item_criterion !== item.item_criterion ? { criterion: next.item_criterion } : {}),+ ...(next.item_check !== item.item_check ? { check: next.item_check } : {}),+ ...(unfreeze && item.item_frozen_digest ? { unfrozen: item.item_frozen_digest } : {}),});});}+/**+ * Hand an item one tier up (B15): its builder could not get it green, so it goes back open, routed+ * to the next stronger model, with what was tried pinned and why it failed in the log. A strong+ * item stays strong and goes back to the coordinator's attention.+ *+ * @param {any} board+ * @param {number} id+ * @param {{ agentId: string, note: string, attempt?: string }} why+ * @returns {{ from: string, to: string }}+ */+export function escalate(board, id, { agentId, note, attempt = '' }) {+ if (!note.trim()) throw new Refused('NOTE_REQUIRED', 'say what was tried and how it failed: --note "..."');+ return atomic(board, () => {+ const item = current(board, itemById(board, id));+ const isHolder = item.item_status === 'claimed' && item.item_owner === agentId;+ if (!isHolder && agentId !== COORDINATOR) {+ throw new Refused('NOT_YOURS', `item #${id} is not claimed by you; only its holder or the coordinator escalates it`);+ }+ if (!['open', 'claimed'].includes(item.item_status)) {+ throw new Refused('CLOSED', `item #${id} is ${item.item_status}; escalate open or claimed work only`);+ }+ const from = item.item_route;+ const to = ROUTES[Math.min(ROUTES.indexOf(from) + 1, ROUTES.length - 1)];+ setItem(board, id, { item_route: to, item_status: 'open', item_owner: null, item_lease_until: null });+ logEvent(board, agentId, 'escalate', id, { from, to, note: note.trim(), ...(attempt ? { attempt } : {}) });+ return { from, to };+ });+}++/**+ * Record one unattended attempt at an item (A11): which try, how long, and how it ended, so each+ * route's record shows whether its tier pays.+ *+ * @param {any} board+ * @param {number} id+ * @param {{ agentId: string, n: number, seconds: number, result: string }} attempt+ */+export function recordAttempt(board, id, { agentId, n, seconds, result }) {+ logEvent(board, agentId, 'attempt', id, { n, seconds, result });+}+/*** Claim an item, or renew your own claim (B4, B5, B12, V2).*@@ -471,8 +545,9 @@ export function claim(board, id, { agentId, lane, leaseMs, freeze }) {: `item #${id} is in the ${item.item_lane} lane; you are in ${lane}`,);}- if (item.item_route !== 'light' && routeOf(board, agentId) === 'light') {- throw new Refused('ROUTE', `item #${id} needs a strong model; you joined on the light route. Take the next light item: pullboard next`);+ const route = routeOf(board, agentId);+ if (!canTake(route, item.item_route)) {+ throw new Refused('ROUTE', `item #${id} needs a ${item.item_route} model; you joined on the ${route} route. Take your next item: pullboard next`);}for (const dependency of item.item_after ? item.item_after.split(',').map(Number) : []) {const before = itemById(board, dependency);@@ -583,7 +658,7 @@ export function submit(board, id, { agentId, commit, tree }) {* Who may verify an item, as a refusal when `agentId` may not (V1).** The builder never may. Under `verify: "coordinator"`, lane work is the coordinator's to verify,- * and the coordinator's own work is any other agent's. A light agent verifies light items only.+ * and the coordinator's own work is any other agent's. An agent verifies items at its tier or below.** @param {any} board* @param {any} item@@ -594,8 +669,9 @@ function checkVerifier(board, item, agentId, policy) {if (item.item_built_by === agentId) {throw new Refused('SELF_VERIFY', 'the builder never verifies its own work; another agent must');}- if (item.item_route !== 'light' && routeOf(board, agentId) === 'light') {- throw new Refused('ROUTE', `item #${item.item_id} needs a strong verifier; you joined on the light route`);+ const route = routeOf(board, agentId);+ if (!canTake(route, item.item_route)) {+ throw new Refused('ROUTE', `item #${item.item_id} needs a ${item.item_route} verifier; you joined on the ${route} route`);}if (policy === COORDINATOR && item.item_lane !== COORDINATOR && agentId !== COORDINATOR) {throw new Refused('COORDINATOR_VERIFIES', 'this repo has the coordinator verify lane work');@@ -875,27 +951,33 @@ export function events(board, { itemId } = {}) {/*** The next item an agent can take (N2): for a builder, the oldest open item in its lane whose- * dependencies are verified; for a verifier, the oldest submitted item it did not build. A light- * agent sees only items routed light; a strong one takes strong items first, leaving light work for- * light models while there is any (B11). When nothing is free, the reasons say what everything is- * waiting on.+ * dependencies are verified; for a verifier, the oldest submitted item it did not build. An agent+ * sees items at its tier and below, its own tier first, so lighter work waits for lighter models+ * while there is heavier work to do (B13). When nothing is free, the reasons say what everything+ * is waiting on.+ *+ * With `runnable`, only items that carry a check command, which an unattended runner needs.** @param {any} board- * @param {{ agentId: string, lane: string, verify?: boolean }} who+ * @param {{ agentId: string, lane: string, verify?: boolean, runnable?: boolean }} who* @returns {{ item: any | null, reasons: string[] }}*/-export function nextFor(board, { agentId, lane, verify = false }) {- const isLight = routeOf(board, agentId) === 'light';- const items = listItems(board).reverse().filter((entry) => !isLight || entry.item_route === 'light');- const routed = isLight ? 'light ' : '';+export function nextFor(board, { agentId, lane, verify = false, runnable = false }) {+ const route = routeOf(board, agentId);+ const tier = (entry) => ROUTES.indexOf(entry.item_route);+ const items = listItems(board)+ .reverse()+ .filter((entry) => canTake(route, entry.item_route) && (!runnable || entry.item_check))+ .sort((first, second) => tier(second) - tier(first));+ const tiers = route === 'strong' ? '' : `${ROUTES.slice(0, ROUTES.indexOf(route) + 1).reverse().join(' or ')} `;+ const routed = `${tiers}${runnable ? 'runnable ' : ''}`;if (verify) {const item = items.find((entry) => entry.item_status === 'submitted' && entry.item_built_by !== agentId) ?? null;return { item, reasons: item ? [] : [`nothing ${routed}submitted that you did not build`] };}const held = items.find((entry) => entry.item_status === 'claimed' && entry.item_owner === agentId && entry.item_parent_id === null);if (held) return { item: held, reasons: [] };- const open = items.filter((entry) => entry.item_status === 'open' && entry.item_lane === lane);- const mine = [...open.filter((entry) => entry.item_route !== 'light'), ...open.filter((entry) => entry.item_route === 'light')];+ const mine = items.filter((entry) => entry.item_status === 'open' && entry.item_lane === lane);const reasons = [];for (const entry of mine) {const waiting = (entry.item_after ? entry.item_after.split(',').map(Number) : [])diff --git a/src/brief.js b/src/brief.jsnew file mode 100644index 00000000..27a82c38--- /dev/null+++ b/src/brief.js@@ -0,0 +1,43 @@+/**+ * A brief's labelled sections (B10, B14): `Files:`, `Change:`, `Test:` and `Out of scope:`, each+ * followed by text on the same line or by lines below it, until the next label. Below the strong+ * route a brief must name its files and its test, because a lighter model works from the brief alone.+ */++const LABEL_RE = /^(files|change|test|out of scope)\s*:\s*(.*)$/i;++/**+ * The brief split into its labelled sections, each a list of non-empty lines without bullets.+ *+ * @param {string} brief+ * @returns {Record<string, string[]>}+ */+export function briefSections(brief) {+ /** @type {Record<string, string[]>} */+ const sections = {};+ let current = '';+ for (const raw of brief.split('\n')) {+ const line = raw.trim();+ const label = LABEL_RE.exec(line);+ if (label) {+ current = label[1].toLowerCase();+ sections[current] = label[2].trim() ? [label[2].trim()] : [];+ } else if (current && line) {+ sections[current].push(line.replace(/^[-*]\s+/, ''));+ }+ }+ return sections;+}++/**+ * The paths a brief's Files section names, without bullets, backticks or trailing notes.+ *+ * @param {string} brief+ * @returns {string[]}+ */+export function briefFiles(brief) {+ return (briefSections(brief).files ?? [])+ .flatMap((entry) => entry.split(/[,\s]+/))+ .map((token) => token.replace(/^[(`'"]+|[)`'",;:]+$/g, ''))+ .filter((token) => /[./]/.test(token) && !/^[a-z]+:\/\//i.test(token));+}diff --git a/src/cli.js b/src/cli.jsindex 2fb4a16d..aa14f19f 100644--- a/src/cli.js+++ b/src/cli.js@@ -12,13 +12,14 @@ import { runGate } from './gate.js';import { contains, git, headCommit, headTree, isClean, repoInfo, resolveCommit, tryGit, untracked } from './git.js';import {FIX_NOTE,+ applyFixers,commitMsgProblems,installHooks,preCommitProblems,prePushProblems,} from './hooks.js';import { initRepo } from './init.js';-import { isLane, laneNames } from './lanes.js';+import { isLane, laneNames, outOfLane } from './lanes.js';import { Refused } from './refused.js';import { commitCitations, committedIds } from './history.js';import { promptFor } from './skills.js';@@ -33,6 +34,8 @@ import {standings,unmetRows,} from './spec.js';+import { briefFiles } from './brief.js';+import { runItems } from './run.js';import { renderSpecView } from './view.js';const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));@@ -51,11 +54,16 @@ Set upWorkpullboard add <lane> <title> [--criterion "..."] [--specs G1.2,K3] [--after 3,4] [--parent <id>]- [--brief "..." | --brief-file <file>] [--route light]+ [--brief "..." | --brief-file <file>] [--route light|mid]--after: claiming waits until those items are verified--brief: what a cold agent needs; --route light: any model can build it- pullboard edit <id> [--brief "..." | --brief-file <file>] [--route strong|light]- pullboard list [lane] [--all] open and active items; --all adds verified and withdrawn+ [--check "<command>"] the command that proves it; with --criterion and a brief, needed below strong+ pullboard edit <id> [--brief "..." | --brief-file <file>] [--route light|mid|strong] [--criterion "..."] [--check "..."]+ pullboard escalate <id> --note "what was tried and how it failed" hand it one tier up+ pullboard run --agent "<command>" [--attempts 3] [--minutes 15] [--items N] [--wait M]+ build routed items unattended in this worktree: the agent command reads+ the context pack at $PULLBOARD_PACK; green work is submitted, red escalated+ pullboard 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 startpullboard next --verify name the next submitted item you can check@@ -104,6 +112,11 @@ const OPTIONS = {'brief-file': { type: 'string' },route: { type: 'string' },as: { type: 'string' },+ check: { type: 'string' },+ agent: { type: 'string' },+ attempts: { type: 'string' },+ minutes: { type: 'string' },+ items: { type: 'string' },wait: { type: 'string' },verify: { type: 'boolean' },all: { type: 'boolean' },@@ -186,6 +199,23 @@ function checkMainVerifier(ctx, board, values) {);}+/**+ * A brief whose Files section stays inside the item's lane (B14), so a builder working from it+ * never runs into the lane check: an item's files sit in its lane.+ *+ * @param {any} ctx+ * @param {string} lane+ * @param {string} brief+ * @returns {string}+ */+function briefInLane(ctx, lane, brief) {+ const foreign = outOfLane(ctx.config, lane, briefFiles(brief));+ if (foreign.length) {+ throw new Refused('BRIEF_LANE', `the brief names files outside the ${lane} lane: ${foreign.join(', ')}; split the item by lane, or wait on the other lane's item with --after`);+ }+ return brief;+}+/*** Print an item's brief, indented under a heading, when it has one.*@@ -265,7 +295,7 @@ function itemLine(item) {const parent = item.item_parent_id ? ` under #${item.item_parent_id}` : '';const after = item.item_after ? ` after ${item.item_after.split(',').map((id) => `#${id}`).join(',')}` : '';const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : '';- const light = item.item_route === 'light' ? ' light' : '';+ const light = item.item_route === 'strong' ? '' : ` ${item.item_route}`;return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}${after}${light}`;}@@ -370,7 +400,8 @@ function readCommands(io, { first, values }) {},list: () => {const ctx = context(io);- const items = withBoard(ctx, (board) => store.listItems(board, { lane: first, all: values.all }));+ const items = withBoard(ctx, (board) => store.listItems(board, { lane: first, all: values.all }))+ .filter((item) => !values.route || item.item_route === values.route);if (values.json) io.say(JSON.stringify(items, null, 2));else if (!items.length) io.say(values.all ? 'no items yet' : 'nothing open; --all shows closed items');else items.forEach((item) => io.say(itemLine(item)));@@ -379,9 +410,10 @@ function readCommands(io, { first, values }) {show: () => {const ctx = context(io);const id = idArg(first);- const { item, verdicts } = withBoard(ctx, (board) => ({+ const { item, verdicts, moves } = withBoard(ctx, (board) => ({item: store.getItem(board, id),verdicts: store.verdictsFor(board, id),+ moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),}));if (values.json) {io.say(JSON.stringify({ ...item, verdicts }, null, 2));@@ -389,7 +421,14 @@ function readCommands(io, { first, values }) {}io.say(itemLine(item));if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);+ if (item.item_check) io.say(`check: ${item.item_check}`);sayBrief(io, item.item_brief);+ const attempts = moves.filter((event) => event.event_kind === 'attempt').map((event) => JSON.parse(event.event_detail).result);+ if (attempts.length) io.say(`unattended attempts: ${attempts.join(', ')}`);+ for (const event of moves.filter((entry) => entry.event_kind === 'escalate')) {+ const detail = JSON.parse(event.event_detail);+ io.say(`escalated ${detail.from} -> ${detail.to} by ${event.event_by}${detail.attempt ? `, pinned at ${detail.attempt}` : ''}: ${detail.note.split('\n')[0]}`);+ }if (item.item_frozen) {const frozen = JSON.parse(item.item_frozen);io.say(`frozen at claim (${item.item_frozen_digest.slice(0, 12)}):`);@@ -544,7 +583,7 @@ function nextOnce(ctx, values) {return withBoard(ctx, (board) => {if (values.verify) checkMainVerifier(ctx, board, values);const me = whoAmI(ctx, board);- const { item, reasons } = store.nextFor(board, { agentId: me.id, lane: me.lane, verify: values.verify });+ const { item, reasons } = store.nextFor(board, { agentId: me.id, lane: me.lane, verify: values.verify, runnable: values.runnable });if (!item) return { reasons };if (values.verify) return { item };if (item.item_status === 'claimed') return { item, held: true };@@ -586,6 +625,7 @@ async function nextHere(io, values) {} else {io.say(`${found.held ? 'you hold' : 'claimed'} #${item.item_id}: ${item.item_title}`);if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);+ if (item.item_check) io.say(`check: ${item.item_check} (run it before you submit)`);for (const row of item.item_frozen ? JSON.parse(item.item_frozen).rows : []) io.say(` ${row.id}: ${row.text}`);sayBrief(io, item.item_brief);io.say(`when it is built and committed: ${here} pullboard submit ${item.item_id}`);@@ -631,18 +671,36 @@ function workCommands(io, args) {specIds,parentId,after,- brief: briefArg(io, values) ?? '',+ brief: briefInLane(ctx, first, briefArg(io, values) ?? ''),route: values.route ?? 'strong',+ check: values.check ?? '',});io.say(`#${id}`);return 0;}),edit: () => act((ctx, board, me) => {const id = idArg(first);- store.editItem(board, id, { agentId: me.id, brief: briefArg(io, values), route: values.route });+ const brief = briefArg(io, values);+ store.editItem(board, id, {+ agentId: me.id,+ brief: brief === undefined ? undefined : briefInLane(ctx, store.getItem(board, id).item_lane, brief),+ route: values.route,+ criterion: values.criterion,+ check: values.check,+ });io.say(`edited #${id}`);return 0;}),+ escalate: () => act((ctx, board, me) => {+ const id = idArg(first);+ const moved = store.escalate(board, id, { agentId: me.id, note: values.note ?? '' });+ if (me.id !== COORDINATOR) {+ store.shout(board, { from: me.id, to: COORDINATOR, text: `#${id} escalated ${moved.from} -> ${moved.to}: ${values.note}`, lanes: laneNames(ctx.config) });+ }+ io.say(`#${id} escalated ${moved.from} -> ${moved.to}; it is open for a ${moved.to} agent`);+ return 0;+ }),+ run: () => runItems(io, values, { context, withBoard, whoAmI, nextOnce, submitHere, freezer }),next: () => nextHere(io, values),claim: () => act((ctx, board, me) => {const result = store.claim(board, idArg(first), { agentId: me.id, lane: me.lane, leaseMs: ctx.config.leaseMs, freeze: freezer(ctx) });@@ -802,6 +860,7 @@ async function hookCommand(io, { first, second }) {}let problems = [];if (first === 'pre-commit') {+ applyFixers(info.root, ctx.config.fix).forEach((note) => io.err(`pullboard pre-commit: ${note}`));const agent = info.isMain ? null : withBoard(ctx, (board) => store.agentAt(board, info.root));problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent });} else if (first === 'commit-msg') {diff --git a/src/config.js b/src/config.jsindex 092f600e..885a4957 100644--- a/src/config.js+++ b/src/config.js@@ -40,6 +40,7 @@ export function defaults() {verify: 'any',lanes: {},shared: [],+ fix: [],commits: {types: [...COMMIT_TYPES],maxHeader: 72,@@ -131,6 +132,10 @@ export function configProblems(config) {problems.push('"verify" is "any" (any other agent) or "coordinator"');}if (!isStringList(config.shared)) problems.push('"shared" is a list of path prefixes');+ const isFixer = (fixer) => typeof fixer?.run === 'string' && fixer.run.trim() && (fixer.files === undefined || isStringList(fixer.files));+ if (!Array.isArray(config.fix) || !config.fix.every(isFixer)) {+ problems.push('"fix" is a list of { "run": "<command that fixes the files it is given>", "files": ["*.ts"] }');+ }if (typeof config.lanes !== 'object' || config.lanes === null || Array.isArray(config.lanes)) {problems.push('"lanes" maps lane names to { owns, specs, starts }');} else {diff --git a/src/hooks.js b/src/hooks.jsindex e29dbda1..5596b8f4 100644--- a/src/hooks.js+++ b/src/hooks.js@@ -3,6 +3,7 @@* its folders, no secret or env file is committed, and a push sends exactly what the gate checked.* Each check returns its problems; an empty list lets git go on.*/+import { spawnSync } from 'node:child_process';import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { git, tryGit } from './git.js';@@ -217,6 +218,48 @@ export function preCommitProblems({ root, isMain, config, agent }) {return problems;}+/**+ * A path quoted for the shell, whatever characters it holds.+ *+ * @param {string} text+ * @returns {string}+ */+const shellQuote = (text) => `'${text.replace(/'/g, `'\\''`)}'`;++/**+ * Run the repo's fixers on the staged files they cover, and stage what they fixed (C5): a formatter+ * is a deterministic tool, so no agent should spend a turn running it, and none should fail a gate+ * on what a tool could have fixed. Only fully staged files are touched; fixing a partly staged one+ * would stage the hunks its author left out. A fixer that fails stages nothing, and the gate reports+ * what it could not fix.+ *+ * @param {string} root+ * @param {{ run: string, files?: string[] }[]} fixers+ * @returns {string[]} Notes for the person committing.+ */+export function applyFixers(root, fixers) {+ if (!fixers.length) return [];+ const { written } = stagedPaths(root);+ const unstaged = new Set(git(root, ['diff', '--name-only', '-z']).split('\0').filter(Boolean));+ const covers = (fixer, path) => (fixer.files ?? ['*']).some((pattern) => matchesPattern(pattern, path));+ const notes = [];+ for (const fixer of fixers) {+ const files = written.filter((path) => covers(fixer, path) && !unstaged.has(path) && existsSync(join(root, path)));+ if (!files.length) continue;+ const result = spawnSync(`${fixer.run} ${files.map(shellQuote).join(' ')}`, {+ cwd: root,+ shell: true,+ encoding: 'utf8',+ timeout: 120_000,+ });+ if (result.status === 0) git(root, ['add', '--', ...files]);+ else notes.push(`fixer "${fixer.run}" failed (${result.status ?? 'timed out'}); staged nothing from it, so the gate will name what it could not fix`);+ }+ const partly = written.filter((path) => unstaged.has(path) && fixers.some((fixer) => covers(fixer, path)));+ if (partly.length) notes.push(`not fixed, because they are partly staged: ${partly.join(', ')}`);+ return notes;+}+/*** Rows the staged change deletes from the spec or the practice (S8). Nobody is exempt, the* coordinator included: a commit or an item may cite any row, so a row that is cut stays, markeddiff --git a/src/init.js b/src/init.jsindex 8f1dd200..7e4b6227 100644--- a/src/init.js+++ b/src/init.js@@ -31,6 +31,25 @@ export function detectGate(root) {}}+/**+ * The fixers to start with (C5): prettier, when the repo already depends on it, on every file it+ * understands. Only fast, deterministic fixers belong at commit time; slow ones stay in the gate.+ *+ * @param {string} root+ * @returns {{ run: string, files: string[] }[]}+ */+export function detectFixers(root) {+ const file = join(root, 'package.json');+ if (!existsSync(file)) return [];+ try {+ const pkg = JSON.parse(readFileSync(file, 'utf8'));+ const hasPrettier = Boolean(pkg?.devDependencies?.prettier ?? pkg?.dependencies?.prettier);+ return hasPrettier ? [{ run: 'npx --no-install prettier --write --ignore-unknown', files: ['*'] }] : [];+ } catch {+ return [];+ }+}+/*** The gate the repo's config sets now, whoever wrote it, or empty when unreadable.*@@ -100,7 +119,7 @@ export function initRepo({ info, openBoardHere, register, closeBoard }) {const { root } = info;const gate = detectGate(root);const notes = [- writeNew(join(root, CONFIG_FILE), configTemplate(gate), CONFIG_FILE),+ writeNew(join(root, CONFIG_FILE), configTemplate(gate, detectFixers(root)), CONFIG_FILE),writeNew(join(root, 'SPEC.md'), specTemplate(basename(root)), 'SPEC.md'),writeNew(join(root, 'PRACTICE.md'), practiceTemplate(), 'PRACTICE.md'),...writeAgentDocs(root),diff --git a/src/run.js b/src/run.jsnew file mode 100644index 00000000..ffb4bce8--- /dev/null+++ b/src/run.js@@ -0,0 +1,353 @@+/**+ * `pullboard run` (N14, B15): builds routed items with no one at the keyboard. For each item it may+ * take, it writes a context pack (the bar, the cited rows, the brief and the files as they are now),+ * runs the agent command the person configured, runs the item's check, and feeds a short digest of+ * any failure into the next attempt. Green work is committed, gated and submitted for a second agent+ * to verify. Work still red after the last attempt is pinned under refs/pullboard/attempts and+ * escalated one tier up, so a stronger model starts from what was tried.+ *+ * Pullboard never calls a model itself (E4): the agent command is whatever the person runs, such as+ * OpenCode on a local model or Claude Code headless on a smaller one.+ */+import { spawn, spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import * as store from './board.js';+import { briefFiles } from './brief.js';+import { COORDINATOR } from './config.js';+import { runGate } from './gate.js';+import { git, headCommit, isClean, tryGit, untracked } from './git.js';+import { laneNames, outOfLane } from './lanes.js';+import { Refused } from './refused.js';++const DIGEST_CHARS = 3000;+const FILE_CHARS = 32_000;+const PACK_FILE_CHARS = 96_000;+const FAILURE_RE = /fail|error|expected|received|assert|not ok|✗|×|cannot|undefined|exception/i;++/**+ * A whole number from a flag, within bounds, or a refusal naming the flag.+ *+ * @param {string} text+ * @param {number} low+ * @param {number} high+ * @param {string} flag+ * @returns {number}+ */+function boundedInt(text, low, high, flag) {+ const value = Number(text);+ if (!Number.isInteger(value) || value < low || value > high) {+ throw new Refused('USAGE', `${flag} is a whole number from ${low} to ${high}`);+ }+ return value;+}++/**+ * Run a shell command in its own process group, so a timeout stops everything it started.+ *+ * @param {string} command+ * @param {{ cwd: string, env?: NodeJS.ProcessEnv, timeoutMs: number }} options+ * @returns {Promise<{ status: number | null, output: string, timedOut: boolean, seconds: number }>}+ */+function runCommand(command, { cwd, env = process.env, timeoutMs }) {+ const started = Date.now();+ return new Promise((done) => {+ const child = spawn(command, { cwd, env, shell: true, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ let output = '';+ const keep = (chunk) => {+ output = (output + chunk.toString()).slice(-200_000);+ };+ child.stdout.on('data', keep);+ child.stderr.on('data', keep);+ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ try {+ process.kill(-child.pid, 'SIGKILL');+ } catch {+ child.kill('SIGKILL');+ }+ }, timeoutMs);+ child.on('close', (status) => {+ clearTimeout(timer);+ done({ status, output, timedOut, seconds: Math.round((Date.now() - started) / 1000) });+ });+ });+}++/**+ * The lines of a failure worth a model's attention: those that look like failures first, then the+ * end of the output, capped, so a retry carries the reason and not the whole log.+ *+ * @param {string} output+ * @returns {string}+ */+export function digestOf(output) {+ const lines = output.split('\n').map((line) => line.trimEnd()).filter(Boolean);+ const failing = lines.filter((line) => FAILURE_RE.test(line)).slice(0, 25);+ const tail = lines.slice(-15);+ const kept = [...new Set([...failing, ...tail])].join('\n');+ return kept.length > DIGEST_CHARS ? `${kept.slice(0, DIGEST_CHARS)}\n...` : kept;+}++/**+ * Every path that differs from the commit the item started at, committed or not, untracked included.+ *+ * @param {string} root+ * @param {string} start+ * @returns {string[]}+ */+function changedSince(root, start) {+ const tracked = git(root, ['diff', '--name-only', '-z', start]).split('\0');+ const fresh = git(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0');+ return [...new Set([...tracked, ...fresh].filter(Boolean))];+}++/**+ * Put paths back as they were when the item started: restored if they existed, removed if not.+ *+ * @param {string} root+ * @param {string} start+ * @param {string[]} paths+ */+function restore(root, start, paths) {+ for (const path of paths) {+ if (tryGit(root, ['cat-file', '-e', `${start}:${path}`]).status === 0) git(root, ['checkout', start, '--', path]);+ else rmSync(join(root, path), { force: true });+ }+}++/**+ * The context pack for one attempt: everything a model needs to build the item from cold, the+ * files it may change included, so it reads them once here instead of again and again.+ *+ * @param {string} root+ * @param {any} item+ * @param {{ attempt: number, attempts: number, digest: string }} state+ * @returns {string}+ */+export function packText(root, item, { attempt, attempts, digest }) {+ const rows = item.item_frozen ? JSON.parse(item.item_frozen).rows : [];+ const files = briefFiles(item.item_brief);+ let budget = PACK_FILE_CHARS;+ const contents = files.map((path) => {+ const file = join(root, path);+ if (!existsSync(file) || !statSync(file).isFile()) return `### ${path}\n(does not exist yet; create it)`;+ const text = readFileSync(file, 'utf8');+ if (text.length > FILE_CHARS || text.length > budget) return `### ${path}\n(${text.length} characters; open it yourself)`;+ budget -= text.length;+ return `### ${path}\n\`\`\`\n${text}\n\`\`\``;+ });+ return [+ `# Item #${item.item_id}: ${item.item_title}`,+ '',+ `You are building one item in the ${item.item_lane} lane of this repo. Attempt ${attempt} of ${attempts}.`,+ '',+ '## Done when',+ item.item_criterion || '(see the brief)',+ '',+ `The check that proves it, which the runner runs after you finish: \`${item.item_check}\``,+ ...(rows.length ? ['', '## Spec rows it serves', ...rows.map((row) => `- ${row.id}: ${row.text}`)] : []),+ '',+ '## Brief',+ item.item_brief || '(none)',+ '',+ '## Rules',+ `- Change only the files the brief lists${files.length ? `: ${files.join(', ')}` : ''}. Changes anywhere else are reverted.`,+ '- Never run git commands; the runner commits your work.',+ '- Add no dependencies. Change a test only where the brief says to.',+ '- Run the check yourself before you finish, and stop when it passes.',+ ...(digest+ ? ['', '## Your previous attempt', 'It left the files as they are below. Continue from them. It failed with:', '```', digest, '```', 'Fix exactly that.']+ : []),+ ...(contents.length ? ['', '## The files, as they are now', ...contents] : []),+ '',+ ].join('\n');+}++/**+ * A commit header for the runner's commit, within the repo's rules: the item's title as a subject,+ * or its number when the title cannot be one.+ *+ * @param {any} item+ * @param {any} rules+ * @param {boolean} plain+ * @returns {string}+ */+function commitHeader(item, rules, plain) {+ const ids = item.item_spec_ids ? ` [${item.item_spec_ids}]` : '';+ const type = ids && rules.types.includes('feat') ? 'feat' : 'chore';+ const prefix = `${type}(${item.item_lane}): `;+ const title = item.item_title.replace(/\s+/g, ' ').replace(/[.\s]+$/, '');+ const subject = plain || !title ? `build item ${item.item_id}` : title[0].toLowerCase() + title.slice(1);+ const room = rules.maxHeader - prefix.length - ids.length;+ return `${prefix}${subject.slice(0, room).trimEnd()}${ids}`;+}++/**+ * Commit the item's changes, the paths it may change and nothing else, through the repo's hooks.+ * When the hooks refuse the title as a subject, it tries once more with the item's number.+ *+ * @param {string} root+ * @param {any} item+ * @param {any} config+ * @param {string[]} paths+ * @returns {{ ok: boolean, output: string }}+ */+function commitWork(root, item, config, paths) {+ git(root, ['add', '-A', '--', ...paths]);+ let output = '';+ for (const plain of [false, true]) {+ const result = spawnSync('git', ['commit', '-q', '-m', commitHeader(item, config.commits, plain)], { cwd: root, encoding: 'utf8' });+ if (result.status === 0) return { ok: true, output: '' };+ output = `${result.stdout}${result.stderr}`;+ }+ return { ok: false, output };+}++/**+ * Pin the worktree as it is, untracked files included, under refs/pullboard/attempts, without+ * touching the index or the files, so escalating never loses what was tried.+ *+ * @param {string} root+ * @param {number} id+ * @returns {string} The ref.+ */+function pinAttempt(root, id) {+ const index = join(git(root, ['rev-parse', '--path-format=absolute', '--git-dir']), 'pullboard-attempt-index');+ const env = { ...process.env, GIT_INDEX_FILE: index };+ const step = (args) => {+ const result = spawnSync('git', args, { cwd: root, env, encoding: 'utf8' });+ if (result.status !== 0) throw new Refused('PIN_FAILED', `could not pin the attempt: git ${args[0]} said ${result.stderr.trim()}`);+ return result.stdout.trim();+ };+ try {+ step(['read-tree', 'HEAD']);+ step(['add', '-A']);+ const tree = step(['write-tree']);+ const commit = step(['commit-tree', tree, '-p', 'HEAD', '-m', `pullboard: attempt at item #${id}`]);+ const ref = `refs/pullboard/attempts/${id}/${commit.slice(0, 12)}`;+ git(root, ['update-ref', ref, commit]);+ return ref;+ } finally {+ rmSync(index, { force: true });+ }+}++/**+ * Build one claimed item: attempts until the check and the gate pass, then submit; or pin, reset+ * and escalate.+ *+ * @param {any} ctx+ * @param {any} item+ * @param {any} options+ * @returns {Promise<'submitted' | 'escalated'>}+ */+async function buildItem(ctx, item, { agent, attempts, minutes, deps, me }) {+ const { root } = ctx.info;+ const id = item.item_id;+ const start = headCommit(root) ?? '';+ 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 = '';+ 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}-${attempt}.md`);+ writeFileSync(pack, packText(root, fresh, { attempt, attempts, digest }));+ ctx.io.say(`#${id} attempt ${attempt}/${attempts}: running the agent`);+ const env = { ...process.env, PULLBOARD_PACK: pack, PULLBOARD_ITEM: String(id), PULLBOARD_ATTEMPT: String(attempt) };+ const built = await runCommand(agent, { cwd: root, env, timeoutMs: minutes * 60_000 });+ writeFileSync(join(packs, `${id}-${attempt}.log`), built.output);+ 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 });+ let result = 'green';+ if (checked.status !== 0) {+ result = 'red';+ digest = `${late}${reverted}The check \`${item.item_check}\` failed:\n${digestOf(checked.output)}`;+ } else {+ const isDirty = !isClean(root) || untracked(root).length > 0;+ const committed = isDirty ? commitWork(root, item, ctx.config, changedSince(root, start)) : { ok: true, output: '' };+ const gate = committed.ok ? runGate(root, ctx.config, { stdio: 'pipe' }) : { isGreen: false, output: committed.output };+ if (!gate.isGreen) {+ result = committed.ok ? 'gate-red' : 'commit-refused';+ digest = `${reverted}The check passed, but ${committed.ok ? "the repo's gate" : 'the commit'} failed:\n${digestOf(gate.output)}`;+ }+ }+ ctx.io.say(`#${id} attempt ${attempt}: ${result} (agent ${built.seconds}s, check ${checked.seconds}s)`);+ if (result === 'green') {+ try {+ deps.submitHere(ctx, id);+ } catch (error) {+ if (!(error instanceof Refused)) throw error;+ result = 'submit-refused';+ digest = `The check and the gate passed, but submit refused: ${error.message}`;+ 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';+ }+ const ref = pinAttempt(root, id);+ git(root, ['reset', '-q', '--hard', start]);+ git(root, ['clean', '-q', '-fd']);+ 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) });+ return result;+ });+ ctx.io.say(`#${id} escalated ${moved.from} -> ${moved.to}; the attempt is pinned at ${ref}`);+ return 'escalated';+}++/**+ * The runner: claims the items this worktree's agent may take, one at a time, and builds each.+ *+ * @param {any} io+ * @param {any} values+ * @param {{ context: Function, withBoard: Function, whoAmI: Function, nextOnce: Function, submitHere: Function, freezer: Function }} deps+ * @returns {Promise<number>}+ */+export async function runItems(io, values, deps) {+ const ctx = deps.context(io);+ 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 agent = String(values.agent ?? '').trim();+ if (!agent) {+ throw new Refused('USAGE', 'pullboard run --agent "<command>": the command that builds one item from the pack in $PULLBOARD_PACK, such as: opencode run "$(cat "$PULLBOARD_PACK")"');+ }+ const attempts = boundedInt(values.attempts ?? '3', 1, 10, '--attempts');+ const minutes = boundedInt(values.minutes ?? '15', 1, 240, '--minutes');+ const limit = values.items === undefined ? Infinity : boundedInt(values.items, 1, 1000, '--items');+ const waitMinutes = values.wait === undefined ? 0 : boundedInt(values.wait, 0, 240, '--wait');+ if (!ctx.config.gate.trim()) throw new Refused('NO_GATE', 'the runner submits through the gate; set "gate" in pullboard.json first');+ if (!isClean(ctx.info.root) || untracked(ctx.info.root).length) {+ 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 totals = { submitted: 0, escalated: 0 };+ const deadline = Date.now() + waitMinutes * 60_000;+ while (totals.submitted + totals.escalated < limit) {+ const found = deps.nextOnce(ctx, { runnable: true });+ if (found.retry) continue;+ if (!found.item) {+ if (Date.now() >= deadline) {+ io.say(`nothing left to run: ${found.reasons.join('; ')}`);+ break;+ }+ await new Promise((done) => setTimeout(done, 5000));+ continue;+ }+ totals[await buildItem(ctx, found.item, { agent, attempts, minutes, deps, me })] += 1;+ }+ io.say(`runner done: ${totals.submitted} submitted, ${totals.escalated} escalated`);+ return 0;+}diff --git a/src/spec.js b/src/spec.jsindex 0ae779b2..1c85b4e9 100644--- a/src/spec.js+++ b/src/spec.js@@ -201,11 +201,12 @@ export function idProblems(spec, ids) {}/**- * The text an item is held to, and its digest (V2): its title, its criterion, and the current text- * of every spec row it cites. Frozen at first claim; a verdict must match it.+ * The text an item is held to, and its digest (V2): its title, its criterion, its check command when+ * it has one, and the current text of every spec row it cites. Frozen at first claim; a verdict must+ * match it.** @param {ReturnType<typeof parseSpec>} spec- * @param {{ item_title: string, item_criterion: string, item_spec_ids: string }} item+ * @param {{ item_title: string, item_criterion: string, item_spec_ids: string, item_check?: string }} item* @returns {{ text: string, digest: string }}*/export function frozenCriterion(spec, item) {@@ -216,7 +217,8 @@ export function frozenCriterion(spec, item) {const row = spec.rows.find((entry) => entry.id === id);return { id, text: row.text, gate: row.gate };});- const text = JSON.stringify({ title: item.item_title, criterion: item.item_criterion, rows });+ const check = item.item_check ? { check: item.item_check } : {};+ const text = JSON.stringify({ title: item.item_title, criterion: item.item_criterion, ...check, rows });return { text, digest: createHash('sha256').update(text).digest('hex') };}diff --git a/src/templates.js b/src/templates.jsindex 7e36fec0..649ddf8e 100644--- a/src/templates.js+++ b/src/templates.js@@ -7,14 +7,16 @@ export const AGENTS_START = '<!-- pullboard:start -->';export const AGENTS_END = '<!-- pullboard:end -->';/**- * The starting pullboard.json: the gate init detected, the spec, and no lanes yet.+ * The starting pullboard.json: the gate and the fixers init detected, the spec, and no lanes yet.** @param {string} gate+ * @param {{ run: string, files: string[] }[]} [fix]* @returns {string}*/-export function configTemplate(gate) {+export function configTemplate(gate, fix = []) {const config = {gate,+ ...(fix.length ? { fix } : {}),spec: 'SPEC.md',practice: 'PRACTICE.md',verify: 'any',@@ -122,7 +124,7 @@ This repo runs on pullboard: a work board, lanes and a spec that live in git. Nopullboard worktree <lane>-It prints the folder to work in and what to run there first. Work only in that folder. Your shell may start every command in the main checkout, where pullboard takes you for the coordinator, so begin each command with \`cd <your worktree> &&\`. Verifiers take the \`review\` lane, which owns no folders. A lighter model joins with \`--route light\` and takes only items routed light, each with a brief. Keep your worktree and branch until your items are merged.+It prints the folder to work in and what to run there first. A smaller model joins with \`--route light\` or \`--route mid\` and takes items at its tier and below. Work only in that folder. Your shell may start every command in the main checkout, where pullboard takes you for the coordinator, so begin each command with \`cd <your worktree> &&\`. Verifiers take the \`review\` lane, which owns no folders. Keep your worktree and branch until your items are merged.**The loop.**1. \`pullboard inbox\`.@@ -130,7 +132,7 @@ It prints the folder to work in and what to run there first. Work only in that f3. Build inside your lane's folders (\`pullboard lanes\`). Pre-commit refuses anything else; shout the owner instead.4. Commit, then \`pullboard submit <id>\`. It needs a clean tree and the gate green at HEAD.5. A different agent verifies: \`pullboard next --verify\` names the next item to check. It checks out the submitted commit and runs \`pullboard verify <id> accept --note "how it proved it"\`, or \`pullboard verify <id> reject --reason TEST_FAILURE --note "what failed"\`.-6. A reject reopens the item. Fix it, commit, claim, submit again; the same head is refused.+6. A reject reopens the item. Fix it, commit, claim, submit again; the same head is refused. If you cannot get an item green, do not force it: \`pullboard escalate <id> --note "what you tried and how it failed"\` hands it one tier up.7. Your lane is done when its items are verified, not when they are submitted. After your last submit, keep running \`pullboard next --wait 30\`: a rejected item comes back to your lane.The coordinator merges verified items into the main line; builders never merge.