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
Merge current main into accepted #695
Corey Olson3344b66660a7
diff --cc src/blueprint-set.jsindex 00000000,45d01b69..04bc93camode 000000,100644..100644--- a/src/blueprint-set.js+++ b/src/blueprint-set.js@@@ -1,0 -1,210 +1,216 @@@+ /**+ * Several blueprints in one init or blueprint add [S1,I1]: --blueprint repeats, and the blueprints+ * land in the order given. A board takes at most one product blueprint and one architecture+ * blueprint, one per deployable (research U110), and any number of practice and beyond-code ones.+ * A rule or question text two of them share is drafted once, by the first, and the later blueprint+ * cites that row. Every starter item keeps the name of the blueprint that filed it.+ */-import { existsSync, readFileSync } from 'node:fs';++import {++ existsSync,++ readFileSync,++} from 'node:fs';+ import { join } from 'node:path';-import { bundledBlueprints, readBlueprint } from './blueprints.js';++import {++ bundledBlueprints,++ readBlueprint,++} from './blueprints.js';+ import { CONFIG_FILE } from './config.js';+ import { Refused } from './refused.js';++ /**+ * The kinds a board takes one of, by the slot each fills. Why infrastructure is here: #719 renamed+ * it architecture and loads it as such, but a kind line written by name still says what it read.+ */+ const ONE_PER_BOARD = { product: 'product', infrastructure: 'architecture', architecture: 'architecture' };++ /**+ * The slot a blueprint fills, product or architecture, or null for a kind a board takes any number of.+ *+ * @param {{ kind?: string }} blueprint+ * @returns {string | null}+ */+ export function blueprintSlot(blueprint) {+ return ONE_PER_BOARD[blueprint.kind] ?? null;+ }++ /**+ * The blueprints a repo's board already has and the slot each fills, read from its SPEC.md: the+ * kind line each one's add leaves, with slot null for a kind a board takes any number of. A board+ * an older Pullboard set up has a blueprint's marker alone. Its kind then comes from the bundled+ * file of that name, else from its own file at the repo root (<name>.json or <name>.blueprint.json),+ * checked like any blueprint; else the slot is unknown, which may be the product or architecture+ * slot, so readBlueprints refuses either until the kind is recorded. Nothing without a spec.+ *+ * @param {string} root - The repository root.+ * @returns {{ name: string, slot: string | null }[]}+ */+ export function installedBlueprints(root) {+ let specFile = 'SPEC.md';+ try { specFile = JSON.parse(readFileSync(join(root, CONFIG_FILE), 'utf8')).spec ?? specFile; }+ catch (error) {+ // No pullboard.json yet, or one init will refuse on its own: the default spec file is read.+ if (!(error instanceof SyntaxError) && error?.code !== 'ENOENT') throw error;+ }+ const file = join(root, String(specFile));+ if (!existsSync(file)) return [];+ const found = new Map();+ const legacy = [];+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/u)) {+ const kind = /^<!-- pullboard-blueprint-kind (\S+) (\S+) -->$/u.exec(line.trim());+ const marker = /^<!-- pullboard-blueprint (\S+) \d+(?: adding .*)? -->$/u.exec(line.trim());+ if (kind) found.set(kind[1], blueprintSlot({ kind: kind[2] }));+ else if (marker) legacy.push(marker[1]);+ }+ for (const name of legacy) if (!found.has(name)) found.set(name, legacySlot(name, root));+ return [...found].map(([name, slot]) => ({ name, slot }));+ }++ /**+ * The slot of a blueprint whose marker has no kind line: from the bundled file of that name, else+ * from its own file at the repo root when that file names it, else "unknown".+ *+ * @param {string} name+ * @param {string} root+ * @returns {string | null}+ */+ function legacySlot(name, root) {+ if (bundledBlueprints().includes(name)) return blueprintSlot(readBlueprint(name, root));+ for (const candidate of [`${name}.json`, `${name}.blueprint.json`]) {+ if (!existsSync(join(root, candidate))) continue;+ try {+ const blueprint = readBlueprint(join(root, candidate), root);+ if (blueprint.name === name) return blueprintSlot(blueprint);+ } catch (error) {+ // A file there that is no valid blueprint says nothing about this one's kind.+ if (!(error instanceof Refused)) throw error;+ }+ }+ return 'unknown';+ }++ /**+ * Read every named blueprint, in the order given, before anything is written, so an unknown name+ * or a clash leaves the repository as it was. The same blueprint version named twice is read once.+ * A second product or architecture blueprint is refused with BLUEPRINT_KIND_TAKEN naming both,+ * whether the first is named in the same command or already on the board; adding again the+ * blueprint the board already has is no clash, since that add changes nothing.+ *+ * @param {string[]} references - Bundled names or paths, as --blueprint gave them.+ * @param {string} cwd+ * @param {string} command - The command to name in the next step, such as "init".+ * @param {{ name: string, slot: string | null }[]} [installed] - The board's own, from installedBlueprints.+ * @returns {{ reference: string, blueprint: import('./blueprints.js').Blueprint }[]}+ */+ export function readBlueprints(references, cwd, command, installed = []) {+ const read = [];+ for (const reference of references) {+ const blueprint = readBlueprint(reference, cwd);+ if (read.some((entry) => entry.blueprint.name === blueprint.name && entry.blueprint.version === blueprint.version)) continue;+ const slot = blueprintSlot(blueprint);+ const onBoard = slot && installed.find((entry) => [slot, 'unknown'].includes(entry.slot) && entry.name !== blueprint.name);+ if (onBoard?.slot === 'unknown') {+ throw new Refused('BLUEPRINT_KIND_TAKEN',+ `${onBoard.name} and ${blueprint.name} may both be ${slot} blueprints: this board has ${onBoard.name}, added before Pullboard recorded a blueprint's kind, and a board takes one ${slot} blueprint; record its kind by adding its file again, which changes nothing else: pullboard blueprint add <${onBoard.name} file>`,+ `record ${onBoard.name}'s kind with pullboard blueprint add <${onBoard.name} file>, then run pullboard ${command} again`);+ }+ if (onBoard) {+ throw new Refused('BLUEPRINT_KIND_TAKEN',+ `${onBoard.name} and ${blueprint.name} are both ${slot} blueprints, and this board already has ${onBoard.name}; a board takes one ${slot} blueprint, so add ${blueprint.name} on a board of its own`,+ `keep ${onBoard.name} and leave ${blueprint.name} out of pullboard ${command}`);+ }+ const holder = slot && read.find((entry) => blueprintSlot(entry.blueprint) === slot);+ if (holder) {+ const keep = read.map((entry) => `--blueprint ${entry.reference}`).join(' ');+ throw new Refused('BLUEPRINT_KIND_TAKEN',+ `${holder.blueprint.name} and ${blueprint.name} are both ${slot} blueprints, and a board takes one ${slot} blueprint; keep one of them: pullboard ${command} ${keep}`,+ `name one ${slot} blueprint: pullboard ${command} ${keep}`);+ }+ read.push({ reference, blueprint });+ }+ return read;+ }++ /**+ * The result blueprint add gives for several blueprints: the first blueprint's own fields, as one+ * add gives them, with the rows, items, lanes and stored checks of all of them, and each one's own+ * summary in blueprints, in the order they landed.+ *+ * @param {any[]} added - Each blueprint's summary from its add, in order.+ * @returns {any}+ */+ export function combinedSummary(added) {+ return { ...added[0], rows: added.flatMap((entry) => entry.rows), items: added.flatMap((entry) => entry.items),+ gate: added.find((entry) => entry.gate)?.gate ?? null, marked: added.every((entry) => entry.marked),+ proposedLanes: [...new Map(added.flatMap((entry) => entry.proposedLanes).map((lane) => [lane.name, lane])).values()],+ checksNotRun: added.flatMap((entry) => entry.checksNotRun), blueprints: added };+ }++ /**+ * What init's JSON result says about one blueprint it added.+ *+ * @param {any} added - The blueprint's summary from its add.+ * @returns {any}+ */+ export function initBlueprintResult(added) {+ return { name: added.blueprint.name, title: added.blueprint.title, section: added.section, waiting: added.rows.length,+ items: added.items.length, gate: added.gate, checksNotRun: added.checksNotRun, shared: added.shared ?? [] };+ }++ /**+ * The line init and blueprint add print for rows a blueprint shares with one added before it:+ * the rows it cites from there instead of drafting them again. Empty when it shares none.+ *+ * @param {any} added - The blueprint's summary from its add.+ * @returns {string[]}+ */+ export function sharedRowLines(added) {+ const shared = added.shared ?? [];+ if (!shared.length) return [];+ return [`${added.blueprint.name} shares ${shared.map((row) => row.id).join(', ')} with an earlier blueprint, so each is drafted once`];+ }++ /**+ * The note fact blueprint add records on each starter item it files, so the item keeps the name of+ * its blueprint: the blueprint's name and version and the starter's key, as JSON after a fixed+ * prefix. The text is the link #734 reads back with blueprint starters, so either reads the other.+ *+ * @param {{ name: string, version: number }} blueprint+ * @param {string} key - The starter's key in the blueprint.+ * @returns {string}+ */+ export function blueprintStarterNote(blueprint, key) {+ return `blueprint starter: ${JSON.stringify({ blueprint: blueprint.name, version: blueprint.version, key })}`;+ }++ /**+ * Add each blueprint in turn with one shared map of the rows drafted so far, by text, so a text+ * two of them share is drafted once, by the first.+ *+ * @template T+ * @param {T[]} list - The blueprints to add, in order.+ * @param {(entry: T, drafted: Map<string, string>) => Promise<any>} add - Adds one and returns its summary.+ * @returns {Promise<any[]>} Each blueprint's summary, in order.+ */+ export async function landEach(list, add) {+ const drafted = new Map();+ const landed = [];+ for (const entry of list) landed.push(await add(entry, drafted));+ return landed;+ }++ /**+ * The lines init prints for one blueprint it added: the summary, the starters that could not go to+ * the lane they asked for, the checks stored and not run, and the rows it shares with one before it.+ *+ * @param {any} added - The blueprint's summary from its add.+ * @param {string[]} laneNotes - askedLaneNotes for its starters.+ * @returns {string[]}+ */+ export function initBlueprintLines(added, laneNotes) {+ const proposed = added.proposedLanes.length ? ` in the ${added.proposedLanes.map((lane) => lane.name).join(' and ')} lane, proposed above and not written until the person accepts` : '';+ return [`added the ${added.blueprint.title} blueprint: ${added.rows.length} ${added.rows.length === 1 ? 'row waits' : 'rows wait'} for your approval in SPEC.md (${added.section}), `+ + `${added.items.length} starter ${added.items.length === 1 ? 'item' : 'items'} filed${proposed}${added.gate ? `, gate set to ${added.gate}` : ''}`,+ ...laneNotes.map((note) => ` ${note}`),+ ...(added.checksNotRun.length ? [` checks stored, not run: ${added.checksNotRun.map((id) => `#${id}`).join(', ')}; no check baseline ran, so read each check before work starts: pullboard show <id>`] : []),+ ...sharedRowLines(added).map((line) => ` ${line}`)];+ }diff --cc src/cli.jsindex 19c8dde6,6bd21cbe..a50cb6ab--- a/src/cli.js+++ b/src/cli.js@@@ -189,192 -62,47 +189,203 @@@ importstandings,unmetRows,} from './spec.js';-import { answerQuestion, bundledBlueprints, landBlueprint, planBlueprint, readBlueprint, repoAnswers, saveBlueprint } from './blueprints.js';-import { blueprintStarterNote, combinedSummary, initBlueprintLines, initBlueprintResult, installedBlueprints, landEach, readBlueprints, sharedRowLines } from './blueprint-set.js';+import {+ answerQuestion,+ bundledBlueprints,+ landBlueprint,+ planBlueprint,+ readBlueprint,+ repoAnswers,+ saveBlueprint,+} from './blueprints.js';++import {++ blueprintStarterNote,++ combinedSummary,++ initBlueprintLines,++ initBlueprintResult,++ installedBlueprints,++ landEach,++ readBlueprints,++ sharedRowLines,++} from './blueprint-set.js';import { briefFiles } from './brief.js';-import { commitFirst, commitOwnerLines, commitOwners, coordinatorInbox, coordinatorInboxLines, inboxFirst } from './resume.js';-import { checkBaseline, prepareCheckBaseline, refuseCheckSyntax, sayCheckBaseline } from './check-baseline.js';-import { checkAcceptCommand, refuseClaimProvesNothing, refuseProvesNothing } from './check-accept.js';-import { retryCheckBaselines, startCheckBaseline } from './check-baseline-worker.js';-import { compareMainFailures, mainRedMessage, mainRedReworkItems } from './main-red.js';+import {+ commitFirst,+ commitOwnerLines,+ commitOwners,+ coordinatorInbox,+ coordinatorInboxLines,+ inboxFirst,+} from './resume.js';+import {+ checkBaseline,+ prepareCheckBaseline,+ refuseCheckSyntax,+ sayCheckBaseline,+} from './check-baseline.js';+import {+ checkAcceptCommand,+ refuseClaimProvesNothing,+ refuseProvesNothing,+} from './check-accept.js';+import {+ retryCheckBaselines,+ startCheckBaseline,+} from './check-baseline-worker.js';+import {+ compareMainFailures,+ mainRedMessage,+ mainRedReworkItems,+} from './main-red.js';import { runItems } from './run.js';-import { parseProblems, sweepItems } from './sweep.js';+import {+ parseProblems,+ sweepItems,+} from './sweep.js';import { renderSpecView } from './view.js';import { tour } from './tour.js';-import { commandOutput, refusalDocument } from './json.js';-import { forgetProject, listApiProjects, registerProjectAndLink, registeredProjectRootsSnapshot } from './projects.js';+import {+ commandOutput,+ refusalDocument,+} from './json.js';+import {+ forgetProject,+ listApiProjects,+ registerProjectAndLink,+ registeredProjectRootsSnapshot,+} from './projects.js';import { milestoneRoadmap } from './roadmap.js';-import { listResources, memoryVerdict, readMachineMemory, runnerResourceStatus } from './resources.js';-import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';-import { exportView, serveView } from './serve.js';-import { forgetView, portHolder, rememberView, runningView } from './view-session.js';-import { backgroundViewLine, keepViewRunning, launchBackgroundView, reportView } from './background-view.js';+import {+ listResources,+ memoryVerdict,+ readMachineMemory,+ runnerResourceStatus,+} from './resources.js';+import {+ citedTestFiles,+ rowEvidence,+ rowStage,+} from './evidence.js';+import {+ exportView,+ serveView,+} from './serve.js';+import {+ forgetView,+ portHolder,+ rememberView,+ runningView,+} from './view-session.js';+import {+ backgroundViewLine,+ keepViewRunning,+ launchBackgroundView,+ reportView,+} from './background-view.js';import { serveApi } from './api.js';import { watchCommand } from './watch.js';import { serveMcp } from './mcp.js';-import { doctorProblems, doctrineProblems } from './doctor.js';-import { boardHealth, healthLines } from './health.js';-import { staleFrozenItems, staleItemFinding } from './approved-rows.js';-import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge, trunkRef } from './trusted-policy.js';+import {+ doctorProblems,+ doctrineProblems,+} from './doctor.js';+import {+ boardHealth,+ healthLines,+} from './health.js';+import {+ staleFrozenItems,+ staleItemFinding,+} from './approved-rows.js';+import {+ mainPolicy,+ policyAt,+ itemPolicy,+ submissionPaths,+ frozenCheck,+ checkAtCommit,+ dependencySnapshots,+ requireTrunkMerge,+ trunkRef,+} from './trusted-policy.js';import { proofStats } from './stats.js';-import { flowLines, flowAlertLine } from './stats-flow.js';+import {+ flowLines,+ flowAlertLine,+} from './stats-flow.js';import { releaseHeadlinesBetween } from './changelog.js';-import { exportBoard, importBoard } from './exchange.js';+import {+ exportBoard,+ importBoard,+} from './exchange.js';+import {+ addSigner,+ assertRequiredSigners,+ defaultPrincipal,+ hasSignerFile,+} from './signature.js';+import {+ browserFreeChecksEnabled,+ gateQueueSettings,+ gateShortSlots,+ loadMachineSettings,+ memoryFloorMB,+} from './settings.js';+import {+ pendingSnapshotSize,+ pendingCheckpointProblem,+ relayCommandReceipt,+ relayCommandReceiptReported,+ relayLinked,+ relayOff,+ relayOn,+ relayOperation,+ relayRecover,+ relayRecovered,+ relayRevoke,+ relayStatus,+ relayTokens,+ syncRelay,+} from './relay.js';+import {+ autoLinkProject,+ offerRelayAtInit,+ relayOnAllCommand,+ revokeRelayDevice,+ unlinkedRelayProjects,+} from './relay-setup.js';+ import { digestCommand } from './digest.js';-import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';-import { addRunner, browserFreeChecksEnabled, gateQueueSettings, gateShortSlots, loadMachineSettings, memoryFloorMB, relayOfferEnabled, setBrowserSlots, setGateShortSlots, setGateSlots } from './settings.js';-import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';-import { autoLinkProject, offerRelayAtInit, relayOnAllCommand, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';import { readRelayMachine } from './relay-machine.js';-import { relayJoin, relayPair } from './relay-pairing-client.js';+import {+ relayJoin,+ relayPair,+} from './relay-pairing-client.js';import { executePersonRequests } from './relay-request-execution.js';-import { engineReceipt } from './engine.js';-import { land, landingRemote, landingSubject } from './land.js';+import {+ boardSetup,+ recordSetupState,+ recordViewBind,+ recordViewReuse,+ setupIdentity,+ viewSetupComplete,+} from './setup-card.js';+import { formatSnapshotLimit } from './relay-messages.js';+import { privateNames } from './private-names.js';+import {+ runnerCommand,+ settingsCommand,+} from './machine-commands.js';+import {+ filesSince,+ recordedRecovery,+ refuseUnverifiedStack,+ reportSubmission,+} from './submission.js';+import {+ land,+ landingRemote,+ landingSubject,+} from './land.js';import { installStep } from './worktree.js';const CHECKOUT_LEASES = new WeakMap();diff --cc src/digest.jsindex 00000000,5c32476c..f6b6f323mode 000000,100644..100644--- a/src/digest.js+++ b/src/digest.js@@@ -1,0 -1,347 +1,369 @@@+ /**+ * `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 {++ 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 {++ milestones,++ openBoardReadOnly,++} from './board.js';+ import { healthReport } from './health.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. Pullboard's secret patterns are checked on the whole+ * source text, on each of its lines and on the text as it would print, before anything is split+ * or shortened; any match redacts the whole entry. Why the whole entry: a multi-line secret such+ * as a private key block is recognised by its header, and redacting only that line would print+ * the body and footer that follow it.+ *+ * @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 source = String(value ?? '');+ const printed = source.replace(/[\u0000-\u001f\u007f]/gu, ' ').replace(/\s+/gu, ' ').trim();+ const views = [source, printed, ...source.split(/\r?\n/u)];+ if (secretsIn(views.map((text) => ({ path: 'digest', line: 1, text }))).length) return '[redacted secret]';+ const text = printed;+ 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, root?: string, config?: any }} [options] root and config let+ * pullboard health's stuck findings join the briefing+ * @returns {{ markdown: string, sequence: number, sections: { title: string, shown: number, total: number }[], bytes: number }}+ */+ export function readDigest(file, { name = 'this project', now = new Date(), root, config } = {}) {+ 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, root, config });+ 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, root?: string, config?: any }} options+ */+ function render(db, { name, now, root, config }) {+ 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);++ // The same findings as pullboard health, read in this transaction: what is stuck and who moves it.+ const health = root ? healthReport({ db, root, config, now }) : { stuck: [] };+ /** Who moves a stuck finding next, in plain words. */+ const owner = ({ role, who }) => (role === 'person' ? 'you' : role === 'coordinator' ? 'the coordinator' : who ? `${text(who, 80)} (${role})` : `a ${role}`);+ const stuck = health.stuck.map((entry) => `- ${entry.item ? label(entry.item) : text(entry.subject, 60)}: ${text(entry.title, 240)}, since ${text(entry.since, 40)}: ${text(entry.why, 400)}\n Next, ${owner(entry.owner)}: ${text(entry.next, 300)}`);+ const sections = [+ section('Stuck and who moves it', stuck, stuck.length, 4_000, 'Nothing is stuck.'),+ section('Open work', open.slice(0, ROW_LIMIT).map(work), open.length, 8_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[6].total} questions wait on you, and ${health.stuck.length} things are stuck.`,+ ].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 any entry that looks like it holds a secret reads [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, root?: string, config?: any, commonDir: string, signal: AbortSignal, interval?: number, onWrite?: (result: any) => void }} options+ */+ export async function watchDigest(file, path, { name, root, config, 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, root, config });+ 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: { root: string, 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, root: ctx.info.root, config: ctx.config, 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, root: ctx.info.root, config: ctx.config });+ 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 --cc test/cli-help.test.jsindex ada26cf8,c72c00aa..8b40aec4--- a/test/cli-help.test.js+++ b/test/cli-help.test.js@@@ -138,60 -124,6 +138,60 @@@ test('next help exposes explicit buildassert.match(all.stdout, /pullboard next --build\s+claim a build explicitly, recording a skipped review offer/u);});+test('help names come from the command declarations [C7,N37]', async (t) => {+ const overview = run('help');+ const all = run('help', '--all');+ assert.equal(overview.status, 0, overview.failure);+ assert.equal(all.status, 0, all.failure);+ assert.equal(overview.stdout, HELP.overview + '\n');+ assert.equal(all.stdout, HELP.all + '\n');+ t.diagnostic('help overview bytes ' + JSON.stringify(overview.stdout));++ const directory = resolve(import.meta.dirname, '../src');+ const config = loadConfig(resolve(directory, '..'));+ const sources = readdirSync(directory, { recursive: true })+ .filter((file) => file.endsWith('.js') && laneOf(config, `src/${file}`) === 'core')+ .map((file) => ({ file, source: readFileSync(join(directory, file), 'utf8') }));+ assert.ok(sources.length > 0, 'the core lane owns source files');+ assert.deepEqual(importStyleViolations(sources), [], 'each actual static import has one binding per line');+ const styles = [+ { file: 'same-line', source: "import { first, second as renamed } from 'module';" },+ { file: 'mixed', source: "import initial, { first } from 'module';" },+ { file: 'namespace', source: "import initial, * as space from 'module';" },+ { file: 'formatted', source: "import {\n first,\n second as renamed,\n} from 'module';" },+ { file: 'comments', source: "import /* before */ { first, /* middle */ second } from 'module';" },+ { file: 'attributes', source: "import { first, second } from 'module' with { type: 'json' };" },+ { file: 'text', source: "const text = 'import { first, second }'; const raw = `import { first, second }`; const expression = /import { first, second }/; /* import { first, second } */" },+ { file: 'quoted', source: "import { 'a,b' as first } from 'module';" },+ { file: 'line-separator', source: "import { // comment\u2028 first, second } from 'module';" },+ { file: 'paragraph-separator', source: "import // comment\u2029 { first, second } from 'module';" },+ ];+ assert.deepEqual(importStyleViolations(styles), ['same-line', 'mixed', 'namespace', 'comments', 'attributes']+ .map((file) => ({ file, line: 1, count: 2 })).concat([+ { file: 'line-separator', line: 2, count: 2 },+ { file: 'paragraph-separator', line: 2, count: 2 },+ ]));++ assert.equal(typeof helpDeclaration.buildHelp, 'function', 'help is built from declarations');+ const generated = helpDeclaration.buildHelp([...resultCommands(), 'future-command']);+ for (const name of resultCommands()) assert.ok(generated.commands[name], `${name} is derived`);- assert.deepEqual(generated.commands['future-command'].usages, ['pullboard future-command']);++ assert.deepEqual(generated.commands['future-command']?.usages, ['pullboard future-command']);+ assert.equal(generated.overview, HELP.overview, 'a new declaration preserves the overview bytes');+ assert.equal(generated.all, HELP.all, 'a new declaration preserves the full-help bytes');++ const original = readFileSync(join(directory, 'cli.js'), 'utf8');+ const declaration = /function readCommands\(io, \{ first, second, rest, values \}\) \{\s*return \{/u;+ assert.match(original, declaration);+ const extended = original.replace(declaration, (text) => text + "\n/** A private new command proves help follows actual dispatch declarations. */\n'future-command': () => 0,")+ .replace(/\bfrom (['"])(\.[^'"]+)\1/gu, (_match, _quote, path) => 'from ' + JSON.stringify(pathToFileURL(resolve(directory, path)).href));+ const privateCli = await import('data:text/javascript;base64,' + Buffer.from(extended).toString('base64'));+ assert.ok(privateCli.resultCommands().includes('future-command'));+ assert.deepEqual(privateCli.HELP.commands['future-command']?.usages, ['pullboard future-command'],+ 'adding an actual command requires no edit to help.js');+ assert.equal(privateCli.HELP.overview, HELP.overview);+ assert.equal(privateCli.HELP.all, HELP.all);+});+test('init help names --blueprint [I1,N37]', () => {const result = run('init', '--help');assert.equal(result.status, 0, result.failure ?? result.stderr);