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(cli): init, the board commands and receipts [I1,R1,B3]
Corey Olsonb0c85f41f835
diff --git a/bin/pullboard.js b/bin/pullboard.jsnew file mode 100755index 00000000..26f718e2--- /dev/null+++ b/bin/pullboard.js@@ -0,0 +1,18 @@+#!/usr/bin/env node+/**+ * The pullboard command. Node 22 announces that node:sqlite is experimental; that notice is noise+ * for a CLI, so it is dropped before the board module loads. Every other warning still prints.+ */+const emitWarning = process.emitWarning;+process.emitWarning = (warning, ...rest) => {+ if (String(warning).includes('SQLite is an experimental feature')) return;+ emitWarning.call(process, warning, ...rest);+};++const { main } = await import('../src/cli.js');+process.exitCode = await main(process.argv.slice(2), {+ cwd: process.cwd(),+ stdout: process.stdout,+ stderr: process.stderr,+ stdin: process.stdin,+});diff --git a/src/cli.js b/src/cli.jsnew file mode 100644index 00000000..0f166a2a--- /dev/null+++ b/src/cli.js@@ -0,0 +1,613 @@+/**+ * The pullboard command line: every command, bound to who is asking (B3). The main checkout is the+ * coordinator; every other worktree is the agent that joined from it.+ */+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { parseArgs } from 'node:util';+import * as store from './board.js';+import { COORDINATOR, loadConfig } from './config.js';+import { runGate } from './gate.js';+import { contains, headCommit, headTree, isClean, repoInfo, resolveCommit, untracked } from './git.js';+import {+ commitMsgProblems,+ installHooks,+ preCommitProblems,+ prePushProblems,+} from './hooks.js';+import { initRepo } from './init.js';+import { isLane, laneNames } from './lanes.js';+import { Refused } from './refused.js';+import {+ frozenCriterion,+ idProblems,+ lintSpec,+ loadSpec,+ readSignoffs,+ signOff,+ standings,+ unmetRows,+} from './spec.js';++const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));+export const VERSION = PACKAGE.version;++export const HELP = `pullboard ${VERSION}: the local-first work board for teams of coding agents.+Nothing ships until a second agent verifies it.++Set up+ pullboard init config, SPEC.md, agent instructions, git hooks, board+ pullboard join <lane> register this worktree as an agent in a lane+ pullboard whoami | lanes | status who you are, the lanes, the board at a glance+ pullboard hooks reinstall the git hooks (e.g. after a fresh clone)++Work+ pullboard add <lane> <title> [--criterion "..."] [--specs G1.2,K3] [--parent <id>]+ pullboard list [lane] [--all] open and active items; --all adds verified and withdrawn+ pullboard show <id> an item, the criterion frozen at claim, its verdicts+ pullboard claim <id> take or renew a lease; the first claim freezes the criterion+ pullboard release <id> hand it back+ pullboard submit <id> needs a clean tree and the gate green at HEAD (alias: done)+ pullboard verify <id> accept from the submitted commit, by anyone but the builder+ pullboard verify <id> reject --reason TEST_FAILURE --note "what failed"+ pullboard shout <lane|agent|all> <text> pullboard inbox++Coordinator+ pullboard merged <id> <commit> record where verified work landed+ pullboard withdraw <id> <reason> drop an item nobody should build+ pullboard refreeze <id> re-freeze a criterion after its spec rows changed++Receipts+ pullboard ledger markdown: what was built, by whom, verified by whom+ pullboard log [id] every move, in order++Spec+ pullboard spec check | show <id> | unmet [--must] | signoff <ids> --by <initials>++Gate and hooks+ pullboard gate run the configured gate+ pullboard hook pre-commit|commit-msg|pre-push git runs these++Reject reasons: TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HEAD, OTHER.+--json prints list, show and status as JSON.`;++const OPTIONS = {+ criterion: { type: 'string' },+ specs: { type: 'string' },+ parent: { type: 'string' },+ reason: { type: 'string' },+ note: { type: 'string' },+ by: { type: 'string' },+ all: { type: 'boolean' },+ must: { type: 'boolean' },+ json: { type: 'boolean' },+ help: { type: 'boolean', short: 'h' },+ version: { type: 'boolean', short: 'v' },+};++/**+ * A positive whole number from an argument, or a refusal naming what was expected.+ *+ * @param {string | undefined} text+ * @param {string} what+ * @returns {number}+ */+function idArg(text, what = 'an item id') {+ const id = Number(String(text ?? '').replace(/^#/, ''));+ if (!Number.isInteger(id) || id < 1) throw new Refused('USAGE', `expected ${what}, got "${text ?? ''}"`);+ return id;+}++/**+ * A comma list of spec ids from a flag.+ *+ * @param {string | undefined} text+ * @returns {string[]}+ */+const idList = (text) => (text ?? '').split(',').map((id) => id.trim()).filter(Boolean);++/**+ * Everything a command needs: the repo, its config, the board's file, and where output goes.+ *+ * @param {any} io+ * @returns {any}+ */+function context(io) {+ const info = repoInfo(io.cwd);+ const config = loadConfig(info.root);+ const file = join(info.commonDir, 'pullboard', 'board.sqlite');+ return { info, config, file, io, clock: io.clock ?? store.systemClock };+}++/**+ * Open the board, run `work`, and always close it.+ *+ * @template T+ * @param {any} ctx+ * @param {(board: any) => T} work+ * @returns {T}+ */+function withBoard(ctx, work) {+ const board = store.openBoard(ctx.file, ctx.clock);+ try {+ return work(board);+ } finally {+ store.closeBoard(board);+ }+}++/**+ * Who is asking: the coordinator in the main checkout, or the agent this worktree joined as.+ *+ * @param {any} ctx+ * @param {any} board+ * @returns {{ id: string, lane: string }}+ */+function whoAmI(ctx, board) {+ if (ctx.info.isMain) return { id: store.ensureCoordinator(board, ctx.info.root), lane: COORDINATOR };+ const agent = store.agentAt(board, ctx.info.root);+ if (!agent) {+ throw new Refused('NOT_JOINED', 'this worktree has not joined a lane: pullboard join <lane> (see: pullboard lanes)');+ }+ return { id: agent.agent_id, lane: agent.agent_lane };+}++/**+ * The criterion an item is held to, frozen from the spec as it reads now.+ *+ * @param {any} ctx+ * @returns {(item: any) => { text: string, digest: string }}+ */+const freezer = (ctx) => (item) => frozenCriterion(loadSpec(ctx.info.root, ctx.config), item);++/**+ * One item on one line: id, status and holder, lane, title, spec ids.+ *+ * @param {any} item+ * @returns {string}+ */+function itemLine(item) {+ const holder = item.item_status === 'claimed' ? ` ${item.item_owner}` : '';+ const verifier = item.item_status === 'verified' ? ` by ${item.item_verified_by}` : '';+ const specs = item.item_spec_ids ? ` [${item.item_spec_ids}]` : '';+ const parent = item.item_parent_id ? ` under #${item.item_parent_id}` : '';+ const rejected = item.item_status === 'open' && item.item_verdict === 'REJECT' ? ' (rejected)' : '';+ return `#${item.item_id} ${item.item_status}${holder}${verifier}${rejected} ${item.item_lane} ${item.item_title}${specs}${parent}`;+}++/**+ * The commands that set a repo or a worktree up.+ *+ * @param {any} io+ * @param {{ first?: string }} args+ * @returns {Record<string, () => number>}+ */+function setupCommands(io, { first }) {+ return {+ init: () => {+ const info = repoInfo(io.cwd);+ const notes = initRepo({+ info,+ openBoardHere: () => store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), io.clock),+ register: store.register,+ closeBoard: store.closeBoard,+ });+ notes.forEach((note) => io.say(note));+ io.say('next: write SPEC.md rows, declare lanes in pullboard.json, then: pullboard add <lane> <title>');+ return 0;+ },+ hooks: () => {+ installHooks(repoInfo(io.cwd).root).forEach((note) => io.say(note));+ return 0;+ },+ join: () => {+ const ctx = context(io);+ if (ctx.info.isMain) throw new Refused('MAIN_IS_COORDINATOR', 'the main checkout is the coordinator; join from a worktree: git worktree add ../<dir>');+ if (!first || first === COORDINATOR || !isLane(ctx.config, first)) {+ throw new Refused('NO_LANE', `no lane "${first ?? ''}"; lanes: ${laneNames(ctx.config).slice(1).join(', ') || 'none yet, declare them in pullboard.json'}`);+ }+ const id = withBoard(ctx, (board) => store.register(board, { lane: first, path: ctx.info.root }));+ io.say(`joined as ${id} in the ${first} lane`);+ return 0;+ },+ };+}++/**+ * The commands that read the board without changing it.+ *+ * @param {any} io+ * @param {any} args+ * @returns {Record<string, () => number>}+ */+function readCommands(io, { first, values }) {+ return {+ whoami: () => {+ const ctx = context(io);+ const me = withBoard(ctx, (board) => whoAmI(ctx, board));+ io.say(`${me.id} (${me.lane} lane) at ${ctx.info.root}`);+ return 0;+ },+ lanes: () => {+ const { config } = context(io);+ io.say(`${COORDINATOR.padEnd(14)} everything no lane owns; verifies, merges, may change any path`);+ for (const [name, lane] of Object.entries(config.lanes)) {+ const specs = lane.specs?.length ? ` [${lane.specs.join(', ')}]` : '';+ const starts = lane.starts ? ` starts: ${lane.starts}` : '';+ io.say(`${name.padEnd(14)} ${lane.owns.join(' ')}${specs}${starts}`);+ }+ if (config.shared.length) io.say(`${'shared'.padEnd(14)} ${config.shared.join(' ')} (any lane)`);+ return 0;+ },+ list: () => {+ const ctx = context(io);+ const items = withBoard(ctx, (board) => store.listItems(board, { lane: first, all: values.all }));+ 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)));+ return 0;+ },+ show: () => {+ const ctx = context(io);+ const id = idArg(first);+ const { item, verdicts } = withBoard(ctx, (board) => ({+ item: store.getItem(board, id),+ verdicts: store.verdictsFor(board, id),+ }));+ if (values.json) {+ io.say(JSON.stringify({ ...item, verdicts }, null, 2));+ return 0;+ }+ io.say(itemLine(item));+ if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);+ if (item.item_frozen) {+ const frozen = JSON.parse(item.item_frozen);+ io.say(`frozen at claim (${item.item_frozen_digest.slice(0, 12)}):`);+ frozen.rows.forEach((row) => io.say(` ${row.id}: ${row.text}${row.gate ? ` | gate: ${row.gate}` : ''}`));+ }+ if (item.item_commit) io.say(`submitted by ${item.item_built_by} at ${item.item_commit}`);+ verdicts.forEach((verdict) => io.say(`${verdict.verdict_decision} ${verdict.verdict_reason} by ${verdict.verdict_by} at ${verdict.verdict_commit.slice(0, 12)}${verdict.verdict_note ? `: ${verdict.verdict_note}` : ''}`));+ if (item.item_merged_commit) io.say(`merged as ${item.item_merged_commit}`);+ if (item.item_withdrawn_reason) io.say(`withdrawn: ${item.item_withdrawn_reason}`);+ return 0;+ },+ status: () => {+ const ctx = context(io);+ const summary = withBoard(ctx, (board) => {+ const me = whoAmI(ctx, board);+ const mine = store.listItems(board).filter((item) => item.item_status === 'claimed' && item.item_owner === me.id);+ return { me, mine, stats: store.stats(board), unread: store.unreadCount(board, me.id) };+ });+ if (values.json) {+ io.say(JSON.stringify(summary, null, 2));+ return 0;+ }+ const { items, accepted, rejected } = summary.stats;+ io.say(`${summary.me.id}: ${summary.unread} unread shouts; holding ${summary.mine.map((item) => `#${item.item_id}`).join(', ') || 'nothing'}`);+ io.say(`board: ${items.open} open, ${items.claimed} claimed, ${items.submitted} awaiting verification, ${items.verified} verified, ${items.withdrawn} withdrawn`);+ io.say(`verdicts: ${accepted} accepted, ${rejected} rejected`);+ return 0;+ },+ inbox: () => {+ const ctx = context(io);+ const shouts = withBoard(ctx, (board) => store.inbox(board, whoAmI(ctx, board).id));+ if (!shouts.length) io.say('no new shouts');+ shouts.forEach((shout) => io.say(`${shout.shout_at.slice(0, 16)} ${shout.shout_from} -> ${shout.shout_to}: ${shout.shout_text}`));+ return 0;+ },+ ledger: () => {+ const ctx = context(io);+ const { items, stats } = withBoard(ctx, (board) => ({+ items: store.listItems(board, { all: true }),+ stats: store.stats(board),+ }));+ const built = items.filter((item) => item.item_built_by && item.item_status !== 'withdrawn').reverse();+ const cell = (text) => String(text ?? '').replace(/\|/g, '/').replace(/\s+/g, ' ');+ io.say(`${stats.items.verified} verified by a second agent · ${stats.items.submitted} awaiting verification · ${stats.rejected} rejections along the way`);+ io.say('');+ io.say('| # | Lane | Item | Spec | Built by | Verified by | Commit | Merged |');+ io.say('| --- | --- | --- | --- | --- | --- | --- | --- |');+ for (const item of built) {+ io.say(`| ${item.item_id} | ${item.item_lane} | ${cell(item.item_title)} | ${cell(item.item_spec_ids)} | ${item.item_built_by} | ${item.item_verified_by ?? ''} | ${(item.item_commit ?? '').slice(0, 12)} | ${(item.item_merged_commit ?? '').slice(0, 12)} |`);+ }+ return 0;+ },+ log: () => {+ const ctx = context(io);+ const itemId = first ? idArg(first) : undefined;+ const rows = withBoard(ctx, (board) => store.events(board, { itemId }));+ rows.forEach((event) => io.say(`${event.event_at.slice(0, 19)} ${event.event_by.padEnd(14)} ${event.event_kind.padEnd(9)} ${event.item_id ? `#${event.item_id}` : ''} ${event.event_detail === '{}' ? '' : event.event_detail}`.trimEnd()));+ return 0;+ },+ };+}++/**+ * Submit: a clean tree, nothing untracked, the gate green at HEAD, then the board (V4).+ *+ * The cheap checks run before the gate, so a submit that cannot succeed fails fast.+ *+ * @param {any} ctx+ * @param {number} id+ * @returns {number}+ */+function submitHere(ctx, id) {+ const { root } = ctx.info;+ const me = withBoard(ctx, (board) => {+ const who = whoAmI(ctx, board);+ const item = store.getItem(board, id);+ if (item.item_status !== 'claimed' || item.item_owner !== who.id) {+ throw new Refused('NOT_YOURS', `item #${id} is not claimed by you; claim it first`);+ }+ return who;+ });+ if (!isClean(root)) throw new Refused('DIRTY', 'commit your changes first; the gate must check what you submit');+ const stray = untracked(root);+ if (stray.length) throw new Refused('UNTRACKED', `commit or ignore ${stray.length} untracked file(s), e.g. ${stray[0]}`);+ const commit = headCommit(root);+ if (!commit) throw new Refused('NO_COMMIT', 'nothing committed yet');+ const gate = runGate(root, ctx.config);+ if (!gate.isGreen) throw new Refused('GATE_RED', `the gate is red at ${commit.slice(0, 12)}; fix it, commit, submit again`);+ withBoard(ctx, (board) => store.submit(board, id, { agentId: me.id, commit, tree: headTree(root) ?? '' }));+ ctx.io.say(`submitted #${id} at ${commit.slice(0, 12)}; gate green${gate.isCached ? ' (this tree already passed)' : ''}`);+ ctx.io.say(`next: another agent checks out ${commit.slice(0, 12)} and runs: pullboard verify ${id} accept|reject`);+ return 0;+}++/**+ * Verify from this checkout (V3, V7): the submitted commit must be here, at or under HEAD, and the+ * criterion is re-read from the spec, so a verdict is never given against a moved bar.+ *+ * @param {any} ctx+ * @param {number} id+ * @param {any} args+ * @returns {number}+ */+function verifyHere(ctx, id, { second, values }) {+ const decision = { accept: 'ACCEPT', reject: 'REJECT' }[String(second ?? '').toLowerCase()];+ if (!decision) throw new Refused('USAGE', 'pullboard verify <id> accept, or reject --reason CODE --note "..."');+ const { root } = ctx.info;+ const result = withBoard(ctx, (board) => {+ const me = whoAmI(ctx, board);+ const item = store.getItem(board, id);+ if (item.item_status !== 'submitted') {+ throw new Refused('NOT_SUBMITTED', `item #${id} is ${item.item_status}, not submitted`);+ }+ const head = headCommit(root) ?? '';+ const commit = resolveCommit(root, item.item_commit);+ if (!commit || !contains(root, commit, head)) {+ throw new Refused('NOT_AT_COMMIT', `check out the submitted commit first: git switch --detach ${item.item_commit.slice(0, 12)}`);+ }+ let digest = 'missing';+ try {+ digest = freezer(ctx)(item).digest;+ } catch (error) {+ if (!(error instanceof Refused)) throw error;+ }+ return store.verify(board, id, {+ agentId: me.id,+ decision,+ reason: values.reason,+ note: values.note ?? '',+ head,+ digest,+ policy: ctx.config.verify,+ });+ });+ ctx.io.say(result.decision === 'ACCEPT' ? `verified #${id}: ${result.reason}` : `rejected #${id}: ${result.reason}; it is open again for rework`);+ return 0;+}++/**+ * The commands that change the board.+ *+ * @param {any} io+ * @param {any} args+ * @returns {Record<string, () => number>}+ */+function workCommands(io, args) {+ const { first, second, rest, values } = args;+ const act = (work) => {+ const ctx = context(io);+ return withBoard(ctx, (board) => work(ctx, board, whoAmI(ctx, board)));+ };+ return {+ add: () => act((ctx, board, me) => {+ if (!first || !isLane(ctx.config, first)) throw new Refused('NO_LANE', `no lane "${first ?? ''}"; see: pullboard lanes`);+ const specIds = idList(values.specs);+ const problems = idProblems(loadSpec(ctx.info.root, ctx.config), specIds);+ if (problems.length) throw new Refused('UNKNOWN_SPEC', `${problems.join('; ')}`);+ const parentId = values.parent ? idArg(values.parent, 'a parent item id') : null;+ const title = [second, ...rest].filter(Boolean).join(' ');+ const id = store.addItem(board, { by: me.id, lane: first, title, criterion: values.criterion ?? '', specIds, parentId });+ io.say(`#${id}`);+ return 0;+ }),+ 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) });+ io.say(`${result.renewed ? 'renewed' : 'claimed'} #${first} until ${result.leaseUntil}; criterion frozen as ${result.digest.slice(0, 12)}`);+ return 0;+ }),+ release: () => act((ctx, board, me) => {+ store.release(board, idArg(first), me.id);+ io.say(`released #${first}`);+ return 0;+ }),+ submit: () => submitHere(context(io), idArg(first)),+ done: () => submitHere(context(io), idArg(first)),+ verify: () => verifyHere(context(io), idArg(first), args),+ merged: () => act((ctx, board, me) => {+ const commit = resolveCommit(ctx.info.root, second ?? '');+ if (!commit) throw new Refused('NO_COMMIT', `no commit "${second ?? ''}" in this repo`);+ store.merged(board, idArg(first), { agentId: me.id, commit });+ io.say(`#${first} merged as ${commit.slice(0, 12)}`);+ return 0;+ }),+ withdraw: () => act((ctx, board, me) => {+ store.withdraw(board, idArg(first), { agentId: me.id, reason: [second, ...rest].filter(Boolean).join(' ') });+ io.say(`withdrew #${first}`);+ return 0;+ }),+ refreeze: () => act((ctx, board, me) => {+ const result = store.refreeze(board, idArg(first), { agentId: me.id, freeze: freezer(ctx) });+ io.say(`#${first} refrozen ${String(result.before).slice(0, 12)} -> ${result.after.slice(0, 12)}; open again`);+ return 0;+ }),+ shout: () => act((ctx, board, me) => {+ store.shout(board, { from: me.id, to: first ?? '', text: [second, ...rest].filter(Boolean).join(' '), lanes: laneNames(ctx.config) });+ io.say(`shouted to ${first}`);+ return 0;+ }),+ };+}++/**+ * The spec commands: check, show, unmet, signoff.+ *+ * @param {any} io+ * @param {any} args+ * @returns {number}+ */+function specCommand(io, { first, second, rest, values }) {+ const ctx = context(io);+ const spec = loadSpec(ctx.info.root, ctx.config);+ if (!spec.exists) throw new Refused('NO_SPEC', `no ${ctx.config.spec}; run: pullboard init`);+ if (first === 'check' || first === undefined) {+ const findings = lintSpec(spec);+ findings.forEach((finding) => io.say(`${ctx.config.spec}:${finding.line} ${finding.id ?? ''} ${finding.level}: ${finding.message}`.replace(' ', ' ')));+ const errors = findings.filter((finding) => finding.level === 'error').length;+ io.say(`${spec.rows.length} rows, ${errors} errors, ${findings.length - errors} warnings`);+ return errors ? 1 : 0;+ }+ const signoffs = readSignoffs(ctx.info.root);+ if (first === 'show') {+ const row = spec.rows.find((entry) => entry.id === second);+ if (!row) throw new Refused('NO_ROW', `no row ${second ?? ''} in ${ctx.config.spec}`);+ const standing = standings(spec.rows, signoffs).get(row.id) ?? { met: [], stale: [] };+ io.say(`${row.id} [${row.status}${row.tier ? `, ${row.tier}` : ''}] ${row.text}`);+ if (row.gate) io.say(`gate: ${row.gate}`);+ if (row.serves.length) io.say(`serves: ${row.serves.join(', ')}`);+ io.say(`signed: ${standing.met.map((entry) => `${entry.by} ${entry.on}`).join(', ') || 'no'}${standing.stale.length ? `; stale: ${standing.stale.length}` : ''}`);+ return 0;+ }+ if (first === 'unmet') {+ const rows = unmetRows(spec.rows, signoffs, { mustOnly: values.must });+ rows.forEach((row) => io.say(`${row.id} [${row.tier || 'no tier'}] ${row.text}`));+ io.say(`${rows.length} approved rows without a current sign-off`);+ return 0;+ }+ if (first === 'signoff') {+ const ids = [second, ...rest].filter(Boolean).flatMap((text) => idList(text));+ const count = signOff(ctx.info.root, spec, { ids, by: values.by ?? '', on: new Date().toISOString().slice(0, 10) });+ io.say(`signed ${count} rows as ${values.by}; commit .pullboard/signoffs.jsonl`);+ return 0;+ }+ throw new Refused('USAGE', 'pullboard spec check | show <id> | unmet [--must] | signoff <ids> --by <initials>');+}++/**+ * Read everything git writes on a hook's stdin, or nothing when run by hand.+ *+ * @param {any} stdin+ * @returns {Promise<string>}+ */+async function readStdin(stdin) {+ if (!stdin || stdin.isTTY) return '';+ const chunks = [];+ for await (const chunk of stdin) chunks.push(chunk);+ return Buffer.concat(chunks).toString('utf8');+}++/**+ * The hooks git runs. In a repo without pullboard.json they pass, so a stray hook never blocks.+ *+ * @param {any} io+ * @param {any} args+ * @returns {Promise<number>}+ */+async function hookCommand(io, { first, second }) {+ const info = repoInfo(io.cwd);+ let ctx;+ try {+ ctx = context(io);+ } catch (error) {+ if (error instanceof Refused && error.code === 'NO_CONFIG') return 0;+ throw error;+ }+ let problems = [];+ if (first === 'pre-commit') {+ 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') {+ const message = readFileSync(second ?? '', 'utf8');+ problems = commitMsgProblems(message, { rules: ctx.config.commits, spec: loadSpec(info.root, ctx.config) });+ } else if (first === 'pre-push') {+ problems = prePushProblems(info.root, await readStdin(io.stdin));+ if (!problems.length) {+ const gate = runGate(info.root, ctx.config);+ if (gate.isCached) io.say('pre-push: the gate passed on this exact tree; not running it twice');+ if (!gate.isGreen) problems = ['the gate is red; fix it before pushing'];+ }+ } else {+ throw new Refused('USAGE', 'pullboard hook pre-commit | commit-msg <file> | pre-push');+ }+ if (!problems.length) return 0;+ io.err(`pullboard ${first}: blocked\n${problems.map((problem) => ` - ${problem}`).join('\n')}`);+ return 1;+}++/**+ * Run one command. Returns the exit code: 0 done, 1 refused, 2 usage.+ *+ * @param {string[]} argv+ * @param {{ cwd: string, stdout: any, stderr: any, stdin?: any, clock?: any }} streams+ * @returns {Promise<number>}+ */+export async function main(argv, streams) {+ const io = {+ ...streams,+ say: (line) => streams.stdout.write(`${line}\n`),+ err: (line) => streams.stderr.write(`${line}\n`),+ };+ let parsed;+ try {+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });+ } catch (error) {+ io.err(`pullboard: ${error.message}\n\n${HELP}`);+ return 2;+ }+ const { values, positionals } = parsed;+ const [command = '', first, second, ...rest] = positionals;+ if (values.version || command === 'version') {+ io.say(VERSION);+ return 0;+ }+ if (values.help || !command || command === 'help') {+ io.say(HELP);+ return 0;+ }+ const args = { first, second, rest, values };+ try {+ if (command === 'spec') return specCommand(io, args);+ if (command === 'hook') return await hookCommand(io, args);+ if (command === 'gate') {+ const ctx = context(io);+ const gate = runGate(ctx.info.root, ctx.config);+ io.say(gate.isGreen ? `gate green${gate.isCached ? ' (this tree already passed)' : ''}` : 'gate red');+ return gate.isGreen ? 0 : 1;+ }+ const commands = { ...setupCommands(io, args), ...readCommands(io, args), ...workCommands(io, args) };+ const run = commands[command];+ if (!run) {+ io.err(`pullboard: no command "${command}"\n\n${HELP}`);+ return 2;+ }+ return run();+ } catch (error) {+ if (error instanceof Refused) {+ io.err(`pullboard: ${error.message}`);+ return 1;+ }+ throw error;+ }+}diff --git a/src/index.js b/src/index.jsnew file mode 100644index 00000000..6b7d0bec--- /dev/null+++ b/src/index.js@@ -0,0 +1,11 @@+/**+ * The library surface, for tools that drive pullboard without the CLI: the board, the spec, the+ * lanes and the hooks, each usable on its own.+ */+export * as board from './board.js';+export { loadConfig, defaults as defaultConfig } from './config.js';+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 { main } from './cli.js';diff --git a/src/init.js b/src/init.jsnew file mode 100644index 00000000..468dc1a5--- /dev/null+++ b/src/init.js@@ -0,0 +1,102 @@+/**+ * `pullboard init` (I1, I2): one command puts the method into a repo. It writes the config, a+ * starter spec and the agent instructions, installs the git hooks, opens the board and registers+ * the main checkout as the coordinator. It runs again safely and never overwrites a file it did not+ * write.+ */+import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';+import { basename, join } from 'node:path';+import { CONFIG_FILE, COORDINATOR } from './config.js';+import { installHooks } from './hooks.js';+import { Refused } from './refused.js';+import { AGENTS_START, agentsBlock, configTemplate, specTemplate } from './templates.js';++const NPM_DEFAULT_TEST = 'echo "Error: no test specified" && exit 1';++/**+ * The gate to start with: `npm test` when the repo has a real test script, otherwise none yet.+ *+ * @param {string} root+ * @returns {string}+ */+export function detectGate(root) {+ const file = join(root, 'package.json');+ if (!existsSync(file)) return '';+ try {+ const test = JSON.parse(readFileSync(file, 'utf8'))?.scripts?.test;+ return typeof test === 'string' && test.trim() && test !== NPM_DEFAULT_TEST ? 'npm test' : '';+ } catch {+ return '';+ }+}++/**+ * Write a file only when it does not exist yet.+ *+ * @param {string} file+ * @param {string} text+ * @param {string} name+ * @returns {string} What happened.+ */+function writeNew(file, text, name) {+ if (existsSync(file)) return `kept ${name}`;+ writeFileSync(file, text);+ return `wrote ${name}`;+}++/**+ * Put the agent instructions in AGENTS.md, appending pullboard's block to a file the repo already+ * has, and point CLAUDE.md at AGENTS.md so Claude Code reads the same rules.+ *+ * @param {string} root+ * @returns {string[]}+ */+function writeAgentDocs(root) {+ const notes = [];+ const agents = join(root, 'AGENTS.md');+ if (!existsSync(agents)) {+ writeFileSync(agents, `# AGENTS.md\n\n${agentsBlock()}`);+ notes.push('wrote AGENTS.md');+ } else if (!readFileSync(agents, 'utf8').includes(AGENTS_START)) {+ appendFileSync(agents, `\n${agentsBlock()}`);+ notes.push('added the pullboard section to AGENTS.md');+ } else notes.push('kept AGENTS.md');+ const claude = join(root, 'CLAUDE.md');+ if (!existsSync(claude)) {+ writeFileSync(claude, '@AGENTS.md\n');+ notes.push('wrote CLAUDE.md (points at AGENTS.md)');+ } else if (!readFileSync(claude, 'utf8').includes('AGENTS.md')) {+ appendFileSync(claude, '\[email protected]\n');+ notes.push('pointed CLAUDE.md at AGENTS.md');+ }+ return notes;+}++/**+ * Set the repo up. Must run in the main checkout, which becomes the coordinator.+ *+ * @param {{ info: { root: string, isMain: boolean }, openBoardHere: () => any, register: Function, closeBoard: Function }} context+ * @returns {string[]} What happened, one line each.+ */+export function initRepo({ info, openBoardHere, register, closeBoard }) {+ if (!info.isMain) {+ throw new Refused('NOT_MAIN', 'run init in the main checkout; worktrees join a lane instead');+ }+ const { root } = info;+ const gate = detectGate(root);+ const notes = [+ writeNew(join(root, CONFIG_FILE), configTemplate(gate), CONFIG_FILE),+ writeNew(join(root, 'SPEC.md'), specTemplate(basename(root)), 'SPEC.md'),+ ...writeAgentDocs(root),+ ...installHooks(root),+ ];+ const board = openBoardHere();+ try {+ register(board, { lane: COORDINATOR, path: root });+ } finally {+ closeBoard(board);+ }+ notes.push('opened the board in the git dir; this checkout is the coordinator');+ if (!gate) notes.push('no gate yet: set "gate" in pullboard.json to the command that proves the build');+ return notes;+}diff --git a/src/templates.js b/src/templates.jsnew file mode 100644index 00000000..914d39aa--- /dev/null+++ b/src/templates.js@@ -0,0 +1,80 @@+/**+ * What `pullboard init` writes into a repo: the config, a starter spec, and the agent instructions+ * every coding agent reads (AGENTS.md, which CLAUDE.md points at).+ */++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.+ *+ * @param {string} gate+ * @returns {string}+ */+export function configTemplate(gate) {+ const config = {+ gate,+ spec: 'SPEC.md',+ verify: 'any',+ lease: '2h',+ lanes: {},+ shared: [],+ commits: { requireIds: ['feat', 'fix'] },+ };+ return `${JSON.stringify(config, null, 2)}\n`;+}++/**+ * A starter SPEC.md with the row format shown by example.+ *+ * @param {string} project+ * @returns {string}+ */+export function specTemplate(project) {+ return `# ${project} spec++Every requirement is a row with an id. Agents build against approved rows; commits cite the ids they serve. \`pullboard spec check\` lints this file.++Statuses: approved = decided · draft = proposed · pending = open question · fact = true today · retired = spent, never reused. Tiers: must · aim.++## G · Goals: what the client asked for+- G1 [draft, must] Replace with the first thing the client needs, in one line. | gate: the test that proves it++## K · Constraints+- K1 [draft, must] Replace with a constraint, e.g. runs locally with no account. | gate: review+`;+}++/**+ * The agent instructions, between markers so init can find its own block and never touch the rest.+ *+ * @returns {string}+ */+export function agentsBlock() {+ return `${AGENTS_START}+## Working here: pullboard++This repo runs on pullboard: a work board, lanes and a spec that live in git. Nothing ships until a second agent verifies it.++**Source of truth.** \`SPEC.md\` holds every requirement as a row with an id, like \`G1.2\`. Code follows the spec. Commits cite the ids they serve: \`feat(scope): subject [G1.2]\`. Only a person approves or changes an approved row.++**Who you are.** An agent is its worktree. The main checkout is the coordinator. Every other agent works in its own worktree and joins one lane:++ git worktree add ../<repo>-<lane> -b <lane>/<slug>+ cd ../<repo>-<lane> && pullboard join <lane>++**The loop.**+1. \`pullboard inbox\`, then \`pullboard list <lane>\`.+2. \`pullboard claim <id>\`. A claim is a 2-hour lease; claim again to renew. The criterion freezes now: \`pullboard show <id>\` is the bar your work is judged against.+3. 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: it checks out the submitted commit and runs \`pullboard verify <id> accept\`, 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.++**Talk.** \`pullboard shout <lane|agent|all> "<text>"\`. Read \`pullboard inbox\` before you start and after you submit.++**Never.** Bypass a hook with \`--no-verify\`. Edit the board's database. Verify your own work. Change an approved spec row without the person's OK.+${AGENTS_END}+`;+}