Skip to content

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.

feat(core): export and import boards [A7]

Corey Olson9ddad6adc307
diff --git a/src/cli.js b/src/cli.js
index c8667a9d..f162fd3c 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -45,6 +45,7 @@ import { tour } from './tour.js';
import { forgetProject, registerProject } from './projects.js';
import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
import { serveView } from './serve.js';
+import { exportBoard, importBoard } from './exchange.js';
const PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
export const VERSION = PACKAGE.version;
@@ -96,6 +97,8 @@ Work
pullboard shout <to> <text> --evidence attempt|receipt --outcome <word> --item <id> --commit <rev>
pullboard answer <shout-id> <text> answer a shout that asked for a decision
pullboard decisions shouts still waiting for a decision
+ pullboard export print the whole board as versioned JSON
+ pullboard import <file> restore a versioned export into an empty board
Coordinator
pullboard sweep --run "<checker>" --check "<checker on {file}>" [--route light] [--max 20] [--dry-run]
@@ -779,8 +782,30 @@ function refuseUncommittedSetup(mainRoot, config) {
* @param {any} args
* @returns {Record<string, () => number>}
*/
-function readCommands(io, { first, values }) {
+function readCommands(io, { first, second, rest, values }) {
return {
+ export: () => {
+ if (first) throw new Refused('USAGE', 'pullboard export takes no arguments');
+ const ctx = context(io);
+ io.say(JSON.stringify(withBoard(ctx, (board) => exportBoard(board)), null, 2));
+ return 0;
+ },
+ import: () => {
+ if (!first || second || rest.length) throw new Refused('USAGE', 'pullboard import <file>');
+ const file = resolve(io.cwd, first);
+ if (!existsSync(file)) throw new Refused('NO_FILE', `no export file ${first}`);
+ let document;
+ try {
+ document = JSON.parse(readFileSync(file, 'utf8'));
+ } catch {
+ throw new Refused('IMPORT_FORMAT', `file ${first} is not a JSON export; use pullboard export to make one`);
+ }
+ const ctx = context(io);
+ const imported = withBoard(ctx, (board) => importBoard(board, document));
+ if (typeof io.result === 'function') io.result({ tables: imported.tables });
+ else io.say(`imported version ${document.version} board tables: ${imported.tables.join(', ')}`);
+ return 0;
+ },
resume: () => resumeHere(io),
whoami: () => {
const ctx = context(io);
diff --git a/src/exchange.js b/src/exchange.js
new file mode 100644
index 00000000..735637b0
--- /dev/null
+++ b/src/exchange.js
@@ -0,0 +1,117 @@
+/**
+ * Export and import whole board files (A7), including their AUTOINCREMENT counters, so a copy can
+ * continue producing the same ids after its rows are restored.
+ */
+import { Refused } from './refused.js';
+import { storeTriggers } from './machine.js';
+
+const VERSION = 1;
+
+/**
+ * Quote a SQLite identifier read from the database or a validated document.
+ * @param {string} name
+ * @returns {string}
+ */
+const identifier = (name) => `"${name.replaceAll('"', '""')}"`;
+
+/**
+ * Names of the board's data tables, with sqlite_sequence last so imported counters remain exact.
+ * @param {any} db
+ * @returns {string[]}
+ */
+function tableNames(db) {
+ const names = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(({ name }) => name);
+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_sequence'").get()) names.push('sqlite_sequence');
+ return names;
+}
+
+/**
+ * The columns in a board table, in their declared order.
+ * @param {any} db
+ * @param {string} table
+ * @returns {string[]}
+ */
+function columnsOf(db, table) {
+ return db.prepare(`PRAGMA table_info(${identifier(table)})`).all().map(({ name }) => name);
+}
+
+/**
+ * Capture every board table and row in the stable v1 document format.
+ * @param {{ db: any }} board
+ * @returns {{ version: number, tables: Record<string, any[]> }}
+ */
+export function exportBoard(board) {
+ const tables = Object.fromEntries(tableNames(board.db).map((table) => [
+ table,
+ board.db.prepare(`SELECT * FROM ${identifier(table)} ORDER BY ${table === 'sqlite_sequence' ? 'name' : 'rowid'}`).all(),
+ ]));
+ return { version: VERSION, tables };
+}
+
+/**
+ * Validate the document shape against the open board's schema before changing any rows.
+ * @param {any} db
+ * @param {any} document
+ * @param {string[]} names
+ */
+function validateDocument(db, document, names) {
+ if (!document || typeof document !== 'object' || Array.isArray(document) || document.version !== VERSION) {
+ throw new Refused('IMPORT_VERSION', `expected board export version ${VERSION}; export it again with this pullboard version`);
+ }
+ if (!document.tables || typeof document.tables !== 'object' || Array.isArray(document.tables)) {
+ throw new Refused('IMPORT_FORMAT', 'the export needs a tables object; use pullboard export to make one');
+ }
+ const supplied = Object.keys(document.tables).sort();
+ const expected = [...names].sort();
+ if (JSON.stringify(supplied) !== JSON.stringify(expected)) {
+ throw new Refused('IMPORT_SCHEMA', `the export tables do not match this board; export and import with the same pullboard version`);
+ }
+ for (const table of names) {
+ const columns = columnsOf(db, table);
+ const rows = document.tables[table];
+ if (!Array.isArray(rows)) throw new Refused('IMPORT_FORMAT', `table ${table} must contain an array of rows; export it again`);
+ for (const row of rows) {
+ if (!row || typeof row !== 'object' || Array.isArray(row) || JSON.stringify(Object.keys(row).sort()) !== JSON.stringify([...columns].sort())) {
+ throw new Refused('IMPORT_SCHEMA', `a ${table} row does not have exactly its board columns; export it again`);
+ }
+ }
+ }
+}
+
+/**
+ * Restore a v1 export only into an empty board, atomically, while briefly allowing historical item
+ * states to be inserted before restoring the board's declared lifecycle triggers.
+ * @param {{ db: any }} board
+ * @param {any} document
+ * @returns {{ tables: string[] }}
+ */
+export function importBoard(board, document) {
+ const db = board.db;
+ const names = tableNames(db);
+ validateDocument(db, document, names);
+ db.exec('PRAGMA defer_foreign_keys = ON; BEGIN IMMEDIATE');
+ try {
+ const occupied = names.filter((table) => db.prepare(`SELECT 1 FROM ${identifier(table)} LIMIT 1`).get());
+ if (occupied.length) {
+ throw new Refused('IMPORT_NOT_EMPTY', `board tables already have rows (${occupied.join(', ')}); import into a repo with an empty board`);
+ }
+ const triggers = db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name LIKE 'machine_%'").all();
+ for (const { name } of triggers) db.exec(`DROP TRIGGER ${identifier(name)}`);
+ for (const table of names.filter((name) => name !== 'sqlite_sequence')) {
+ const columns = columnsOf(db, table);
+ const sql = `INSERT INTO ${identifier(table)} (${columns.map(identifier).join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;
+ const insert = db.prepare(sql);
+ for (const row of document.tables[table]) insert.run(...columns.map((column) => row[column]));
+ }
+ const setSequence = db.prepare('UPDATE sqlite_sequence SET seq = ? WHERE name = ?');
+ for (const row of document.tables.sqlite_sequence ?? []) {
+ if (!setSequence.run(row.seq, row.name).changes) db.prepare('INSERT INTO sqlite_sequence (name, seq) VALUES (?, ?)').run(row.name, row.seq);
+ }
+ for (const { name, sql } of storeTriggers()) db.exec(sql);
+ db.exec('COMMIT');
+ return { tables: names };
+ } catch (error) {
+ db.exec('ROLLBACK');
+ throw error;
+ }
+}
diff --git a/test/exchange.test.js b/test/exchange.test.js
new file mode 100644
index 00000000..5ecf5b19
--- /dev/null
+++ b/test/exchange.test.js
@@ -0,0 +1,157 @@
+/**
+ * The v1 board exchange keeps each SQLite row, including lifecycle history and sequence counters.
+ */
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { main } from '../src/cli.js';
+import { exportBoard, importBoard } from '../src/exchange.js';
+
+const SHA = 'a'.repeat(40);
+/** The deterministic frozen criterion used by the fixture. */
+const FREEZE = (item) => ({ text: item.item_title, digest: `digest:${item.item_title}` });
+
+/**
+ * Make a real board file with every item state, both verdict outcomes, decision and evidence shouts,
+ * registered agents, an event history and a held lane.
+ * @param {string} file
+ * @returns {any}
+ */
+function populatedBoard(file) {
+ const board = store.openBoard(file);
+ store.register(board, { lane: 'coordinator', path: '/source' });
+ for (let index = 1; index <= 5; index += 1) store.register(board, { lane: 'web', path: `/source/web-${index}` });
+ /** Add one open item before driving it into a lifecycle state. */
+ const add = (title) => store.addItem(board, { by: 'coordinator', lane: 'web', title });
+ const open = add('open');
+ const claimed = add('claimed');
+ store.claim(board, claimed, { agentId: 'web-1', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });
+ const submitted = add('submitted');
+ store.claim(board, submitted, { agentId: 'web-2', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });
+ store.submit(board, submitted, { agentId: 'web-2', commit: SHA, tree: 'tree:submitted' });
+ const verified = add('verified');
+ store.claim(board, verified, { agentId: 'web-3', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });
+ store.submit(board, verified, { agentId: 'web-3', commit: SHA, tree: 'tree:verified' });
+ store.verify(board, verified, { agentId: 'web-4', decision: 'ACCEPT', note: 'removed the proof; its test failed', head: SHA, digest: `digest:verified`, policy: 'any' });
+ const rejected = add('rejected then reopened');
+ store.claim(board, rejected, { agentId: 'web-5', lane: 'web', leaseMs: 3_600_000, freeze: FREEZE });
+ store.submit(board, rejected, { agentId: 'web-5', commit: SHA, tree: 'tree:rejected' });
+ store.verify(board, rejected, { agentId: 'web-2', decision: 'REJECT', reason: 'TEST_FAILURE', note: 'the check fails', head: SHA, digest: `digest:rejected then reopened`, policy: 'any' });
+ const withdrawn = add('withdrawn');
+ store.withdraw(board, withdrawn, { agentId: 'coordinator', reason: 'no longer needed' });
+ store.shout(board, { from: 'coordinator', to: 'web', text: 'Should this ship?', lanes: ['web'], decision: true });
+ store.shout(board, { from: 'web-1', to: 'coordinator', text: 'Tried the edge case', lanes: [], evidence: { kind: 'attempt', outcome: 'passed after fix', item: open, commit: SHA } });
+ store.holdLane(board, 'web', { agentId: 'coordinator', reason: 'freeze the board for export' });
+ return board;
+}
+
+/**
+ * Create a disposable directory removed after a test finishes.
+ * @returns {string}
+ */
+const tempDirectory = () => mkdtempSync(join(tmpdir(), 'pullboard-exchange-'));
+
+/**
+ * Create an isolated real git repo with the smallest valid Pullboard config.
+ * @param {string} root
+ */
+function gitRepo(root) {
+ mkdirSync(root);
+ const result = spawnSync('git', ['init', '-q'], { cwd: root, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ lanes: {} }));
+}
+
+test('round trips every board row, state, history and AUTOINCREMENT counter [A7]', () => {
+ const directory = tempDirectory();
+ const source = populatedBoard(join(directory, 'source.sqlite'));
+ const target = store.openBoard(join(directory, 'target.sqlite'));
+ try {
+ const document = exportBoard(source);
+ const result = importBoard(target, document);
+ assert.deepEqual(result.tables, Object.keys(document.tables));
+ assert.deepEqual(exportBoard(target), document);
+ assert.deepEqual(document.tables.item.map((row) => row.item_status).sort(), ['claimed', 'open', 'open', 'submitted', 'verified', 'withdrawn']);
+ assert.ok(document.tables.verdict.some((row) => row.verdict_decision === 'ACCEPT'));
+ assert.ok(document.tables.verdict.some((row) => row.verdict_decision === 'REJECT'));
+ assert.ok(document.tables.shout.some((row) => row.shout_decision === 1));
+ assert.ok(document.tables.shout.some((row) => row.shout_evidence_kind === 'attempt'));
+ const previousSequence = document.tables.sqlite_sequence.find((row) => row.name === 'item').seq;
+ const next = store.addItem(target, { by: 'coordinator', lane: 'web', title: 'next id' });
+ assert.equal(next, previousSequence + 1);
+ } finally {
+ store.closeBoard(source);
+ store.closeBoard(target);
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test('import refuses a board with rows and leaves it unchanged [A7]', () => {
+ const directory = tempDirectory();
+ const source = populatedBoard(join(directory, 'source.sqlite'));
+ const target = store.openBoard(join(directory, 'target.sqlite'));
+ try {
+ store.register(target, { lane: 'coordinator', path: '/target' });
+ const before = exportBoard(target);
+ assert.throws(() => importBoard(target, exportBoard(source)), /IMPORT_NOT_EMPTY.*empty board/);
+ assert.deepEqual(exportBoard(target), before);
+ } finally {
+ store.closeBoard(source);
+ store.closeBoard(target);
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test('import refuses an export from another version before writing [A7]', () => {
+ const directory = tempDirectory();
+ const source = populatedBoard(join(directory, 'source.sqlite'));
+ const target = store.openBoard(join(directory, 'target.sqlite'));
+ try {
+ const document = exportBoard(source);
+ document.version = 2;
+ assert.throws(() => importBoard(target, document), /IMPORT_VERSION.*version 1/);
+ const empty = store.openBoard(':memory:');
+ try {
+ assert.deepEqual(exportBoard(target), exportBoard(empty));
+ } finally {
+ store.closeBoard(empty);
+ }
+ } finally {
+ store.closeBoard(source);
+ store.closeBoard(target);
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+test('export and import CLI commands exchange a versioned document between real repos [A7]', async () => {
+ const directory = tempDirectory();
+ const sourceRoot = join(directory, 'source');
+ const targetRoot = join(directory, 'target');
+ gitRepo(sourceRoot);
+ gitRepo(targetRoot);
+ const source = store.openBoard(join(sourceRoot, '.git', 'pullboard', 'board.sqlite'));
+ store.register(source, { lane: 'coordinator', path: sourceRoot });
+ store.closeBoard(source);
+ let exported = '';
+ let errors = '';
+ const streams = (cwd) => ({ cwd, stdout: { write: (text) => { exported += text; } }, stderr: { write: (text) => { errors += text; } } });
+ try {
+ assert.equal(await main(['export'], streams(sourceRoot)), 0, errors);
+ const document = JSON.parse(exported);
+ writeFileSync(join(directory, 'board.json'), JSON.stringify(document));
+ exported = '';
+ assert.equal(await main(['import', join(directory, 'board.json')], streams(targetRoot)), 0, errors);
+ const imported = store.openBoard(join(targetRoot, '.git', 'pullboard', 'board.sqlite'));
+ try {
+ assert.deepEqual(JSON.parse(JSON.stringify(exportBoard(imported))), document);
+ } finally {
+ store.closeBoard(imported);
+ }
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});