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(digest): pullboard digest writes a readable briefing [A2,N26]

Corey Olson25ef1135e786
diff --git a/docs/api.md b/docs/api.md
index 6d09e627..2f3d2477 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -119,6 +119,7 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec
| `prompt` | `version:number`, `role:string`, `text:string` |
| `gate` | `version:number`, `green:boolean`, `report:string` |
| `export` | `version:number`, `tables:object` |
+| `digest` | `version:number`, `markdown:string`, `bytes:number`, `sequence:number`, `sections:array` |
| `import` | `version:number`, `tables:array` |
| `spec` | `version:number`, `rows:array` |
| `spec check` | `version:number`, `rows:array` |
diff --git a/src/cli.js b/src/cli.js
index ccf54309..18eb0342 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -87,6 +87,7 @@ import { proofStats } from './stats.js';
import { flowLines, flowAlertLine } from './stats-flow.js';
import { releaseHeadlinesBetween } from './changelog.js';
import { exportBoard, importBoard } from './exchange.js';
+import { digestCommand } from './digest.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
import { addRunner, browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, memoryFloorMB, setBrowserSlots, setGateSlots } from './settings.js';
import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';
@@ -253,6 +254,7 @@ const OPTIONS = {
by: { type: 'string' },
key: { type: 'string' },
out: { type: 'string' },
+ watch: { type: 'boolean' },
after: { type: 'string' },
brief: { type: 'string' },
'brief-file': { type: 'string' },
@@ -1951,6 +1953,8 @@ function readCommands(io, { first, second, rest, values }) {
io.say(JSON.stringify(withBoard(ctx, (board) => exportBoard(board)), null, 2));
return 0;
},
+ // A read-only briefing of this board only; it opens the board file read-only (src/digest.js).
+ digest: () => digestCommand(io, { first, second, rest, values }, context(io)),
import: () => {
if (!first || second || rest.length) throw new Refused('USAGE', 'pullboard import <file>');
const file = resolve(io.cwd, first);
@@ -4001,7 +4005,7 @@ async function runMain(argv, streams) {
positionals: parsed.positionals.slice(1),
values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };
sync = Boolean(command) && !parsed.values.help && !parsed.values.version
- && !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp'].includes(command)
+ && !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp', 'digest'].includes(command)
// A coordinator declaration on a linked clone must refuse before auto-link or relay sync.
&& !(command === 'join' && parsed.positionals[1] === COORDINATOR);
needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');
diff --git a/src/digest.js b/src/digest.js
new file mode 100644
index 00000000..feec5491
--- /dev/null
+++ b/src/digest.js
@@ -0,0 +1,337 @@
+/**
+ * `pullboard digest`: a short Markdown briefing of one board, for a person or a chat assistant
+ * that can read the repo but never the board [A2,N26].
+ *
+ * Why read-only SQLite and not the board API: the digest must never change the board, so it opens
+ * the file read-only and never migrates, syncs or resolves another registered board.
+ */
+import { randomUUID } from 'node:crypto';
+import { closeSync, existsSync, fsyncSync, openSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+import { setTimeout as pause } from 'node:timers/promises';
+import { milestones, openBoardReadOnly } from './board.js';
+import { secretsIn } from './hooks.js';
+import { Refused } from './refused.js';
+
+/** The briefing stays under 50 KB, counted in UTF-8 bytes. */
+export const DIGEST_MAX_BYTES = 50_000;
+/** How many rows each section reads before its byte budget decides how many it shows. */
+const ROW_LIMIT = 200;
+/** Fact kinds that record a judgement and its reason. */
+const JUDGEMENTS = ['decision', 'rejection', 'root-cause', 'supersession'];
+/** Plain words for verdict reasons, keeping the code beside them for agents. */
+const REASONS = {
+ TEST_FAILURE: 'a test failed', BEHAVIOR_MISMATCH: 'the behavior differs from the bar', INSUFFICIENT_EVIDENCE: 'too little evidence',
+ STALE_HEAD: 'the commit was out of date', CRITERION_MET: 'it meets its bar', OTHER: 'another reason',
+};
+
+/**
+ * Board text as one safe Markdown line: any line that matches Pullboard's secret patterns is
+ * redacted before the text is shortened, so a cut can never expose part of a secret.
+ *
+ * @param {unknown} value
+ * @param {number} limit UTF-8 bytes
+ * @param {{ count: number }} cut counts shortened fields for the left-out section
+ * @returns {string}
+ */
+function line(value, limit, cut) {
+ const lines = String(value ?? '').split(/\r?\n/u)
+ .map((text) => (secretsIn([{ path: 'digest', line: 1, text }]).length ? '[redacted secret]' : text));
+ let text = lines.join('\n');
+ // A multi-line secret, such as a private key block, is caught on the joined text.
+ if (secretsIn([{ path: 'digest', line: 1, text }]).length) text = '[redacted secret]';
+ text = text.replace(/[\u0000-\u001f\u007f]/gu, ' ').replace(/\s+/gu, ' ').trim();
+ if (Buffer.byteLength(text) <= limit) return text;
+ cut.count += 1;
+ let kept = text.slice(0, limit);
+ while (Buffer.byteLength(kept) > limit - 4) kept = kept.slice(0, -1);
+ return `${kept.replace(/[\uD800-\uDBFF]$/u, '')} …`;
+}
+
+/**
+ * One section: its heading, as many entries as fit its byte budget, and a closing line naming how
+ * many were left out. The counts also go to the final left-out section and the JSON result.
+ *
+ * @param {string} title
+ * @param {string[]} entries newest or most important first
+ * @param {number} total every matching row on the board, shown or not
+ * @param {number} budget UTF-8 bytes for the whole section
+ * @param {string} empty what the section says when the board has none
+ */
+function section(title, entries, total, budget, empty) {
+ let text = `## ${title}\n\n`;
+ let shown = 0;
+ for (const entry of entries) {
+ if (Buffer.byteLength(text) + Buffer.byteLength(entry) + 80 > budget) break;
+ text += `${entry}\n`;
+ shown += 1;
+ }
+ if (!total) text += `${empty}\n`;
+ else if (shown < total) text += `${shown ? '\n' : ''}${total - shown} more left out to keep this briefing short.\n`;
+ return { title, shown, total, text: `${text}\n` };
+}
+
+/**
+ * Read one consistent snapshot of the board at `file` and render the briefing.
+ *
+ * @param {string} file the board's SQLite file
+ * @param {{ name?: string, now?: Date }} [options]
+ * @returns {{ markdown: string, sequence: number, sections: { title: string, shown: number, total: number }[], bytes: number }}
+ */
+export function readDigest(file, { name = 'this project', now = new Date() } = {}) {
+ if (!existsSync(file)) throw new Refused('NO_BOARD', 'this repository has no board yet; run pullboard init in the main checkout first');
+ const db = openBoardReadOnly(file);
+ try {
+ db.exec('BEGIN DEFERRED');
+ const result = render(db, { name, now });
+ db.exec('COMMIT');
+ return result;
+ } finally { db.close(); }
+}
+
+/**
+ * Render the briefing from an open read-only connection inside one read transaction.
+ *
+ * @param {any} db
+ * @param {{ name: string, now: Date }} options
+ */
+function render(db, { name, now }) {
+ const cut = { count: 0 };
+ const at = now.toISOString();
+ /** One field of board text, bounded. */
+ const text = (value, limit = 1_200) => line(value, limit, cut);
+ const all = db.prepare('SELECT * FROM item ORDER BY item_id').all();
+ /** An item's state as its reader means it: an expired claim is open again. */
+ const state = (item) => (item.item_status === 'claimed' && (item.item_lease_until ?? '') <= at ? 'open' : item.item_status);
+ const items = new Map(all.map((item) => [item.item_id, { ...item, state: state(item) }]));
+ /** An item named by its title, with its number for pullboard show. */
+ const label = (id) => {
+ const item = items.get(id);
+ return item ? `${text(item.item_title, 240)} (#${id})` : `an item this board no longer has (#${id})`;
+ };
+ const laneHolds = new Map(db.prepare('SELECT hold_lane, hold_reason FROM hold').all().map((row) => [row.hold_lane, row.hold_reason]));
+ const open = [];
+ const blocked = [];
+ const review = [];
+ for (const item of [...items.values()].sort((a, b) => b.item_updated_at.localeCompare(a.item_updated_at) || b.item_id - a.item_id)) {
+ if (item.state === 'submitted') { review.push(item); continue; }
+ if (!['open', 'claimed'].includes(item.state)) continue;
+ const waits = String(item.item_after ?? '').split(',').filter(Boolean).map(Number).filter((id) => items.get(id)?.state !== 'verified');
+ const hold = item.item_hold_reason || laneHolds.get(item.item_lane);
+ (hold || waits.length ? blocked : open).push({ ...item, waits, hold });
+ }
+ /** One open or blocked item with its bar, who holds it, and what it waits on. */
+ const work = (item) => {
+ const who = item.state === 'claimed' && item.item_owner ? `claimed by ${text(item.item_owner, 80)}` : 'open to claim';
+ const lines = [`- ${label(item.item_id)}, in the ${text(item.item_lane, 60)} lane: ${who}.`,
+ ` Done when: ${text(item.item_criterion || 'no bar is written yet.', 500)}`];
+ if (item.hold) lines.push(` Held: ${text(item.hold, 400)}`);
+ if (item.waits.length) lines.push(` Waits for: ${item.waits.slice(0, 6).map(label).join('; ')}${item.waits.length > 6 ? `; and ${item.waits.length - 6} more` : ''}.`);
+ return lines.join('\n');
+ };
+ const landed = all.filter((item) => item.item_status === 'verified' && item.item_merged_commit).length;
+ const accepted = all.filter((item) => item.item_status === 'verified' && !item.item_merged_commit).length;
+
+ const judged = `event_kind = 'row_decision' OR (event_kind = 'fact' AND json_valid(event_detail) AND json_extract(event_detail, '$.kind') IN (${JUDGEMENTS.map(() => '?').join(', ')}))`;
+ const facts = db.prepare(`SELECT * FROM event WHERE ${judged} ORDER BY event_id DESC LIMIT ?`).all(...JUDGEMENTS, ROW_LIMIT);
+ const answered = 'FROM shout reply JOIN shout ask ON ask.shout_id = reply.shout_answers WHERE ask.shout_decision = 1';
+ const answers = db.prepare(`SELECT reply.*, ask.shout_text AS question, ask.shout_from AS asker ${answered} ORDER BY reply.shout_id DESC LIMIT ?`).all(ROW_LIMIT);
+ const decisions = [
+ ...facts.map((row) => {
+ const detail = JSON.parse(row.event_detail);
+ if (row.event_kind === 'row_decision') {
+ const record = detail.record ?? {};
+ const verb = record.decision === 'approve' ? 'approved' : 'declined';
+ return { at: row.event_at, entry: `- ${text(row.event_by, 80)} ${verb} the ${text(record.kind, 20)} row ${text(record.id, 40)}, ${text(row.event_at, 40)}: ${text(record.text, 600)}${record.reason ? `\n Reason: ${text(record.reason, 600)}` : ''}` };
+ }
+ return { at: row.event_at, entry: `- A ${text(detail.kind, 20)} on ${label(row.item_id)} by ${text(row.event_by, 80)}, ${text(row.event_at, 40)}:\n ${text(detail.text, 500)}` };
+ }),
+ ...answers.map((row) => ({ at: row.shout_at, entry: `- ${text(row.shout_from, 80)} answered ${text(row.asker, 80)}, ${text(row.shout_at, 40)}.\n Asked: ${text(row.question, 600)}\n Answer and reason: ${text(row.shout_text, 500)}` })),
+ ].sort((a, b) => String(b.at).localeCompare(String(a.at)));
+ const decisionTotal = Number(db.prepare(`SELECT count(*) AS n FROM event WHERE ${judged}`).get(...JUDGEMENTS).n)
+ + Number(db.prepare(`SELECT count(*) AS n ${answered}`).get().n);
+
+ const verdicts = db.prepare('SELECT * FROM verdict ORDER BY verdict_id DESC LIMIT ?').all(ROW_LIMIT).map((row) => {
+ const verb = row.verdict_decision === 'ACCEPT' ? 'accepted' : 'rejected';
+ const why = REASONS[row.verdict_reason] ? `${REASONS[row.verdict_reason]} (${row.verdict_reason})` : text(row.verdict_reason, 80);
+ return `- ${label(row.item_id)} was ${verb} by ${text(row.verdict_by, 80)}, ${text(row.verdict_at, 40)}: ${why}.${row.verdict_note ? `\n Note: ${text(row.verdict_note, 300)}` : ''}`;
+ });
+ const waiting = "FROM shout ask WHERE ask.shout_to = 'person' AND ask.shout_decision = 1 AND NOT EXISTS (SELECT 1 FROM shout reply WHERE reply.shout_answers = ask.shout_id)";
+ const questions = db.prepare(`SELECT ask.* ${waiting} ORDER BY ask.shout_id LIMIT ?`).all(ROW_LIMIT).map((row) =>
+ `- ${text(row.shout_from, 80)} asks, ${text(row.shout_at, 40)}: ${text(row.shout_text)}\n Answer: pullboard answer ${row.shout_id} "<your answer>" --as person`);
+ const shouts = db.prepare("SELECT * FROM shout WHERE shout_to = 'coordinator' ORDER BY shout_id DESC LIMIT ?").all(ROW_LIMIT).map((row) =>
+ `- ${text(row.shout_from, 80)}, ${text(row.shout_at, 40)}: ${text(row.shout_text, 400)}`);
+
+ let elsewhere = 0;
+ const roadmap = milestones({ db }).map((milestone, order) => {
+ const local = milestone.items.filter((id) => typeof id === 'number');
+ elsewhere += milestone.items.length - local.length;
+ const count = (test) => local.filter((id) => test(items.get(id))).length;
+ const counts = [`${count((item) => item?.item_status === 'verified' && item.item_merged_commit)} landed`,
+ `${count((item) => item?.item_status === 'verified' && !item.item_merged_commit)} accepted`,
+ `${count((item) => item?.state === 'submitted')} in review`,
+ `${count((item) => ['open', 'claimed'].includes(item?.state))} open`];
+ const finished = local.length > 0 && count((item) => item?.item_status === 'verified') === local.length;
+ const moved = count((item) => item && !['open', 'claimed'].includes(item.state) && item.item_status !== 'withdrawn') > 0;
+ return { order, finished, entry: `- ${text(milestone.name, 200)}: ${finished ? 'finished' : moved ? 'in progress' : 'planned'}; ${local.length} items, ${counts.join(', ')}.${milestone.note ? `\n ${text(milestone.note, 240)}` : ''}` };
+ })
+ // Releases still in progress come first, in roadmap order; then the most recently finished.
+ .sort((a, b) => (a.finished - b.finished) || (a.finished ? b.order - a.order : a.order - b.order)).map((row) => row.entry);
+
+ const sections = [
+ section('Open work', open.slice(0, ROW_LIMIT).map(work), open.length, 10_000, 'Nothing is open.'),
+ section('Blocked work', blocked.slice(0, ROW_LIMIT).map(work), blocked.length, 6_000, 'Nothing is blocked.'),
+ section('In review', review.slice(0, ROW_LIMIT).map((item) => `- ${label(item.item_id)}, built by ${text(item.item_built_by ?? item.item_owner, 80)}: waits for a second agent to verify it.`), review.length, 3_000, 'Nothing waits for review.'),
+ section('Recent decisions and answers', decisions.map((row) => row.entry), decisionTotal, 7_000, 'No decisions are recorded yet.'),
+ section('Recent verdicts', verdicts, Number(db.prepare('SELECT count(*) AS n FROM verdict').get().n), 5_000, 'No work has been verified yet.'),
+ section('Questions waiting on you', questions, Number(db.prepare(`SELECT count(*) AS n ${waiting}`).get().n), 4_500, 'No question waits on you.'),
+ section('Latest shouts to the coordinator', shouts, Number(db.prepare("SELECT count(*) AS n FROM shout WHERE shout_to = 'coordinator'").get().n), 5_000, 'No one has shouted the coordinator yet.'),
+ section('Milestones', roadmap, roadmap.length, 4_000, 'No milestones are set.'),
+ ];
+ const sequence = Number(db.prepare('SELECT coalesce(max(event_id), 0) AS n FROM event').get().n);
+ const glance = [
+ `- ${landed} items landed and ${accepted} are accepted and wait to land.`,
+ `- ${review.length} wait for review, ${open.length} are open and ${blocked.length} are blocked.`,
+ `- ${sections[5].total} questions wait on you.`,
+ ].join('\n');
+ const left = [
+ ...sections.filter((entry) => entry.shown < entry.total).map((entry) => `- ${entry.title}: ${entry.shown} of ${entry.total} shown.`),
+ `- ${cut.count} long texts were cut short, and lines that look like secrets read [redacted secret].`,
+ `- ${elsewhere} milestone items from other boards were left out; this briefing covers this board only.`,
+ '- Older history, finished work, code and full conversations stay on the board: pullboard show <number> prints any item.',
+ ].join('\n');
+ const markdown = `# Board briefing: ${text(name, 200)}\n\nRead from this project's board at ${at}, through board move ${sequence}. Making it changed nothing on the board.\n\n## At a glance\n\n${glance}\n\n${sections.map((entry) => entry.text).join('')}## Left out of this briefing\n\n${left}\n`;
+ const bytes = Buffer.byteLength(markdown);
+ // The section budgets sum well under the cap, so this refusal marks a bug in those budgets.
+ if (bytes >= DIGEST_MAX_BYTES) throw new Refused('DIGEST_SIZE', 'the briefing outgrew its 50 KB budget; shout the coordinator with the board size so the budgets get fixed');
+ return { markdown, sequence, bytes, sections: sections.map(({ title, shown, total }) => ({ title, shown, total })) };
+}
+
+/**
+ * The output path, refused inside Git metadata (where the board lives) or onto an SQLite file,
+ * so a typo can never replace the board with a briefing. Symlinked directories are resolved first.
+ *
+ * @param {string} path
+ * @param {string} commonDir
+ * @returns {string}
+ */
+function outputPath(path, commonDir) {
+ const target = resolve(path);
+ let parent;
+ try { parent = realpathSync(dirname(target)); }
+ catch { throw new Refused('DIGEST_WRITE', `the folder for ${target} does not exist; create it or choose another --out file`); }
+ const canonical = join(parent, basename(target));
+ const inside = relative(realpathSync(commonDir), canonical);
+ if (basename(canonical) === '.git' || !inside || (inside !== '..' && !inside.startsWith(`..${sep}`) && !isAbsolute(inside))) {
+ throw new Refused('DIGEST_WRITE', 'the board lives in .git; choose an --out file outside it, such as briefing.md');
+ }
+ if (existsSync(canonical) && statSync(canonical).isFile()) {
+ const fd = openSync(canonical, 'r');
+ try {
+ const head = Buffer.alloc(16);
+ if (readSync(fd, head, 0, 16, 0) === 16 && head.toString() === 'SQLite format 3\0') {
+ throw new Refused('DIGEST_WRITE', `${canonical} is a database; choose a Markdown --out file, such as briefing.md`);
+ }
+ } finally { closeSync(fd); }
+ }
+ return canonical;
+}
+
+/**
+ * Replace the chosen file atomically: write a private temporary file beside it, flush it, then
+ * rename it over the target, so a reader sees the old briefing or the new one and never half.
+ *
+ * @param {string} path
+ * @param {string} markdown
+ * @param {string} commonDir
+ * @returns {string} the file written
+ */
+export function writeDigest(path, markdown, commonDir) {
+ const target = outputPath(path, commonDir);
+ const temporary = join(dirname(target), `.pullboard-digest-${randomUUID()}.tmp`);
+ let fd;
+ try {
+ fd = openSync(temporary, 'wx', 0o600);
+ writeFileSync(fd, markdown);
+ fsyncSync(fd);
+ closeSync(fd);
+ fd = undefined;
+ renameSync(temporary, target);
+ return target;
+ } catch (error) {
+ if (error instanceof Refused) throw error;
+ throw new Refused('DIGEST_WRITE', `could not write ${target}; choose a writable --out file and run pullboard digest again`);
+ } finally {
+ if (fd !== undefined) closeSync(fd);
+ rmSync(temporary, { force: true });
+ }
+}
+
+/**
+ * Rewrite the briefing after every board move until `signal` aborts. SQLite's data_version
+ * changes when another connection commits, including WAL writes, so polling it is cheap and the
+ * watcher holds no transaction between reads.
+ *
+ * @param {string} file
+ * @param {string} path
+ * @param {{ name: string, commonDir: string, signal: AbortSignal, interval?: number, onWrite?: (result: any) => void }} options
+ */
+export async function watchDigest(file, path, { name, commonDir, signal, interval = 250, onWrite = () => {} }) {
+ let db;
+ let identity;
+ let seen = -1;
+ try {
+ while (!signal.aborted) {
+ const stat = statSync(file);
+ const current = `${stat.dev}:${stat.ino}`;
+ if (current !== identity) {
+ // A restored or replaced board file gets a fresh connection.
+ db?.close();
+ db = openBoardReadOnly(file);
+ identity = current;
+ seen = -1;
+ }
+ const version = db.prepare('PRAGMA data_version').get().data_version;
+ if (version !== seen) {
+ const result = readDigest(file, { name });
+ onWrite({ ...result, path: writeDigest(path, result.markdown, commonDir) });
+ seen = version;
+ }
+ try { await pause(interval, undefined, { signal }); }
+ catch (error) { if (error.name !== 'AbortError') throw error; }
+ }
+ } finally { db?.close(); }
+}
+
+/**
+ * The digest command: print the briefing, write it with --out, or keep it current with --watch.
+ *
+ * @param {any} io
+ * @param {{ first?: string, second?: string, rest: string[], values: Record<string, any> }} args
+ * @param {{ info: { commonDir: string }, config: { name?: string }, file: string }} ctx
+ * @returns {Promise<number>}
+ */
+export async function digestCommand(io, { first, second, rest, values }, ctx) {
+ const usage = 'pullboard digest [--out <file>] [--watch]; --watch needs --out';
+ if (first || second || rest.length || Object.keys(values).some((key) => !['out', 'watch', 'json'].includes(key))) throw new Refused('USAGE', usage);
+ if (values.out === '' || (values.watch && (!values.out || values.json))) throw new Refused('USAGE', usage);
+ const name = ctx.config.name;
+ const out = values.out === undefined ? undefined : resolve(io.cwd, values.out);
+ if (values.watch) {
+ const controller = new AbortController();
+ /** Stop watching on Ctrl-C or a termination signal; the board is left as it was. */
+ const stop = () => controller.abort();
+ process.once('SIGINT', stop);
+ process.once('SIGTERM', stop);
+ try {
+ await watchDigest(ctx.file, out, { name, commonDir: ctx.info.commonDir, signal: controller.signal,
+ onWrite: (result) => io.say(`wrote the briefing to ${result.path} (board move ${result.sequence}); Ctrl-C stops watching`) });
+ } finally { process.off('SIGINT', stop); process.off('SIGTERM', stop); }
+ return 0;
+ }
+ const result = readDigest(ctx.file, { name });
+ const path = out === undefined ? undefined : writeDigest(out, result.markdown, ctx.info.commonDir);
+ io.result?.({ markdown: result.markdown, bytes: result.bytes, sequence: result.sequence, sections: result.sections, ...(path ? { path } : {}) });
+ io.say(path ? `wrote the briefing to ${path}; share that file with any chat assistant` : result.markdown.trimEnd());
+ return 0;
+}
diff --git a/src/help.js b/src/help.js
index f04bad16..d3cc3b4a 100644
--- a/src/help.js
+++ b/src/help.js
@@ -111,6 +111,8 @@ Work
pullboard pass <shout-id> <note> coordinator passes a decision to the person
pullboard decisions [--as person] shouts waiting for you; main checkout defaults to coordinator
pullboard export print the whole board as versioned JSON
+ pullboard digest [--out <file>] [--watch] a short Markdown briefing of this board for a person or a chat assistant;
+ secrets redacted; --out replaces a file, --watch rewrites it after every move
pullboard import <file> restore a versioned export into an empty board
Coordinator
@@ -200,7 +202,7 @@ Reject reasons: TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HE
const HELP_NAMES = [
'tour', 'init', 'worktree', 'join', 'takeover', 'whoami', 'lanes', 'lane', 'lane add', 'status', 'resources', 'settings', 'view', 'view export',
'serve', 'mcp', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'skills', 'show', 'next', 'land',
- 'check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'why', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import',
+ 'check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'why', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'digest', 'import',
'sweep', 'merged', 'withdraw', 'refreeze', 'reopen', 'hold', 'stats', 'ledger', 'log', 'spec', 'spec check', 'spec view',
'spec show', 'spec unmet', 'spec signoff', 'spec draft', 'spec signers', 'spec signers add', 'doctrine', 'doctrine check', 'forget', 'prompt', 'gate', 'hook',
'hook pre-commit', 'hook pre-merge-commit', 'hook commit-msg', 'hook pre-push', 'view export', 'version', 'lifecycle', 'help',
@@ -223,7 +225,7 @@ const HELP_EXAMPLES = {
why: 'pullboard why 12',
verify: 'pullboard verify 12 accept --note "removed the fix; the test failed"',
answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',
- status: 'pullboard status', view: 'pullboard view', mcp: 'pullboard mcp', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',
+ status: 'pullboard status', view: 'pullboard view', digest: 'pullboard digest --out briefing.md', mcp: 'pullboard mcp', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',
'lane add': 'pullboard lane add web --owns apps/web/', lane: 'pullboard lane add web --owns apps/web/',
roadmap: 'pullboard roadmap', milestone: 'pullboard milestone add "0.7.0" --items 12,13',
runner: 'pullboard runner add studio --slots 2 --browser 1', 'runner add': 'pullboard runner add studio --slots 2 --browser 1',
diff --git a/src/json.js b/src/json.js
index 8397aaf0..c969fdc6 100644
--- a/src/json.js
+++ b/src/json.js
@@ -73,6 +73,7 @@ export const JSON_SHAPES = {
prompt: shape({ role: 'string', text: 'string' }),
gate: shape({ green: 'boolean', report: 'string' }),
export: shape({ tables: 'object' }),
+ digest: shape({ markdown: 'string', bytes: 'number', sequence: 'number', sections: 'array' }),
import: shape({ tables: 'array' }),
spec: shape({ rows: 'array' }),
'spec check': shape({ rows: 'array' }),
diff --git a/src/next-steps.js b/src/next-steps.js
index 83fd45c4..d56c85ad 100644
--- a/src/next-steps.js
+++ b/src/next-steps.js
@@ -113,6 +113,8 @@ export const NEXT_STEPS = Object.freeze({
DEVICE_WRAP_BINDING: 'upgrade Pullboard, then pair the device again: pullboard relay on --all',
DEVICE_WRAP_KEY: 'pair the device again: pullboard relay on --all',
DIFF_TOO_LARGE: 'split the change into smaller commits',
+ DIGEST_SIZE: 'shout the coordinator with the board size: pullboard shout coordinator "digest outgrew 50 KB"',
+ DIGEST_WRITE: 'choose a writable file outside .git: pullboard digest --out briefing.md',
DIRTY: 'commit your changes, then run the command again',
EMPTY_FACT: 'give nonempty fact text: pullboard fact <id> note "<what you saw>"',
EMPTY_BLUEPRINT: 'ask the person to approve exportable rows written as "<rule> Why: <reason>", then run pullboard blueprint save again',
diff --git a/test/api.test.js b/test/api.test.js
index 008edff9..da082cc0 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -951,6 +951,7 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>
const source = project();
const target = project();
const document = json(source, source.repo, 'export');
+ assert.match(json(source, source.repo, 'digest').markdown, /^# Board briefing: /u);
const file = join(source.dir, 'board.json');
writeFileSync(file, JSON.stringify(document));
json(source, target.repo, 'import', [file]);
diff --git a/test/digest.test.js b/test/digest.test.js
new file mode 100644
index 00000000..66c7ab3c
--- /dev/null
+++ b/test/digest.test.js
@@ -0,0 +1,209 @@
+/** pullboard digest: a readable, bounded, read-only briefing of one real board [A2,N26]. */
+import assert from 'node:assert/strict';
+import { once } from 'node:events';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { DIGEST_MAX_BYTES } from '../src/digest.js';
+import { exportBoard } from '../src/exchange.js';
+import { registerProject } from '../src/projects.js';
+import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';
+import { runFixtureChild, runFixtureGit, startFixtureChild } from './fixture-child.js';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+
+/**
+ * A real repository with its own board in a private temporary folder, so the developer's registry
+ * and board are never read or touched.
+ */
+function fixture(t, name) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-digest-'));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const repo = join(dir, 'repo');
+ mkdirSync(repo);
+ const env = { ...process.env, PULLBOARD_HOME: join(dir, 'home'), PULLBOARD_MACHINE_HOME: join(dir, 'machine'),
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Fixture', GIT_COMMITTER_EMAIL: '[email protected]' };
+ for (const key of Object.keys(env)) if (key.startsWith('GIT_') && !key.startsWith('GIT_CONFIG') && !/^GIT_(AUTHOR|COMMITTER)_/u.test(key)) delete env[key];
+ for (const marker of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete env[marker];
+ delete env.PULLBOARD_RELAY_TOKEN;
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: repo, env });
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ name, spec: 'SPEC.md', gate: 'true', lanes: { web: { owns: ['web/'] } } }));
+ writeFileSync(join(repo, 'SPEC.md'), '# Fixture\n\n## G · Goals\n- G1 [approved, must] Keep the board. | gate: true\n');
+ runFixtureGit(['add', '-A'], { cwd: repo, env });
+ runFixtureGit(['commit', '-q', '-m', 'chore: start the digest fixture'], { cwd: repo, env });
+ const commonDir = join(repo, '.git');
+ const file = join(commonDir, 'pullboard', 'board.sqlite');
+ const board = store.openBoard(file);
+ t.after(() => store.closeBoard(board));
+ store.register(board, { lane: 'coordinator', path: repo });
+ store.register(board, { lane: 'web', path: join(dir, 'builder') });
+ store.register(board, { lane: 'web', path: join(dir, 'reviewer') });
+ return { dir, repo, env, commonDir, file, board };
+}
+
+/** Add an item through the board's own API, so the fixture obeys the lifecycle rules. */
+function add(board, title, extra = {}) {
+ return store.addItem(board, { by: 'coordinator', lane: 'web', title, criterion: `Done means ${title} works`, specIds: ['G1'], ...extra });
+}
+
+/** Run the real CLI in the fixture repo and return its stdout. */
+function cli(box, ...args) {
+ const result = runFixtureChild(process.execPath, [BIN, ...args], { cwd: box.repo, env: box.env, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.failure || result.stderr);
+ return result.stdout;
+}
+
+/** What a read-only command must leave exactly as it was: every row, and the event count. */
+function snapshot(box) {
+ return { events: box.board.db.prepare('SELECT count(*) AS n, max(event_id) AS last FROM event').get(), tables: exportBoard(box.board) };
+}
+
+/** Register both projects in the fixture's private registry, as two boards on one machine. */
+function registerBoth(home, roots) {
+ const previous = process.env.PULLBOARD_HOME;
+ process.env.PULLBOARD_HOME = home;
+ try { for (const root of roots) registerProject(root); }
+ finally { if (previous === undefined) delete process.env.PULLBOARD_HOME; else process.env.PULLBOARD_HOME = previous; }
+}
+
+/** The body of one `## ` section, up to the next heading. */
+function sectionOf(markdown, title) {
+ const start = markdown.indexOf(`\n## ${title}\n`);
+ assert.ok(start >= 0, `the briefing has a ${title} section`);
+ const end = markdown.indexOf('\n## ', start + 4);
+ return markdown.slice(start, end < 0 ? undefined : end);
+}
+
+test('the digest is a readable briefing of one board [A2,N26]', (t) => {
+ const box = fixture(t, 'Briefing project');
+ const other = fixture(t, 'Other private project');
+ add(other.board, 'Other board private item');
+ store.shout(other.board, { from: 'web-1', to: 'coordinator', text: 'Other board shout to its coordinator', lanes: ['web'] });
+ registerBoth(box.env.PULLBOARD_HOME, [box.repo, other.repo]);
+
+ const planted = 'gh' + 'p_' + 'Q'.repeat(36); // A synthetic token, built here so no secret is committed.
+ const first = add(box.board, 'Upload page', { criterion: 'A person uploads a file and sees it listed' });
+ const prerequisite = add(box.board, 'Storage bucket');
+ add(box.board, 'Share links', { after: [prerequisite], criterion: 'A shared link opens the file' });
+ const held = add(box.board, 'Pricing page');
+ store.holdItem(box.board, held, { agentId: 'coordinator', reason: 'The person picks the prices first' });
+ add(box.board, 'Secret in a bar', { criterion: `Use token ${planted} for the demo` });
+ store.appendFact(box.board, first, { agentId: 'coordinator', kind: 'decision', text: 'One upload path, because two paths drift apart' });
+ const ask = store.shout(box.board, { from: 'web-1', to: 'coordinator', text: 'May the cache be the source of truth?', lanes: ['web'], decision: true });
+ store.answerDecision(box.board, ask, { agentId: 'coordinator', text: 'No, because the cache must stay disposable', lanes: ['web'] });
+ store.shout(box.board, { from: 'coordinator', to: 'person', text: 'Should a newcomer see the tour first?', lanes: ['web'], decision: true });
+ store.shout(box.board, { from: 'web-1', to: 'coordinator', text: `Found a key ${planted} in the logs`, lanes: ['web'] });
+ store.shout(box.board, { from: 'web-2', to: 'coordinator', text: 'The upload review is next in my queue', lanes: ['web'] });
+ /** The frozen criterion a claim records. */
+ const freeze = (item) => ({ text: item.item_title, digest: 'digest:briefing' });
+ store.claim(box.board, first, { agentId: 'web-1', lane: 'web', leaseMs: 3_600_000, freeze });
+ store.submit(box.board, first, { agentId: 'web-1', commit: 'a'.repeat(40), tree: 'fixture-tree' });
+ store.verify(box.board, first, { agentId: 'web-2', decision: 'REJECT', reason: 'TEST_FAILURE',
+ note: 'The upload test fails on an empty file', head: 'a'.repeat(40), digest: 'digest:briefing', policy: 'any' });
+ store.addMilestone(box.board, { agentId: 'coordinator', name: 'First release', note: 'Uploads that work', items: [first, prerequisite] });
+
+ const before = snapshot(box);
+ const markdown = cli(box, 'digest');
+ assert.deepEqual(snapshot(box), before, 'the digest changes no row and records no event');
+
+ assert.match(markdown, /^# Board briefing: Briefing project\n/u);
+ const open = sectionOf(markdown, 'Open work');
+ assert.match(open, /Upload page \(#1\), in the web lane: open to claim\.\n {2}Done when: A person uploads a file and sees it listed/u);
+ assert.match(open, /Storage bucket \(#2\)/u);
+ const blocked = sectionOf(markdown, 'Blocked work');
+ assert.match(blocked, /Share links \(#3\).*\n {2}Done when: A shared link opens the file\n {2}Waits for: Storage bucket \(#2\)\./u);
+ assert.match(blocked, /Pricing page \(#4\).*\n {2}Done when: .*\n {2}Held: The person picks the prices first/u);
+ const decisions = sectionOf(markdown, 'Recent decisions and answers');
+ assert.match(decisions, /A decision on Upload page \(#1\) by coordinator.*\n {2}One upload path, because two paths drift apart/u);
+ assert.match(decisions, /Asked: May the cache be the source of truth\?\n {2}Answer and reason: No, because the cache must stay disposable/u);
+ assert.match(sectionOf(markdown, 'Recent verdicts'),
+ /Upload page \(#1\) was rejected by web-2, .*: a test failed \(TEST_FAILURE\)\.\n {2}Note: The upload test fails on an empty file/u);
+ assert.match(sectionOf(markdown, 'Questions waiting on you'),
+ /coordinator asks, .*: Should a newcomer see the tour first\?\n {2}Answer: pullboard answer \d+ "<your answer>" --as person/u);
+ const shouts = sectionOf(markdown, 'Latest shouts to the coordinator');
+ assert.match(shouts, /web-2, .*: The upload review is next in my queue/u);
+ assert.ok(shouts.indexOf('upload review') < shouts.indexOf('[redacted secret]'), 'the latest shout comes first');
+ assert.match(sectionOf(markdown, 'Milestones'), /First release: planned; 2 items, 0 landed, 0 accepted, 0 in review, 2 open\.\n {2}Uploads that work/u);
+ assert.match(sectionOf(markdown, 'At a glance'), /1 questions wait on you/u);
+
+ assert.equal(markdown.includes(planted), false, 'a secret never reaches the briefing');
+ assert.equal(markdown.includes('ghp_'), false, 'no part of the secret survives');
+ assert.match(sectionOf(markdown, 'Open work'), /Secret in a bar \(#5\).*\n {2}Done when: \[redacted secret\]/u);
+ assert.match(shouts, /web-1, .*: \[redacted secret\]/u);
+ for (const foreign of ['Other private project', 'Other board private item', 'Other board shout', other.repo]) {
+ assert.equal(markdown.includes(foreign), false, `nothing from the second board appears: ${foreign}`);
+ }
+ assert.match(sectionOf(markdown, 'Left out of this briefing'), /this briefing covers this board only/u);
+ assert.ok(Buffer.byteLength(markdown) < DIGEST_MAX_BYTES);
+
+ const json = JSON.parse(cli(box, 'digest', '--json'));
+ /** The briefing from its first section on; the header carries the time it was read. */
+ const body = (text) => text.slice(text.indexOf('## At a glance')).trimEnd();
+ assert.equal(body(json.markdown), body(markdown), 'the JSON result carries the same briefing');
+ assert.deepEqual(json.sections.map((entry) => entry.title), ['Open work', 'Blocked work', 'In review', 'Recent decisions and answers',
+ 'Recent verdicts', 'Questions waiting on you', 'Latest shouts to the coordinator', 'Milestones']);
+
+ const out = join(box.dir, 'briefing.md');
+ writeFileSync(out, 'an older briefing');
+ assert.match(cli(box, 'digest', '--out', out), /wrote the briefing to .*briefing\.md/u);
+ assert.match(readFileSync(out, 'utf8'), /^# Board briefing: Briefing project\n/u);
+ assert.equal(statSync(out).mode & 0o777, 0o600);
+ assert.deepEqual(readdirSync(box.dir).filter((name) => name.startsWith('.pullboard-digest-')), [], 'the replacement leaves no temporary file');
+ const intoBoard = runFixtureChild(process.execPath, [BIN, 'digest', '--out', box.file], { cwd: box.repo, env: box.env, encoding: 'utf8' });
+ assert.equal(intoBoard.status, 1);
+ assert.match(intoBoard.stderr, /DIGEST_WRITE/u);
+ assert.deepEqual(snapshot(box), before, 'writing the file changes nothing on the board');
+
+ for (let index = 0; index < 240; index += 1) add(box.board, `Large item ${index}`, { criterion: 'A long bar with wide text 世界. '.repeat(200) });
+ const largeBefore = snapshot(box);
+ const large = cli(box, 'digest');
+ assert.deepEqual(snapshot(box), largeBefore);
+ assert.ok(Buffer.byteLength(large) < DIGEST_MAX_BYTES, `UTF-8 bytes stay under 50 KB (${Buffer.byteLength(large)})`);
+ assert.match(sectionOf(large, 'Open work'), /\n\d+ more left out to keep this briefing short\.\n/u);
+ assert.match(sectionOf(large, 'Left out of this briefing'), /- Open work: \d+ of 243 shown\./u);
+ assert.match(sectionOf(large, 'Left out of this briefing'), /- [1-9]\d* long texts were cut short/u);
+});
+
+/** Wait for the watched file to satisfy `predicate`; every read must be a whole briefing. */
+async function waitForFile(path, predicate) {
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ if (existsSync(path)) {
+ const markdown = readFileSync(path, 'utf8');
+ assert.match(markdown, /^# Board briefing: /u, 'a reader never sees a partial file');
+ assert.match(markdown, /pullboard show <number> prints any item\.\n$/u, 'every replacement is whole');
+ if (predicate(markdown)) return markdown;
+ }
+ await new Promise((resolveWait) => setTimeout(resolveWait, 20));
+ }
+ assert.fail('the watched briefing did not show the board move in time');
+}
+
+test('digest --watch rewrites the file after every board move and stops cleanly [A2,N26]', { timeout: 30_000 }, async (t) => {
+ const box = fixture(t, 'Watched project');
+ const out = join(box.dir, 'watch.md');
+ const child = startFixtureChild(process.execPath, [BIN, 'digest', '--watch', '--out', out], { cwd: box.repo, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });
+ const closed = once(child, 'close');
+ let stderr = '';
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });
+ child.stdout.resume();
+ try {
+ await waitForFile(out, () => true);
+ for (const text of ['First watched move', 'Second watched move']) {
+ store.shout(box.board, { from: 'web-1', to: 'coordinator', text, lanes: ['web'] });
+ const after = snapshot(box);
+ await waitForFile(out, (markdown) => markdown.includes(text));
+ assert.deepEqual(snapshot(box), after, 'the watcher never changes the board');
+ }
+ child.kill('SIGTERM');
+ const [code, signal] = await closed;
+ assert.equal(code, 0, stderr);
+ assert.equal(signal, null);
+ assert.deepEqual(readdirSync(box.dir).filter((name) => name.startsWith('.pullboard-digest-')), []);
+ } finally {
+ if (child.exitCode === null && child.signalCode === null) { child.kill('SIGTERM'); await closed; }
+ }
+});