Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(blueprints): add person-approved fit proposals [S1,E3]
Corey Olson44b5c1c7a991
diff --git a/docs/api.md b/docs/api.mdindex d2a08059..d31e30de 100644--- a/docs/api.md+++ b/docs/api.md@@ -136,6 +136,8 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec| `spec show` | `version:number`, `row:object`, `standing:object` || `spec draft` | `version:number`, `id:string`, `row:object` || `blueprint add` | `version:number`, `blueprint:object`, `section:string`, `rows:array`, `items:array`, `gate:string\|null`, `proposedLanes:array` |+| `blueprint fit` | `version:number`, `proposals:array` |+| `spec fit` | `version:number`, `proposals:array` || `spec unmet` | `version:number`, `rows:array` || `spec signoff` | `version:number`, `count:number`, `by:string`, `ids:array`, `evidence:array` || `spec signers` | `version:number`, `added:boolean`, `by:string`, `path:string`, `initial:boolean` |@@ -349,6 +351,8 @@ Only the coordinator runs `spec apply`. It preflights every pending row againstTo answer a pending question row (`<ask>: <default>. Choices: a, b.`, as `blueprint add` writes it), the person runs `spec answer <id> "<choice or text>"`, or the local view sends `spec-answer` with `args: {row: "B1", answer: "Postgres"}`. A listed choice matches in any case and keeps its listed spelling; other text joins the choices last. It refuses agent shells, agent worktrees and the API channel, records the same exact-row approval receipt, whose JSON `decisions` carry an `answer` read back from the signed text (never stored on its own), and the row leaves pending when the coordinator runs `spec apply`. `spec check` errors on a question that was pending at the trunk tip and now differs with no matching person decision.+`blueprint fit <name or file> <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"]` records a seat's fit proposal for one row, question or open starter item of a blueprint fully added to this board. Proposals are unverified drafts in `blueprint-fit.json` beside the board; nothing changes until the person reads `spec fit`, edits if needed, and approves the exact batch code with `spec fit approve <batch>`. Approval refuses the proposer, non-person channels, rewritten readings, and any proposal added, removed or changed since the person's reading. Row decisions preserve the proposal reason and blueprint source in their note; starter adaptations change the criterion and drops withdraw the item after recording a decision fact. The local view/API state carries the waiting batch and per-row/item fit status.+To approve new wording, the person uses `spec approve <one-id> --text "exact proposed text"`, or `spec-approve` with `args: {ids: "G1", text: "exact proposed text"}`. This records the same exact-row receipt; files wait for coordinator apply. Text must be one nonempty line without a field separator. Pre-commit checks the staged row against that person decision or a verified staged SSH sign-off; unstaged receipts cannot authorize a commit.A coordinator criterion or check correction on a live claim remains pending until its holder or the coordinator runs `pullboard refreeze <id>`. Renewal and submission refuse with `PENDING_REFREEZE` until then. This refreeze keeps the holder, lease and claim base, and returns `retainedClaim: true` in JSON.diff --git a/src/api.js b/src/api.jsindex 71711c05..58ed1432 100644--- a/src/api.js+++ b/src/api.js@@ -16,6 +16,7 @@ import { milestoneRoadmap } from './roadmap.js';import { proofStats } from './stats.js';import { prepareFlowHistory, projectFlowStats } from './stats-flow.js';import { projectRowDecisions } from './row-decisions.js';+import { fitFile, pendingFit, projectFit } from './blueprint-fit.js';import { Refused } from './refused.js';import { codeAt, projectItemState, projectState } from './serve.js';import { relayPresentationShout } from './relay-presentation.js';@@ -41,6 +42,7 @@ function stateFileInputs(root, config) {{ name: `spec:${config.spec}`, path: join(root, config.spec) },{ name: `practice:${config.practice}`, path: join(root, config.practice) },{ name: 'builtin:standard-doctrine.md', path: new URL('./standard-doctrine.md', import.meta.url) },+ { name: 'fit:blueprint-fit.json', path: fitFile(repoInfo(root).commonDir) },];}@@ -418,7 +420,7 @@ function buildLocalBoardState(root, boardId, board, codeIsMain, { previous = nulstate.requests = projectData.requests;state.personRequests = projectData.personRequests;state.milestones = projectData.milestones;- const decorated = projectRowDecisions(projectData.rowDecisions, state);+ const decorated = projectFit(pendingFit(repoInfo(root).commonDir), projectRowDecisions(projectData.rowDecisions, state));const bases = new Map(decorated.items.map((item) => [item.id, item]));for (const id of dirtyIds) {if (!currentById.has(id)) continue;diff --git a/src/blueprint-fit-command.js b/src/blueprint-fit-command.jsnew file mode 100644index 00000000..7c6a81fb--- /dev/null+++ b/src/blueprint-fit-command.js@@ -0,0 +1,76 @@+/** The blueprint fit verbs: blueprint fit, spec fit, spec fit edit and spec fit approve [S1,E3]. */+import { readFileSync } from 'node:fs';+import * as store from './board.js';+import { approveFit, editFit, fitLine, fitSummary, proposeFit, readFitBatch, refuseOwnFit } from './blueprint-fit.js';+import { readBlueprint } from './blueprints.js';+import { COORDINATOR } from './config.js';+import { headCommit } from './git.js';+import { agentSessionDigest, requirePersonChannel } from './person.js';+import { Refused } from './refused.js';+import { prepareRowDecisions } from './row-decisions.js';+import { loadSpec } from './spec.js';++/**+ * Blueprint fit (#730): a seat proposes how a blueprint's target fits this repo; the person lists,+ * edits and approves the waiting batch. The proposer is this seat's own id and agent session, never+ * a flag. Edit and approve first refuse the session that proposed, then any non-person channel.+ * The CLI passes its ordered dispatch and its identity lookup, so every board move goes through the+ * same engine path as any other command.+ *+ * @param {any} ctx+ * @param {any} board+ * @param {{ id: string } | null} me - The seat, for a proposal; null for the person's verbs.+ * @param {'list' | 'propose' | 'edit' | 'approve' | string} verb+ * @param {string[]} args+ * @param {Record<string, any>} values+ * @param {{ ordered: Function, whoAmI: Function }} cli+ * @returns {Promise<number>}+ */+export async function fitCommand(ctx, board, me, verb, args, values, { ordered, whoAmI }) {+ const { io } = ctx;+ const [spec, items, at] = [loadSpec(ctx.info.root, ctx.config), store.listItems(board, { all: true }), new Date().toISOString()];+ const usage = 'pullboard spec fit [approve <batch>] | spec fit edit <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"]';+ /** List the batch and its code; the person's own listing is their reading of it. */+ const show = (extra = {}) => {+ const read = readFitBatch(ctx.info.commonDir, { isMain: ctx.info.isMain, channel: io.personChannel });+ io.result?.({ ...extra, proposals: read.proposals, batch: read.batch });+ (read.proposals.length ? fitSummary(read) : ['no blueprint fit proposals wait for the person']).forEach((line) => io.say(line));+ return 0;+ };+ if (verb === 'list') return show();+ if (verb === 'propose') {+ const [reference, target, decision, ...extra] = args;+ if (!reference || !target || !decision || extra.length) throw new Refused('USAGE', 'pullboard blueprint fit <name or file> <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"]');+ // Only the proposal's own words are flags; who proposed it is this seat, so no flag can name another.+ const flag = Object.keys(values).find((key) => !['text', 'reason', 'json'].includes(key));+ if (flag) throw new Refused('FLAG_NOT_ALLOWED', `blueprint fit does not take --${flag}; it records this seat as the proposer and takes only --text and --reason`);+ const proposal = proposeFit({ commonDir: ctx.info.commonDir, blueprint: readBlueprint(reference, io.cwd), specSource: readFileSync(spec.file, 'utf8'),+ spec, items, by: me.id, session: agentSessionDigest(), at }, { target, decision, text: values.text, reason: values.reason });+ io.result?.({ proposals: [proposal] });+ io.say(`recorded ${fitLine(proposal)}\nnext: nothing applies until the person reads the batch with pullboard spec fit and approves it with pullboard spec fit approve <batch>`);+ return 0;+ }+ if (!['edit', 'approve'].includes(verb) || (verb === 'approve' && args.length !== 1) || (verb === 'edit' && args.length !== 2)) throw new Refused('USAGE', usage);+ refuseOwnFit(ctx.info.commonDir, agentSessionDigest());+ requirePersonChannel(io.personChannel);+ const person = whoAmI(ctx, board);+ if (!ctx.info.isMain || person.id !== COORDINATOR) throw new Refused('B26_PERSON_APPROVAL', 'only the person, from the main checkout, edits or approves blueprint fit proposals; use pullboard spec fit to read them');+ if (verb === 'edit') {+ const proposal = editFit(ctx.info.commonDir, { target: args[0], decision: args[1], text: values.text, reason: values.reason, at });+ io.say(`edited ${fitLine(proposal)}`);+ // The whole batch is shown again, so the person reads what they will approve.+ return show({ edited: proposal });+ }+ const commit = headCommit(ctx.info.root) ?? '';+ const done = await approveFit({ commonDir: ctx.info.commonDir, spec, items, session: agentSessionDigest(), at, code: args[0] }, {+ decide: async (rows) => await ordered(ctx, board, 'recordRowDecisions', [{ agentId: store.PERSON, channel: io.personChannel ?? 'terminal',+ decisions: rows.flatMap(({ proposal, note }) => prepareRowDecisions(ctx.info.root, ctx.config, { ids: [proposal.target], decision: proposal.decision === 'drop' ? 'decline' : 'approve',+ reason: proposal.reason, text: proposal.text ?? undefined, on: at, commit, note })) }]),+ fact: async (id, text) => await ordered(ctx, board, 'appendFact', [id, { agentId: person.id, kind: 'decision', text }]),+ criterion: async (id, text) => await ordered(ctx, board, 'editItem', [id, { agentId: person.id, criterion: text }]),+ withdraw: async (id, reason) => await ordered(ctx, board, 'withdraw', [id, { agentId: person.id, reason }]),+ });+ io.result?.(done); done.proposals.forEach((proposal) => io.say(`approved ${fitLine(proposal)}`));+ if (done.decisions.length) io.say('next: the coordinator runs pullboard spec apply to write the row decisions');+ return 0;+}diff --git a/src/blueprint-fit.js b/src/blueprint-fit.jsnew file mode 100644index 00000000..48f59a64--- /dev/null+++ b/src/blueprint-fit.js@@ -0,0 +1,508 @@+/**+ * Blueprint fit: after a blueprint lands, a seat proposes how each drafted row, question and+ * starter item fits this repo, and the person approves every proposal as one batch [S1,E3].+ *+ * A proposal is keep, adapt (with the new text), drop (with a reason) or, for a question the repo+ * already settles, answer (with one of its choices). Proposals wait in one file in the git common+ * dir, beside the board, so every worktree of this clone records into the same batch and the+ * person sees them all from the main checkout. Nothing in SPEC.md or on the board changes until+ * the person approves: then each row proposal becomes the person's own row decision (the usual+ * pending apply), each starter adaptation becomes the item's new criterion and each starter drop+ * withdraws it, and every one keeps its reason and its blueprint source.+ *+ * The proposer is the seat's own identity, read by the caller from the board, and the seat's agent+ * session digest; no flag sets either. Any local process can still edit the file, so a proposal is+ * an unverified draft and is always shown as one, with its recorder named as recorded, never as+ * authenticated. The durable record is the person's batch approval on the board. Approval is the+ * person's alone: it refuses an agent session that recorded any proposal in the batch, then every+ * agent shell, remote shell and worktree, then any difference from what the person last read.+ *+ * The person's reading is bound by the person's own hand, not by a file: every listing prints a+ * batch code, a digest of each proposal's id, target and content, and approve takes that code as+ * its argument. The reading file beside the batch only lets a refusal name what differs; approve+ * first checks that the stored reading still hashes to the code the person typed, so a forged or+ * rewritten reading is refused, and only then compares it with the batch, entry by entry: a+ * proposal read but now missing, new since the reading, or changed is refused by name. Like a+ * person's row decision, which is trusted because the person's own channel records it, the+ * approval rests on input only the person gives; anything an agent can write is only a draft.+ */+import { createHash, randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { blueprintMarker, questionText, ruleText } from './blueprints.js';+import { requirePersonChannel } from './person.js';+import { Refused } from './refused.js';++/** What a fit proposal can say about one target. */+export const FIT_DECISIONS = Object.freeze(['keep', 'adapt', 'drop', 'answer']);++/** The proposer a person's own edit records. */+const PERSON = 'person';++/**+ * Where this clone's fit proposals wait: beside the board in the git common dir, so every worktree+ * reads and writes the same batch.+ *+ * @param {string} commonDir+ * @returns {string}+ */+export function fitFile(commonDir) {+ return join(commonDir, 'pullboard', 'blueprint-fit.json');+}++/**+ * Every fit proposal recorded in this clone, waiting or decided, oldest first. A missing file holds+ * none; a file that is not a proposal list is refused rather than read as empty, so a damaged batch+ * is never approved as a smaller one.+ *+ * @param {string} commonDir+ * @returns {any[]}+ */+export function readFit(commonDir) {+ const file = fitFile(commonDir);+ if (!existsSync(file)) return [];+ let value;+ try { value = JSON.parse(readFileSync(file, 'utf8')); }+ catch (error) { throw new Refused('FIT_FILE', `${file} is not readable JSON (${error.message.split('\n')[0]})`); }+ if (!value || value.version !== 1 || !Array.isArray(value.proposals)) throw new Refused('FIT_FILE', `${file} is not a blueprint fit file`);+ // Every proposal has its own id. Two sharing one could let an unread proposal pass as the read+ // one, so a batch with any shared id is refused, naming every target that shares it.+ const seen = new Map();+ for (const proposal of value.proposals) seen.set(proposal?.id, [...(seen.get(proposal?.id) ?? []), proposal?.target]);+ const shared = [...seen.values()].filter((targets) => targets.length > 1).flat();+ if (shared.length) {+ throw new Refused('FIT_FILE', `${shared.join(', ')} share a proposal id in ${file}, so the blueprint fit batch cannot be read or approved`,+ `remove ${file} and have the seats record their proposals again with pullboard blueprint fit`);+ }+ return value.proposals;+}++/**+ * Replace the whole proposal list by rename, so a reader never sees half a batch.+ *+ * @param {string} commonDir+ * @param {any[]} proposals+ */+function writeFit(commonDir, proposals) {+ const file = fitFile(commonDir);+ mkdirSync(dirname(file), { recursive: true });+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;+ writeFileSync(temp, `${JSON.stringify({ version: 1, proposals }, null, 2)}\n`);+ renameSync(temp, file);+}++/**+ * The proposals that wait for the person.+ *+ * @param {string} commonDir+ * @returns {any[]}+ */+export function pendingFit(commonDir) {+ return readFit(commonDir).filter((proposal) => proposal.state === 'proposed');+}++/**+ * The blueprint's drafted rows, questions and open starter items as they sit on this board, by the+ * name a seat uses for them: a row id such as W3, or #12 for an item. A rule matches its row by+ * exact text in its own section, or as a unique shared draft from an earlier blueprint; a question+ * by its ask and choices, whatever default it landed with; a starter by its title and cited rows.+ * A row or item that has moved on (approved, reworded, claimed) is no longer a target.+ *+ * @param {import('./blueprints.js').Blueprint} blueprint+ * @param {{ rows: any[], sections: { name: string }[] }} spec+ * @param {any[]} items - The board's items as store.listItems returns them.+ * @returns {Map<string, { kind: string, key: string, target: string, source: string, current: string, ask?: string, choices?: string[] }>}+ */+export function fitTargets(blueprint, spec, items) {+ const section = spec.sections.find((entry) => entry.name.replace(/^[A-Z][A-Z0-9]*\s*[·.:-]\s*/u, '') === blueprint.title.trim());+ const targets = new Map();+ const ownRows = section ? spec.rows.filter((row) => row.section === section.name) : [];+ /** Prefer this blueprint's section; otherwise accept only a unique shared row on the board. */+ const findDraft = (matches) => {+ const inRows = (rows) => rows.filter((row) => row.status === matches.status && matches.test(row));+ const own = inRows(ownRows);+ if (own.length === 1) return own[0];+ if (own.length > 1) return undefined;+ const shared = inRows(spec.rows);+ return shared.length === 1 ? shared[0] : undefined;+ };+ const ids = {};+ for (const rule of blueprint.rules) {+ const text = ruleText(rule);+ const row = findDraft({ status: 'draft', test: (entry) => entry.text === text });+ if (!row) continue;+ ids[rule.key] = row.id;+ targets.set(row.id, { kind: 'rule', key: rule.key, target: row.id, source: ruleText(rule), current: row.text });+ }+ for (const question of blueprint.questions) {+ const choices = question.choices.map((choice) => choice.trim());+ const row = findDraft({ status: 'pending', test: (entry) => entry.text.startsWith(`${question.ask.trim()}: `)+ && entry.text.endsWith(`. Choices: ${choices.join(', ')}.`) });+ if (!row) continue;+ ids[question.key] = row.id;+ targets.set(row.id, { kind: 'question', key: question.key, target: row.id, source: questionText(question), current: row.text, ask: question.ask.trim(), choices });+ }+ for (const starter of blueprint.items) {+ const cites = starter.cites.map((key) => ids[key]).filter(Boolean).join(',');+ const item = items.find((entry) => entry.item_status === 'open' && entry.item_title === starter.title.trim() && (entry.item_spec_ids ?? '') === cites);+ if (!item) continue;+ const source = `${starter.title.trim()}${starter.criterion ? `; criterion: ${starter.criterion}` : ''}`;+ targets.set(`#${item.item_id}`, { kind: 'item', key: starter.key, target: `#${item.item_id}`, source, current: item.item_criterion ?? '' });+ }+ return targets;+}++/**+ * Check one proposal against its target and give the text it would apply: the new row text, the+ * answered question's row text or the item's new criterion, or null for keep and drop.+ *+ * @param {{ kind: string, target: string, ask?: string, choices?: string[] }} target+ * @param {{ decision?: string, text?: string, reason?: string }} proposal+ * @returns {{ decision: string, text: string | null, reason: string }}+ */+function checkProposal(target, { decision, text, reason }) {+ const line = (value) => typeof value === 'string' && value.trim() && !/[\r\n|]/u.test(value);+ if (!FIT_DECISIONS.includes(decision)) throw new Refused('USAGE', `say how ${target.target} fits: keep, adapt, drop or answer`);+ if (reason !== undefined && !line(reason)) throw new Refused('FIT_PROPOSAL', 'a reason is one nonempty line without a | character');+ if (['adapt', 'drop', 'answer'].includes(decision) && reason === undefined) {+ throw new Refused('FIT_PROPOSAL', `a ${decision} proposal keeps its reason; add --reason "why it fits this repo that way"`);+ }+ if (['keep', 'drop'].includes(decision)) {+ if (text !== undefined) throw new Refused('FIT_PROPOSAL', `a ${decision} proposal takes no --text; use adapt to change the wording`);+ return { decision, text: null, reason: reason?.trim() ?? '' };+ }+ if (!line(text)) throw new Refused('FIT_PROPOSAL', `an ${decision} proposal needs --text, one nonempty line without a | character`);+ if (decision === 'adapt') return { decision, text: text.trim(), reason: reason.trim() };+ if (target.kind !== 'question') throw new Refused('FIT_PROPOSAL', `${target.target} is no question; only a question takes an answer, so use keep, adapt or drop`);+ if (!target.choices.includes(text.trim())) throw new Refused('FIT_PROPOSAL', `${text.trim()} is not one of ${target.target}'s choices (${target.choices.join(', ')})`);+ return { decision, text: questionText({ ask: target.ask, choices: target.choices, default: text.trim() }), reason: reason.trim() };+}++/**+ * Record a seat's fit proposal for one target of a blueprint this board has fully added. A later+ * proposal for the same target replaces the waiting one; nothing else changes.+ *+ * @param {{ commonDir: string, blueprint: import('./blueprints.js').Blueprint, specSource: string, spec: any, items: any[], by: string, session: string | null, at: string }} where+ * @param {{ target?: string, decision?: string, text?: string, reason?: string }} proposal+ * @returns {any} the recorded proposal+ */+export function proposeFit({ commonDir, blueprint, specSource, spec, items, by, session, at }, { target, decision, text, reason }) {+ if (!specSource.split(/\r?\n/u).some((line) => line.trim() === blueprintMarker(blueprint))) {+ throw new Refused('BLUEPRINT_NOT_ADDED', `${blueprint.name} version ${blueprint.version} is not fully added to this board`);+ }+ const targets = fitTargets(blueprint, spec, items);+ const found = targets.get(String(target ?? '').trim());+ if (!found) {+ throw new Refused('FIT_TARGET', `${target ?? 'nothing'} is no drafted row, question or open starter of ${blueprint.name} here; targets: ${[...targets.keys()].join(', ') || 'none left'}`);+ }+ const checked = checkProposal(found, { decision, text, reason });+ return saveProposal(commonDir, { id: randomUUID(), blueprint: { name: blueprint.name, version: blueprint.version }, ...found, ...checked, by, session, at, state: 'proposed' });+}++/**+ * The person's edit of a waiting proposal: the same target and blueprint source, a new decision,+ * text or reason, recorded as the person's own proposal.+ *+ * @param {string} commonDir+ * @param {{ target?: string, decision?: string, text?: string, reason?: string, at: string }} edit+ * @returns {any} the edited proposal+ */+export function editFit(commonDir, { target, decision, text, reason, at }) {+ const waiting = pendingFit(commonDir).find((proposal) => proposal.target === String(target ?? '').trim());+ if (!waiting) throw new Refused('FIT_TARGET', `no fit proposal waits for ${target ?? 'that target'}; read the batch with pullboard spec fit`);+ const checked = checkProposal(waiting, { decision, text, reason });+ // The caller shows the whole batch again after an edit, so the person reads what they approve.+ return saveProposal(commonDir, { ...waiting, id: randomUUID(), ...checked, by: PERSON, session: null, at, editedFrom: waiting.id });+}++/**+ * Put one waiting proposal in the file, replacing any proposal still waiting for its target.+ *+ * @param {string} commonDir+ * @param {any} proposal+ * @returns {any}+ */+function saveProposal(commonDir, proposal) {+ const all = readFit(commonDir).map((entry) => (entry.state === 'proposed' && entry.target === proposal.target ? { ...entry, state: 'replaced', replacedBy: proposal.id } : entry));+ writeFit(commonDir, [...all, proposal]);+ return proposal;+}++/**+ * Where a proposal came from, as one line: the blueprint, its version, its key and its text.+ *+ * @param {any} proposal+ * @returns {string}+ */+export function fitSource(proposal) {+ return `${proposal.blueprint.name} v${proposal.blueprint.version} ${proposal.kind === 'item' ? 'starter' : proposal.kind} ${proposal.key}: ${proposal.source}`;+}++/**+ * One proposal as the person reads it: target, decision, proposer, new text, reason and source.+ *+ * @param {any} proposal+ * @returns {string}+ */+export function fitLine(proposal) {+ return `${proposal.target} ${proposal.decision} (unverified draft, recorded as ${proposal.by})${proposal.text ? `: ${proposal.text}` : ''}`+ + `${proposal.reason ? `; reason: ${proposal.reason}` : ''}; blueprint source: ${fitSource(proposal)}`;+}++/**+ * The lines pullboard spec prints for the waiting batch, or none: every proposal, then the batch+ * code the person approves this exact batch with.+ *+ * @param {{ proposals: any[], batch: string }} read - From readFitBatch.+ * @returns {string[]}+ */+export function fitSummary({ proposals, batch }) {+ if (!proposals.length) return [];+ return [`blueprint fit: ${proposals.length} unverified draft ${proposals.length === 1 ? 'proposal waits' : 'proposals wait'} for the person; nothing applies until the person approves the batch`,+ ...proposals.map((proposal) => ` ${fitLine(proposal)}`),+ `the person edits one with pullboard spec fit edit <target> keep|adapt|drop|answer, or approves exactly this batch with pullboard spec fit approve ${batch}`];+}++/**+ * The note a decision keeps: what the person approved, why, and where it came from.+ *+ * @param {any} proposal+ * @returns {string}+ */+function fitNote(proposal) {+ return `blueprint fit ${proposal.decision}${proposal.reason ? `: ${proposal.reason}` : ''}; recorded as ${proposal.by}, unverified; blueprint source: ${fitSource(proposal)}`;+}++/**+ * The person approves every waiting proposal as one batch. Each target must still read as it did+ * when proposed. Row proposals become one set of the person's row decisions (keep and adapt and+ * answer approve, drop declines with its reason), each with a note keeping the reason and the+ * blueprint source; then starter adaptations set the item's criterion and starter drops withdraw+ * it, each after a fact on the item keeping the same note. The batch is marked approved last.+ *+ * @param {{ commonDir: string, spec: any, items: any[], session: string | null, at: string, code: string }} where - code is the batch code the person typed+ * @param {{ decide: (rows: { proposal: any, note: string }[]) => Promise<any[]>, fact: (id: number, text: string) => Promise<any>, criterion: (id: number, text: string) => Promise<any>, withdraw: (id: number, reason: string) => Promise<any> }} moves+ * @returns {Promise<{ proposals: any[], decisions: any[], items: { id: number, decision: string }[] }>}+ */+export async function approveFit({ commonDir, spec, items, session, at, code }, moves) {+ const batch = refuseOwnFit(commonDir, session);+ refuseUnreadFit(commonDir, batch, code);+ if (!batch.length) throw new Refused('NO_FIT_PROPOSALS', 'no blueprint fit proposals wait for the person');+ return await approveBatch({ commonDir, spec, items, at, batch }, moves);+}++/**+ * Refuse an agent session that recorded any waiting proposal, before any other check reads the+ * caller: a seat never approves or edits its own proposal, whatever channel it comes through.+ * Returns the waiting batch.+ *+ * @param {string} commonDir+ * @param {string | null} session - The caller's agent session digest, or null outside an agent shell.+ * @returns {any[]}+ */+export function refuseOwnFit(commonDir, session) {+ const batch = pendingFit(commonDir);+ const own = session && batch.find((proposal) => proposal.session === session);+ if (own) throw new Refused('FIT_OWN_PROPOSAL', `this agent session recorded ${own.target}'s fit proposal as ${own.by}; a seat never approves its own proposal`);+ return batch;+}++/**+ * Apply an already-authorized batch; see approveFit.+ *+ * @param {{ commonDir: string, spec: any, items: any[], at: string, batch: any[] }} where+ * @param {any} moves+ * @returns {Promise<{ proposals: any[], decisions: any[], items: { id: number, decision: string }[] }>}+ */+async function approveBatch({ commonDir, spec, items, at, batch }, moves) {+ const stale = batch.filter((proposal) => {+ const item = proposal.kind === 'item' && items.find((entry) => `#${entry.item_id}` === proposal.target && entry.item_status === 'open');+ const now = proposal.kind === 'item'+ ? (item ? item.item_criterion ?? '' : null)+ : spec.rows.find((row) => row.id === proposal.target && ['draft', 'pending'].includes(row.status))?.text ?? null;+ return now !== proposal.current;+ });+ if (stale.length) {+ // The batch no longer matches the board, so none of it applies; the stale proposals leave the+ // batch, so the person can read what is left and approve that.+ const ids = new Set(stale.map((proposal) => proposal.id));+ writeFit(commonDir, readFit(commonDir).map((entry) => (ids.has(entry.id) ? { ...entry, state: 'stale', staleAt: at } : entry)));+ throw new Refused('FIT_STALE', `${stale.map((proposal) => proposal.target).join(', ')} changed after its fit proposal, so nothing in the batch was applied and those proposals left it`,+ 'read what is left with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>');+ }+ const rows = batch.filter((proposal) => proposal.kind !== 'item');+ const decisions = rows.length ? await moves.decide(rows.map((proposal) => ({ proposal, note: fitNote(proposal) }))) : [];+ const changed = [];+ for (const proposal of batch.filter((entry) => entry.kind === 'item' && entry.decision !== 'keep')) {+ const id = Number(proposal.target.slice(1));+ await moves.fact(id, `The person approved this blueprint fit: ${fitNote(proposal)}`);+ if (proposal.decision === 'adapt') await moves.criterion(id, proposal.text);+ else await moves.withdraw(id, `blueprint fit drop: ${proposal.reason}`);+ changed.push({ id, decision: proposal.decision });+ }+ const approved = new Set(batch.map((proposal) => proposal.id));+ const events = new Map(decisions.map((record) => [record.id, record.event]));+ const after = readFit(commonDir).map((entry) => (approved.has(entry.id)+ ? { ...entry, state: 'approved', approvedBy: PERSON, approvedAt: at, ...(events.has(entry.target) ? { decisionEvent: events.get(entry.target) } : {}) }+ : entry));+ writeFit(commonDir, after);+ return { proposals: after.filter((entry) => approved.has(entry.id)), decisions, items: changed };+}++/**+ * Show the waiting batch in the shared view state: each row a proposal names carries it and a+ * stage saying it waits for the person, unless the person already decided that row; each starter+ * carries its proposal; and the state lists the whole batch as fit.+ *+ * @param {any[]} proposals - From pendingFit.+ * @param {any} state - The API state, after row decisions are projected.+ * @returns {any}+ */+export function projectFit(proposals, state) {+ if (!proposals.length) return state;+ // A recorder is shown only as recorded, never as an authenticated author, and no session digest leaves.+ const drafts = proposals.map(({ by, session, ...proposal }) => ({ ...proposal, recordedAs: by, verified: false }));+ const byTarget = new Map(drafts.map((proposal) => [proposal.target, proposal]));+ return { ...state,+ fit: drafts,+ spec: state.spec.map((row) => (byTarget.has(row.id) && !row.decision+ ? { ...row, fit: byTarget.get(row.id), stage: `fit draft, unverified: ${byTarget.get(row.id).decision}, waits for the person` } : row)),+ items: state.items.map((item) => (byTarget.has(`#${item.id}`) ? { ...item, fit: byTarget.get(`#${item.id}`) } : item)),+ };+}++/**+ * The digest of what a proposal says, so a reading can tell later whether it changed.+ *+ * @param {any} proposal+ * @returns {string}+ */+export function fitDigest(proposal) {+ const { id, blueprint, kind, key, target, source, current, decision, text, reason, by } = proposal;+ return createHash('sha256').update(JSON.stringify({ id, blueprint, kind, key, target, source, current, decision, text, reason, by })).digest('hex');+}++/**+ * Where the person's last reading is kept, so a refusal can name what differs from it. It is no+ * proof of anything by itself: approve checks it against the batch code the person typed.+ *+ * @param {string} commonDir+ * @returns {string}+ */+function viewedFile(commonDir) {+ return join(commonDir, 'pullboard', 'blueprint-fit-viewed.json');+}++/**+ * Each proposal of a batch as a reading holds it, one entry per proposal and never merged by id:+ * its id, its target and its digest, in id then digest order.+ *+ * @param {any[]} proposals+ * @returns {{ id: string, target: string, digest: string }[]}+ */+function readingOf(proposals) {+ const entries = proposals.map((proposal) => ({ id: String(proposal.id), target: String(proposal.target), digest: fitDigest(proposal) }));+ return entries.sort((a, b) => (a.id === b.id ? (a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0) : a.id < b.id ? -1 : 1));+}++/**+ * The batch code of a reading: a short digest of every entry's id, target and proposal digest, each+ * entry on its own. The person approves by typing it, which binds the approval to exactly what+ * they read.+ *+ * @param {{ id: string, target: string, digest: string }[]} reading+ * @returns {string}+ */+export function batchCode(reading) {+ const entries = reading.map((entry) => [entry?.id, entry?.target, entry?.digest]);+ return createHash('sha256').update(JSON.stringify(entries)).digest('hex').slice(0, 12);+}++/**+ * The person's last reading, or null when there is none or it cannot be read.+ *+ * @param {string} commonDir+ * @returns {{ id: string, target: string, digest: string }[] | null}+ */+function readViewed(commonDir) {+ const file = viewedFile(commonDir);+ if (!existsSync(file)) return null;+ let value;+ try { value = JSON.parse(readFileSync(file, 'utf8')); }+ catch (error) {+ if (!(error instanceof SyntaxError)) throw error;+ // A damaged reading is no reading; approve refuses it and the person reads the batch again.+ return null;+ }+ const reading = value?.reading;+ const entry = (item) => item && ['id', 'target', 'digest'].every((key) => typeof item[key] === 'string');+ return Array.isArray(reading) && reading.every(entry) ? reading : null;+}++/**+ * The waiting batch for a reader, with its batch code. When the reader is the person, in the main+ * checkout's own terminal, this listing is the person's reading and replaces the last one. An+ * agent, a remote shell or a worktree sees the batch and its code without it counting as read.+ *+ * @param {string} commonDir+ * @param {{ isMain: boolean, channel?: string, at?: string }} reader+ * @returns {{ proposals: any[], batch: string }}+ */+export function readFitBatch(commonDir, { isMain, channel, at = new Date().toISOString() }) {+ const proposals = pendingFit(commonDir);+ const reading = readingOf(proposals);+ if (isMain && isPersonTerminal(channel)) {+ const file = viewedFile(commonDir);+ mkdirSync(dirname(file), { recursive: true });+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;+ writeFileSync(temp, `${JSON.stringify({ version: 1, at, reading }, null, 2)}\n`);+ renameSync(temp, file);+ }+ return { proposals, batch: batchCode(reading) };+}++/**+ * True when this terminal is the person's own, by the same rule person moves use.+ *+ * @param {string | undefined} channel+ * @returns {boolean}+ */+function isPersonTerminal(channel) {+ try { requirePersonChannel(channel ?? 'terminal'); return channel !== 'view'; }+ catch (error) {+ if (error instanceof Refused) return false;+ throw error;+ }+}++/**+ * Refuse unless the batch is exactly what the person last read. The stored reading must hash to+ * the code the person typed, or it was rewritten after the reading (FIT_READING). Then every id+ * the person read must still wait with the same digest, and nothing may wait that they did not+ * read (FIT_CHANGED, naming each). Nothing is written on either refusal.+ *+ * @param {string} commonDir+ * @param {any[]} batch+ * @param {string} code+ */+function refuseUnreadFit(commonDir, batch, code) {+ const reading = readViewed(commonDir);+ if (!reading || batchCode(reading) !== String(code ?? '').trim()) {+ throw new Refused('FIT_READING', `${code ?? 'no batch code'} is not the batch code of your last reading of the blueprint fit batch, or that reading was changed since; nothing was approved`,+ 'read the batch again with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>');+ }+ const now = readingOf(batch);+ // Compared entry by entry, never merged by id: a shared id, on either side, is itself a difference.+ const count = (entries) => entries.reduce((ids, entry) => ids.set(entry.id, (ids.get(entry.id) ?? 0) + 1), new Map());+ const [readIds, nowIds] = [count(reading), count(now)];+ const named = [+ ...reading.filter((entry) => !nowIds.has(entry.id)).map((entry) => `${entry.target} (gone)`),+ ...now.filter((entry) => !readIds.has(entry.id)).map((entry) => `${entry.target} (new)`),+ ...now.filter((entry) => readIds.has(entry.id) && !reading.some((read) => read.id === entry.id && read.digest === entry.digest)).map((entry) => `${entry.target} (changed)`),+ ...[...reading, ...now].filter((entry) => readIds.get(entry.id) > 1 || nowIds.get(entry.id) > 1).map((entry) => `${entry.target} (shared id)`),+ ];+ if (named.length) {+ throw new Refused('FIT_CHANGED', `${named.join(', ')} differ from your last reading of the blueprint fit batch, so nothing was approved`,+ 'read the batch again with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>');+ }+}diff --git a/src/cli.js b/src/cli.jsindex 6bd21cbe..129c4273 100644--- a/src/cli.js+++ b/src/cli.js@@ -63,6 +63,8 @@ import {unmetRows,} from './spec.js';import { answerQuestion, bundledBlueprints, landBlueprint, planBlueprint, readBlueprint, repoAnswers, saveBlueprint } from './blueprints.js';+import { fitCommand } from './blueprint-fit-command.js';+import { fitSummary, readFitBatch } from './blueprint-fit.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';@@ -2943,6 +2945,7 @@ function workCommands(io, args) {};return {blueprint: () => act(async (ctx, board, me) => {+ if (first === 'fit') return await fitCommand(ctx, board, me, 'propose', [second, ...rest].filter((value) => value !== undefined), values, { ordered, whoAmI });const references = [...(second ? [second] : []), ...(values.blueprint ?? [])];if (first !== 'add' || !references.length || rest.length) throw new Refused('USAGE', `pullboard blueprint add <name or file> [--blueprint <name or file>]... | save [file]; bundled: ${bundledBlueprints().join(', ')}`);// Several blueprints land in the order given, as one result; one lands exactly as before (#720).@@ -3517,6 +3520,7 @@ async function specCommand(io, { first, second, rest, values }) {decline: ['reason'],answer: [],apply: [],+ fit: ['text', 'reason'],}[first ?? '--json'];if (!commandFlags) throw new Refused('USAGE', 'use pullboard spec --json | check | view | show <id> | unmet [--must] | draft "<text>" | signoff <ids> | approve <ids> | decline <ids> --reason "why" | answer <id> "<choice or text>" | apply');const allowedFlags = [...new Set([...commandFlags, 'json'])];@@ -3526,6 +3530,9 @@ async function specCommand(io, { first, second, rest, values }) {throw new Refused('FLAG_NOT_ALLOWED', `spec ${first ?? '--json'} does not take --${flag}; ${next}`);}}+ if (first === 'fit') {+ return await withBoard(ctx, async (board) => await fitCommand(ctx, board, null, second ?? 'list', rest, values, { ordered, whoAmI }));+ }const spec = loadSpec(ctx.info.root, ctx.config);if (!spec.exists) throw new Refused('NO_SPEC', `no ${ctx.config.spec}; run: pullboard init`);const practice = ctx.doctrine;@@ -3709,8 +3716,10 @@ async function specCommand(io, { first, second, rest, values }) {{ id, status, tier, text, gate, serves, signers, section, line, file: source ?? file,...(from === undefined ? {} : { source: from }), ...(origin ? { origin, version, reason } : {}) })));- io.result({ rows });+ const fit = readFitBatch(ctx.info.commonDir, { isMain: ctx.info.isMain, channel: io.personChannel });+ io.result({ rows, ...(fit.proposals.length ? { fit: fit.proposals, fitBatch: fit.batch } : {}) });} else messages.forEach((message) => io.say(message));+ if (!values.json) fitSummary(readFitBatch(ctx.info.commonDir, { isMain: ctx.info.isMain, channel: io.personChannel })).forEach((message) => io.say(message));return errors ? 1 : 0;}if (first === 'signers' && second === 'add') {diff --git a/src/help.js b/src/help.jsindex 8bb1eb48..d7eb8cd4 100644--- a/src/help.js+++ b/src/help.js@@ -187,6 +187,8 @@ Specpullboard blueprint add <name or file> [--blueprint <name or file>]... add a blueprint's rules and questions as drafts, and its starter itemsbundled: web-app; nothing is approved, and a repeat adds nothingseveral land in order: one product, one architecture, any practice; a shared rule is drafted once+ pullboard blueprint fit <name or file> <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"] propose this repo's fit; nothing applies yet+ pullboard spec fit [approve <batch>] | fit edit <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"] the person's fit batchpullboard blueprint save [file] [--name <name>] [--title "<title>"] write approved rules and answered questions as a blueprintnever items, notes, paths, emails or names; file defaults to <project>.blueprint.jsonpullboard spec signers add [--key <path>] [--by <principal>] opt into SSH-signed sign-offs@@ -220,7 +222,7 @@ const HELP_NAMES = ['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',- 'roadmap', 'milestone', 'runner', 'runner add', 'blueprint', 'blueprint add', 'blueprint save',+ 'roadmap', 'milestone', 'runner', 'runner add', 'blueprint', 'blueprint add', 'blueprint fit', 'blueprint save', 'spec fit',];const HELP_GROUPS = [@@ -259,6 +261,8 @@ const HELP_EXAMPLES = {'spec view': 'pullboard spec view', 'spec show': 'pullboard spec show G1','spec draft': 'pullboard spec draft "Describe the first requirement"','blueprint add': 'pullboard blueprint add web-app', 'blueprint save': 'pullboard blueprint save',+ 'blueprint fit': 'pullboard blueprint fit web-app G1 keep --reason "the repository already meets this row"',+ 'spec fit': 'pullboard spec fit','spec unmet': 'pullboard spec unmet', 'spec signoff': 'pullboard spec signoff G1','spec signers add': 'pullboard spec signers add', help: 'pullboard help claim', version: 'pullboard --version',};@@ -274,8 +278,10 @@ const HELP_ALIASES = {lifecycle: { usage: 'pullboard lifecycle', source: null },escalate: { usage: 'pullboard escalate <id> --note "..." [--note-file <file>]', source: 'escalate <id> --note "what was tried and how it failed"', extraFlags: ['--note-file <file>'] },'view export': { usage: 'pullboard view --export <dir>', source: 'view' },- blueprint: { usage: 'pullboard blueprint add <name or file> [--blueprint <name or file>]...', source: 'blueprint add' },+ blueprint: { usage: 'pullboard blueprint add <name or file>, then a seat runs pullboard blueprint fit <name or file> <row id or #item> keep|adapt|drop|answer, then the person runs pullboard spec fit approve <batch>', source: 'blueprint add' },'blueprint add': { usage: 'pullboard blueprint add <name or file> [--blueprint <name or file>]...', source: 'blueprint add' },+ 'blueprint fit': { usage: 'pullboard blueprint fit <name or file> <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"]', source: null, onlyFlags: ['--text', '--reason'] },+ 'spec fit': { usage: 'pullboard spec fit [approve <batch>] | fit edit <row id or #item> keep|adapt|drop|answer [--text "..."] [--reason "why"]', source: null, onlyFlags: ['--text', '--reason'] },'spec check': { usage: 'pullboard spec check', source: 'spec check' },'spec view': { usage: 'pullboard spec view [--out file]', source: 'spec view' },'spec show': { usage: 'pullboard spec show <id>', source: 'spec show', onlyFlags: [] },diff --git a/src/json.js b/src/json.jsindex c638a6ce..4c70f6ce 100644--- a/src/json.js+++ b/src/json.js@@ -85,6 +85,8 @@ export const JSON_SHAPES = {'spec show': shape({ row: 'object', standing: 'object' }),'spec draft': shape({ id: 'string', row: 'object' }),'blueprint add': shape({ blueprint: 'object', section: 'string', rows: 'array', items: 'array', gate: 'string|null', proposedLanes: 'array' }),+ 'blueprint fit': shape({ proposals: 'array' }),+ 'spec fit': shape({ proposals: 'array' }),'spec unmet': shape({ rows: 'array' }),'spec signoff': shape({ count: 'number', by: 'string', ids: 'array', evidence: 'array' }),'spec signers': shape({ added: 'boolean', by: 'string', path: 'string', initial: 'boolean' }),diff --git a/src/needs-state.js b/src/needs-state.jsindex 3095adec..659656b8 100644--- a/src/needs-state.js+++ b/src/needs-state.js@@ -3,6 +3,7 @@ import { join } from 'node:path';import * as store from './board.js';import { repoInfo } from './git.js';import { projectRowDecisions } from './row-decisions.js';+import { pendingFit, projectFit } from './blueprint-fit.js';import { projectState } from './serve.js';/** Borrow an existing connection or open a read-only one; retain exact row-decision matching. */@@ -10,7 +11,7 @@ export function personNeedsState(root, { board: providedBoard = null } = {}) {const info = repoInfo(root);const board = providedBoard ?? { db: store.openBoardReadOnly(join(info.commonDir, 'pullboard', 'board.sqlite')) };try {- return projectRowDecisions(store.rowDecisions(board), projectState(root, { board }));+ return projectFit(pendingFit(info.commonDir), projectRowDecisions(store.rowDecisions(board), projectState(root, { board })));} finally {if (!providedBoard) store.closeBoard(board);}diff --git a/src/next-steps.js b/src/next-steps.jsindex 05e5911a..86c15f04 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -71,6 +71,7 @@ export const NEXT_STEPS = Object.freeze({BLUEPRINT_EXISTS: 'choose a file that does not exist: pullboard blueprint save <new-file>',BLUEPRINT_ITEM_UNCHECKED: 'give the starter item named in the message a criterion and a check command, then run pullboard blueprint add <file> again',BLUEPRINT_KIND_TAKEN: 'keep at most one product and one architecture blueprint, then run the same command again',+ BLUEPRINT_NOT_ADDED: 'add the blueprint to this board first: pullboard blueprint add <name or file>',BLUEPRINT_NO_SOURCE: 'give the rule named in the message the reference it paraphrases as source { name, id, url }, then run pullboard blueprint add <file> again',BLUEPRINT_URL: 'download and read the blueprint yourself, then run pullboard blueprint add <local-file>',BOARD_BUSY: 'wait for the other pullboard process to finish, then retry',@@ -125,6 +126,14 @@ export const NEXT_STEPS = Object.freeze({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',+ FIT_CHANGED: 'read the batch again with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>',+ FIT_READING: 'read the batch again with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>',+ FIT_FILE: 'restore or remove .git/pullboard/blueprint-fit.json, then have the seat record its proposals again with pullboard blueprint fit',+ FIT_OWN_PROPOSAL: 'ask the person to approve the batch: pullboard spec fit approve <batch>',+ FIT_PROPOSAL: 'retry with keep, adapt --text "<new text>" --reason "why", drop --reason "why", or answer --text "<choice>"',+ FIT_STALE: 'read what is left with pullboard spec fit, then approve it with the batch code it prints: pullboard spec fit approve <batch>',+ FIT_TARGET: 'pick a target the message lists, or read the waiting batch with pullboard spec fit',+ NO_FIT_PROPOSALS: 'have a seat record proposals with pullboard blueprint fit <name or file> <target> keep|adapt|drop|answer',EMPTY_NOTE: 'say why: pullboard pass <id> --note "<reason>"',EMPTY_SHOUT: 'give the shout text: pullboard shout <to> "<text>"',EMPTY_SIGNERS: 'restore the signer list from Git: git restore --source=HEAD -- .pullboard/signers',diff --git a/src/row-decisions.js b/src/row-decisions.jsindex e7addd9a..827894d9 100644--- a/src/row-decisions.js+++ b/src/row-decisions.js@@ -28,7 +28,7 @@ function decisionRows(root, config, ids) {* a pending question is an approval of its answered text and carries no separate answer field: the* answer shown is read back from the signed source and text by decisionAnswer.*/-export function prepareRowDecisions(root, config, { ids, decision, reason = '', text: proposedText, by, on, commit = '' }) {+export function prepareRowDecisions(root, config, { ids, decision, reason = '', text: proposedText, by, on, commit = '', note = '' }) {if (!ids.length) throw new Refused('USAGE', 'name rows: pullboard spec approve <ids> or spec decline <ids> --reason "why"');if (!['approve', 'decline'].includes(decision)) throw new Refused('ROW_DECISION', 'use pullboard spec approve or decline');if (decision === 'decline' && (!reason.trim() || /[\r\n|]/u.test(reason))) throw new Refused('ROW_DECISION', 'a decline needs a one-line reason without a field separator; use --reason "why"');@@ -40,7 +40,7 @@ export function prepareRowDecisions(root, config, { ids, decision, reason = '',const text = decision === 'approve' ? proposedText?.trim() ?? row.text : row.text;const replacement = source.replace(/\[([a-z]+)(,\s*[a-z]+)?\]/u, (_, old, tier = '') => `[${status}${tier}]`).replace(/(\]\s+)([^|]*)(?=\s*\||$)/u, (_, prefix, old) => `${prefix}${text}${old.match(/\s+$/u)?.[0] ?? ''}`);- const record = { version: 1, type: 'row-decision', kind, file, id: row.id, source, replacement, text, decision, reason: decision === 'decline' ? reason.trim() : '', by: principal, on, commit, note: '' };+ const record = { version: 1, type: 'row-decision', kind, file, id: row.id, source, replacement, text, decision, reason: decision === 'decline' ? reason.trim() : '', by: principal, on, commit, note };return signed ? signRowDecision(root, record) : record;});}diff --git a/src/templates.js b/src/templates.jsindex 2fa58cd5..0e974eda 100644--- a/src/templates.js+++ b/src/templates.js@@ -107,6 +107,8 @@ This repo runs on pullboard: a work board, lanes and a spec that live in git. No**Doctrine.** Our house rules for agentic development. This repo inherits Pullboard standard doctrine version 1. ${doctrine.repo ? doctrine.name : DOCTRINE_FILE} adds the repo's own rows, overrides a standard rule by its PB id, or declines it with a wont row and its reason as the row text: - PB7 [wont] <why>. Approved rows are in force; follow them as you would the spec. A rule with \`gate: check <command>\` and \`count: N\` holds a count that only falls: run pullboard doctrine check to see each count, and submit refuses RATCHET_ROSE when a touched rule rises or a changed file gains a problem. Lower \`count:\` in a commit when you fix problems; only the person raises it. Run pullboard spec --json to read the current merged rules. Re-run pullboard init after changing the doctrine to refresh this managed guidance.+**Fit a blueprint.** After \`blueprint add\`, a seat can propose how each drafted row, question and starter item fits this repository with \`pullboard blueprint fit <name or file> <row id or #item> keep|adapt|drop|answer\`. Include \`--text\` for adapted wording or an answer, and \`--reason\` for why. The proposals remain drafts until the person reads \`pullboard spec fit\` and approves that batch with its printed code; the proposer cannot approve their own batch.+### Current doctrine${doctrineText(doctrine)}diff --git a/test/api.test.js b/test/api.test.jsindex 488a852c..83141e28 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -1025,6 +1025,11 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>/** Exercise the agent-only takeover with a private explicit session, leaving later terminal calls markerless. */const sessionSource = { ...source, run: (cwd, ...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, env: { ...source.env, CODEX_SESSION_ID: 'api-catalog-session' }, encoding: 'utf8' }) };json(sessionSource, source.repo, 'takeover');+ const fitBlueprint = json(source, source.repo, 'blueprint', ['add', 'web-app'], 'add');+ const fitTarget = fitBlueprint.rows[0].id;+ const fitProposal = json(source, source.repo, 'blueprint', ['fit', 'web-app', fitTarget, 'keep'], 'fit');+ assert.equal(fitProposal.proposals[0].target, fitTarget);+ assert.equal(json(source, source.repo, 'spec', ['fit'], 'fit').proposals.length, 1);const lane = json(source, source.repo, 'lane', ['add', 'catalog', '--owns', 'catalog/'], 'add');assert.deepEqual([lane.lane, lane.owns], ['catalog', ['catalog/']]);assert.deepEqual(json(source, source.repo, 'lanes').lanes.catalog, { owns: ['catalog/'] });diff --git a/test/blueprint.test.js b/test/blueprint.test.jsindex af912298..c2cd1bf6 100644--- a/test/blueprint.test.js+++ b/test/blueprint.test.js@@ -1,5 +1,6 @@/** pullboard blueprint add: a blueprint lands on a board as drafts, once [S1,I1]. */import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { hostname, tmpdir } from 'node:os';import { join, resolve } from 'node:path';@@ -46,7 +47,7 @@ function freshBoard(config = {}) {writeFileSync(file, `${JSON.stringify({ ...JSON.parse(readFileSync(file, 'utf8')), ...config }, null, 2)}\n`);git('add', '-A');git('commit', '-q', '-m', 'chore: set up blueprint fixture');- return { dir, repo, run, runIn, git };+ return { dir, repo, run, runIn, git, env };}/** Run one command with --json and return its document, failing with its output. */@@ -901,6 +902,14 @@ test('init takes a product and an architecture blueprint together [S1,I1]', () =const own = rowsIn(practice)[0].id;assert.equal(byTitle(practice.items[0].title).item_spec_ids, [sharedRule, own, sharedQuestion].join(','), 'the shared starter cites the rows already drafted');+ const sharedProposal = json(box, 'blueprint', 'fit', practiceFile, sharedRule, 'keep');+ assert.deepEqual([sharedProposal.proposals[0].blueprint.name, sharedProposal.proposals[0].key, sharedProposal.proposals[0].target],+ ['house-rules', product.rules[0].key, sharedRule], 'a later blueprint can fit its shared row in the earlier section');+ const starterId = byTitle(practice.items[0].title).item_id;+ const starterProposal = json(box, 'blueprint', 'fit', practiceFile, `#${starterId}`, 'keep');+ assert.deepEqual([starterProposal.proposals[0].blueprint.name, starterProposal.proposals[0].target], ['house-rules', `#${starterId}`],+ 'the later starter can fit when it cites that shared row');+// blueprint add takes --blueprint more than once too, and each starter it files names its blueprint.const board = freshBoard();const added = json(board, 'blueprint', 'add', 'web-app', '--blueprint', 'serverless');@@ -1133,3 +1142,221 @@ test('blueprint save reads back a question with three or more choices [S1]', ()assert.deepEqual(rows.map((row) => [row.status, row.text]), questions.map((text) => ['pending', text]),'each question round-trips to its exact row text');});+++/** Hash the fields the person's blueprint-fit reading binds, without importing the feature under test. */+function fitDigest(proposal) {+ const { id, blueprint, kind, key, target, source, current, decision, text, reason, by } = proposal;+ return createHash('sha256').update(JSON.stringify({ id, blueprint, kind, key, target, source, current, decision, text, reason, by })).digest('hex');+}++/** Encode the reading's ordered ids, targets and digests as the short code the person approves. */+function batchCode(reading) {+ const entries = reading.map((entry) => [entry?.id, entry?.target, entry?.digest]);+ return createHash('sha256').update(JSON.stringify(entries)).digest('hex').slice(0, 12);+}++/**+ * A web-app board in a plain node --test repo, committed, with one agent seat joined in its own+ * worktree. seat runs a command there as that agent's session; as runs one in the main checkout+ * with any agent session, or as the person when session is null.+ */+function fitBoard() {+ const box = freshBoard({ lanes: { web: { owns: ['web/'] } } });+ writeFileSync(join(box.repo, 'package.json'), `${JSON.stringify({ name: 'lib', scripts: { test: 'node --test' } })}\n`);+ const added = json(box, 'blueprint', 'add', 'web-app');+ box.git('add', '-A');+ box.git('commit', '-q', '-m', 'chore: add the web-app blueprint');+ const worktree = join(box.dir, 'seat');+ box.git('worktree', 'add', '-q', worktree, '-b', 'web/fit');+ const as = (session, cwd, ...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, encoding: 'utf8',+ env: session ? { ...box.env, CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: session } : box.env });+ const seat = (...args) => as('fit-seat', worktree, ...args);+ const joined = seat('join', 'web', '--model', 'Fit Seat', '--json');+ assert.equal(joined.status, 0, joined.stdout + joined.stderr);+ const key = (name) => added.rows.find((row) => row.key === name).id;+ const starter = (name) => added.items.find((item) => item.key === name).id;+ return { box, worktree, seat, as, key, starter };+}++/** Run a command, require success, and return its JSON document. */+function ok(result, label) {+ assert.equal(result.status, 0, `${label}: ${result.stdout}${result.stderr}`);+ return JSON.parse(result.stdout);+}++/** Run a command, require a refusal, and return its code. */+function refusal(result, label) {+ assert.notEqual(result.status, 0, `${label} must be refused: ${result.stdout}`);+ return JSON.parse(result.stdout).error.code;+}++test('a fit proposal waits for the person and keeps its reason [S1,E3]', () => {+ const { box, seat, key, starter } = fitBoard();+ assert.match(box.run('help', 'blueprint').stdout, /^Usage: pullboard blueprint add <name or file>, then a seat runs pullboard blueprint fit .+, then the person runs pullboard spec fit approve <batch>$/mu, 'help blueprint names the fit step');+ const W1 = key('W1');+ const W2 = key('W2');+ const W3 = key('W3');+ const Q1 = key('Q1');+ const specBefore = readFileSync(join(box.repo, 'SPEC.md'), 'utf8');+ const criterionBefore = ok(box.run('show', String(starter('1')), '--json'), 'show').item_criterion;+ const adapted = 'Every change ships with a node:test test that fails without it. Why: one runner keeps the gate honest.';+ const proposals = [+ [W1, 'adapt', '--text', adapted, '--reason', 'this repo already tests with node --test'],+ [W2, 'keep'],+ [W3, 'drop', '--reason', 'this repo is a library with no pages'],+ [Q1, 'answer', '--text', 'Something else', '--reason', 'a plain node:test library with no web framework'],+ [`#${starter('1')}`, 'adapt', '--text', 'npm test runs node --test with one passing test', '--reason', 'the runner is already node:test'],+ [`#${starter('2')}`, 'drop', '--reason', 'there is no home page to fit to a phone'],+ ];+ const by = new Set();+ for (const args of proposals) {+ const recorded = ok(seat('blueprint', 'fit', 'web-app', ...args, '--json'), `fit ${args.join(' ')}`).proposals[0];+ by.add(recorded.by);+ }+ assert.equal(by.size, 1, 'one seat recorded every proposal');+ const seatId = [...by][0];+ assert.match(seatId, /^web-/u, "the proposer is the seat's own id");+ assert.equal(refusal(seat('blueprint', 'fit', 'web-app', W2, 'keep', '--by', 'person', '--json'), 'a flag naming the proposer'), 'FLAG_NOT_ALLOWED');+ assert.equal(refusal(seat('blueprint', 'fit', 'web-app', W3, 'drop', '--json'), 'a drop with no reason'), 'FIT_PROPOSAL');++ // Nothing applies before the person approves: SPEC.md, the row decisions and the starters are as they were.+ assert.equal(readFileSync(join(box.repo, 'SPEC.md'), 'utf8'), specBefore, 'SPEC.md is unchanged');+ for (const id of [W1, W2, W3, Q1]) assert.equal(ok(box.run('spec', 'show', id, '--json'), 'spec show').row.decision, undefined, `${id} has no decision yet`);+ const first = ok(box.run('show', String(starter('1')), '--json'), 'show');+ assert.equal(first.item_criterion, criterionBefore, 'the starter keeps its criterion');+ assert.equal(ok(box.run('show', String(starter('2')), '--json'), 'show').item_status, 'open', 'the dropped starter is still open');++ // The person sees every proposal together: in pullboard spec, and in the view's state.+ const listed = box.run('spec');+ assert.equal(listed.status, 0, listed.stdout + listed.stderr);+ assert.match(listed.stdout, /blueprint fit: 6 unverified draft proposals wait for the person; nothing applies until the person approves the batch/u);+ assert.doesNotMatch(listed.stdout, /proposed by/u, 'a recorder is never shown as an authenticated author');+ for (const [target, decision] of proposals) assert.match(listed.stdout, new RegExp(`^ ${target} ${decision} \\(unverified draft, recorded as ${seatId}\\)`, 'mu'), `${target} is listed`);+ assert.match(listed.stdout, new RegExp(`${W3} drop \\(unverified draft, recorded as ${seatId}\\); reason: this repo is a library with no pages; blueprint source: web-app v1 rule W3: Every page works at phone width`, 'u'));+ assert.equal(ok(box.run('spec', 'fit', '--json'), 'spec fit').proposals.length, 6);+ const out = join(box.dir, 'export');+ assert.equal(box.run('view', '--export', out).status, 0);+ const boards = JSON.parse(readFileSync(join(out, 'api/v1/boards.json'), 'utf8'));+ const state = JSON.parse(readFileSync(join(out, 'api/v1/boards', boards.boards[0].id, 'state.json'), 'utf8')).state;+ assert.ok(Array.isArray(state.fit), 'the view state carries the fit batch');+ assert.deepEqual(state.fit.map((proposal) => proposal.target), proposals.map(([target]) => target), 'the view state lists the whole batch');+ assert.ok(state.fit.every((proposal) => proposal.verified === false && proposal.recordedAs === seatId && !('by' in proposal) && !('session' in proposal)), 'the view shows each proposal as an unverified draft, never with an authenticated author');+ assert.equal(state.spec.find((row) => row.id === W1).stage, 'fit draft, unverified: adapt, waits for the person', 'a row shows its draft waiting');+ assert.equal(state.items.find((item) => item.id === starter('2')).fit.reason, 'there is no home page to fit to a phone');+ const w1Fit = state.fit.find((proposal) => proposal.target === W1);+ assert.deepEqual([w1Fit.decision, w1Fit.text, w1Fit.reason, w1Fit.blueprint, w1Fit.key, w1Fit.source], ['adapt', adapted, 'this repo already tests with node --test', { name: 'web-app', version: 1 }, 'W1', 'Every change ships with a test that fails without it. Why: a test that passes either way proves nothing.'], 'the view state carries each proposal with its text, reason and blueprint source');++ // The person edits one proposal and approves the batch.+ const reread = ok(box.run('spec', 'fit', 'edit', W2, 'drop', '--reason', 'the gate already holds main', '--json'), 'person edit');+ assert.equal(reread.proposals.length, 6, 'an edit shows the whole batch again');+ const done = ok(box.run('spec', 'fit', 'approve', reread.batch, '--json'), 'approve');+ assert.equal(done.proposals.length, 6);+ assert.ok(done.proposals.every((proposal) => proposal.state === 'approved' && proposal.approvedBy === 'person'));+ const w1 = ok(box.run('spec', 'show', W1, '--json'), 'spec show').row;+ assert.equal(w1.stage, 'approved, pending apply');+ assert.equal(w1.decision.text, adapted, 'the adaptation is the approved text');+ assert.equal(w1.decision.note, `blueprint fit adapt: this repo already tests with node --test; recorded as ${seatId}, unverified; blueprint source: web-app v1 rule W1: Every change ships with a test that fails without it. Why: a test that passes either way proves nothing.`);+ const w3 = ok(box.run('spec', 'show', W3, '--json'), 'spec show').row;+ assert.equal(w3.stage, 'declined, pending apply');+ assert.equal(w3.reason, 'this repo is a library with no pages', 'the drop keeps its reason');+ assert.match(w3.decision.note, /blueprint source: web-app v1 rule W3: Every page works at phone width before it ships\./u, 'the drop keeps its blueprint source');+ assert.match(ok(box.run('spec', 'show', W2, '--json'), 'spec show').row.decision.note, /^blueprint fit drop: the gate already holds main; recorded as person, unverified;/u, "the person's edit is what applies");+ assert.equal(ok(box.run('spec', 'show', Q1, '--json'), 'spec show').row.decision.text, 'The app is built with: Something else. Choices: Next.js, SvelteKit, Rails, Something else.');+ const adaptedItem = ok(box.run('show', String(starter('1')), '--json'), 'show');+ assert.equal(adaptedItem.item_criterion, 'npm test runs node --test with one passing test');+ const dropped = ok(box.run('show', String(starter('2')), '--json'), 'show');+ assert.equal(dropped.item_status, 'withdrawn');+ assert.equal(dropped.item_withdrawn_reason, 'blueprint fit drop: there is no home page to fit to a phone');+ const thread = box.run('show', String(starter('2')));+ assert.match(thread.stdout, /blueprint fit drop: there is no home page to fit to a phone; recorded as web-\S+, unverified; blueprint source: web-app v1 starter 2: The home page works at phone width/u, 'the starter drop keeps its reason and source');++ // The coordinator applies the decisions to SPEC.md as usual.+ assert.equal(box.run('spec', 'apply').status, 0);+ const applied = parseSpec(readFileSync(join(box.repo, 'SPEC.md'), 'utf8')).rows;+ assert.deepEqual([W1, W3].map((id) => applied.find((row) => row.id === id)).map((row) => [row.status, row.text]), [['approved', adapted], ['wont', `${PUBLISHED.rules[2].text} Why: ${PUBLISHED.rules[2].why}`]]);+});++test('an agent cannot approve its own fit proposal [S1,E3,B26]', () => {+ const { box, worktree, seat, as, key } = fitBoard();+ const W3 = key('W3');+ ok(seat('blueprint', 'fit', 'web-app', W3, 'drop', '--reason', 'no pages here', '--json'), 'propose');+ const specBefore = readFileSync(join(box.repo, 'SPEC.md'), 'utf8');+ // The proposing session is refused by name, from its worktree or the main checkout, for approve and edit.+ assert.equal(refusal(seat('spec', 'fit', 'approve', 'any-code', '--json'), 'approve from the seat'), 'FIT_OWN_PROPOSAL');+ assert.equal(refusal(as('fit-seat', box.repo, 'spec', 'fit', 'approve', 'any-code', '--json'), 'approve from main'), 'FIT_OWN_PROPOSAL');+ assert.equal(refusal(as('fit-seat', box.repo, 'spec', 'fit', 'edit', W3, 'keep', '--json'), 'edit from main'), 'FIT_OWN_PROPOSAL');+ // Any other agent session is no person either, nor is the seat's worktree.+ assert.equal(refusal(as('another-seat', box.repo, 'spec', 'fit', 'approve', 'any-code', '--json'), 'another agent'), 'B26_PERSON_CHANNEL');+ assert.equal(refusal(as(null, worktree, 'spec', 'fit', 'approve', 'any-code', '--json'), 'a worktree terminal'), 'B26_PERSON_APPROVAL');+ // Nothing applied, and the proposal still waits for the person.+ assert.equal(readFileSync(join(box.repo, 'SPEC.md'), 'utf8'), specBefore);+ assert.equal(ok(box.run('spec', 'show', W3, '--json'), 'spec show').row.decision, undefined);+ const first = ok(box.run('spec', 'fit', '--json'), 'the person reads the batch');+ assert.equal(first.proposals.length, 1);++ // Every refusal below leaves the batch, the reading, SPEC.md and the board as they were.+ const file = join(box.repo, '.git', 'pullboard', 'blueprint-fit.json');+ const readingFile = join(box.repo, '.git', 'pullboard', 'blueprint-fit-viewed.json');+ const refusedWith = (code, batch, label) => {+ const before = [file, readingFile, join(box.repo, 'SPEC.md')].map((path) => readFileSync(path, 'utf8'));+ const result = box.run('spec', 'fit', 'approve', batch, '--json');+ assert.equal(refusal(result, label), code, label);+ assert.deepEqual([file, readingFile, join(box.repo, 'SPEC.md')].map((path) => readFileSync(path, 'utf8')), before, `${label}: nothing is persisted`);+ assert.equal(ok(box.run('spec', 'show', W3, '--json'), 'spec show').row.decision, undefined, `${label}: nothing applied`);+ return JSON.parse(result.stdout).error.message;+ };+ // A proposal changed in the file after the person read it is refused by name.+ const stored = JSON.parse(readFileSync(file, 'utf8'));+ stored.proposals.at(-1).reason = 'a different reason slipped in after the reading';+ writeFileSync(file, `${JSON.stringify(stored)}\n`);+ assert.match(refusedWith('FIT_CHANGED', first.batch, 'approve after an edit'), new RegExp(`^${W3} \\(changed\\) differ from your last reading`, 'u'), 'the refusal names the changed proposal');+ // A proposal that arrives after the reading is refused too; an agent reading the batch does not count.+ const second = ok(box.run('spec', 'fit', '--json'), 'the person reads it again');+ assert.equal(second.proposals[0].reason, 'a different reason slipped in after the reading');+ const W4 = key('W4');+ ok(seat('blueprint', 'fit', 'web-app', W4, 'keep', '--json'), 'a later proposal');+ ok(seat('spec', 'fit', '--json'), 'the seat reads the batch');+ assert.match(refusedWith('FIT_CHANGED', second.batch, 'approve after a new proposal'), new RegExp(`^${W4} \\(new\\) differ from`, 'u'), 'the refusal names only the unread proposal');++ // The person reads both. A proposal deleted from the file after that reading is refused by name.+ const third = ok(box.run('spec', 'fit', '--json'), 'the person reads both');+ assert.equal(third.proposals.length, 2);+ const read = readFileSync(file, 'utf8');+ const readReading = readFileSync(readingFile, 'utf8');+ const both = JSON.parse(read);+ writeFileSync(file, `${JSON.stringify({ ...both, proposals: both.proposals.filter((proposal) => proposal.target !== W4) })}\n`);+ assert.match(refusedWith('FIT_CHANGED', third.batch, 'approve after a deletion'), new RegExp(`^${W4} \\(gone\\) differ from`, 'u'), 'the refusal names the deleted proposal');+ writeFileSync(file, read);+ // A reading rewritten to match a changed batch is caught: it no longer hashes to the code the person typed.+ const forged = JSON.parse(read);+ const target = forged.proposals.find((proposal) => proposal.target === W3);+ target.reason = 'slipped in with a matching reading';+ writeFileSync(file, `${JSON.stringify(forged)}\n`);+ const reading = JSON.parse(readReading);+ reading.reading.find((entry) => entry.id === target.id).digest = fitDigest(target);+ writeFileSync(readingFile, `${JSON.stringify(reading)}\n`);+ assert.notEqual(batchCode(reading.reading), third.batch, 'the forged reading has another code');+ assert.match(refusedWith('FIT_READING', third.batch, 'approve after the reading was rewritten'), new RegExp(`^${third.batch} is not the batch code of your last reading`, 'u'));+ // The forger's own code fails the same way once the reading is put back, since the batch differs.+ writeFileSync(readingFile, readReading);+ assert.match(refusedWith('FIT_CHANGED', third.batch, 'approve a forged batch'), new RegExp(`^${W3} \\(changed\\)`, 'u'));++ // An unread proposal given a read one's id, and placed first, is refused by name: ids are never merged.+ writeFileSync(file, read);+ const W5 = key('W5');+ ok(seat('blueprint', 'fit', 'web-app', W5, 'keep', '--json'), 'an unread proposal');+ const withW5 = JSON.parse(readFileSync(file, 'utf8'));+ const unread = withW5.proposals.find((proposal) => proposal.target === W5);+ unread.id = withW5.proposals.find((proposal) => proposal.target === W3).id;+ writeFileSync(file, `${JSON.stringify({ ...withW5, proposals: [unread, ...withW5.proposals.filter((proposal) => proposal !== unread)] })}\n`);+ assert.match(refusedWith('FIT_FILE', third.batch, 'approve with a shared id'), new RegExp(`^${W5}, ${W3} share a proposal id`, 'u'), 'the refusal names both targets');+ assert.equal(refusal(box.run('spec', 'fit', '--json'), 'read a batch with a shared id'), 'FIT_FILE');+ assert.equal(ok(box.run('spec', 'show', W5, '--json'), 'spec show').row.decision, undefined, 'the unread proposal applied nothing');++ // Put back as the person read it, the batch is the person's to approve, with the code they were shown.+ writeFileSync(file, read);+ assert.equal(refusal(box.run('spec', 'fit', 'approve', '--json'), 'approve with no batch code'), 'USAGE');+ const approved = ok(box.run('spec', 'fit', 'approve', third.batch, '--json'), 'the person approves');+ assert.deepEqual(approved.decisions.map((record) => [record.id, record.decision]), [[W3, 'decline'], [W4, 'approve']]);+});