Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

feat(rigor): draft a rule from a repeated cause [D1,D3,S1]

Corey Olson6c5d7bc21145
diff --git a/docs/api.md b/docs/api.md
index 89c8beb2..888e1e02 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -95,6 +95,7 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec
| `ledger` | `version:number`, `items:array`, `stats:object` |
| `log` | `version:number`, `events:array` |
| `rigor` | `version:number`, `causes:array`, `uncaused:number` |
+| `rigor draft` | `version:number`, `key:string`, `reads:string`, `evidence:object`, `proof:object`, `drafts:array` |
| `add` | `version:number`, `item:object` |
| `edit` | `version:number`, `item:object` |
| `fact` | `version:number`, `item:number`, `fact:object` |
@@ -229,6 +230,8 @@ Rigor is how errors become doctrine or specs. It starts by noticing a failure ca
The person can mark a cause never-again from the main checkout's terminal: `pullboard fact <id> root-cause "<why>" --cause <key> --never-again --as person`. The fact is recorded as the person's, carries `cause` and `neverAgain: true`, and `rigor` lists its cause at once. An agent or a fact without `--as person` is refused with `RIGOR_PERSON_ONLY`. Over the relay, a fact move with person mode, a never-again or a cause key is accepted only from an authenticated person sender; an agent, a coordinator seat or the machine credential is refused with `RELAY_PERSON_ONLY` whatever channel the move names, and nothing is recorded. A move that carries a cause key needs move engine 30; moves without one replay as before.
+`pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit> [--section <letter>]` turns a cause that `rigor` lists into a draft row. The key must be listed now, or it is refused with `RIGOR_UNNOTICED`. First it proves the check: it runs `--check` with `sh -c` in a throwaway detached worktree at each commit. A work check counts problems: it exits 0 or 1 and prints one nonblank line per problem, at least one at `--red` and none at `--green`. A product check is a test: it exits nonzero at `--red` and 0 at `--green`. A cause that reads as both needs both. A missing `--check`, `--red` or `--green`, an unknown commit, a timeout, or a check that is not red then green is refused with `RIGOR_UNPROVEN`, naming what failed. Then it writes the rows through the same writer as `spec draft`, as `[draft, must]`: a work cause becomes a doctrine row `- <id> [draft, must] <rule> Why: rigor <key> failed on #a, #b; red at <sha>, green at <sha>. | gate: check <command> | count: 0`, a product cause a spec row with the same text and `gate: <command>`, and a cause that reads as both one of each. `--section` picks the section prefix; the default is the doctrine file's first section and the spec's G. Nothing is approved or applied: the person approves the rows in Pullboard View or with `spec approve`, and from then on the row's own gate holds it. The JSON result is `{version, key, reads, evidence: {items, occurrences, neverAgain}, proof: {check, red, green}, drafts: [{id, file, line, row}]}`, where `red` and `green` are `{commit, exit, problems, timedOut}`.
+
## Refusals
A refusal keeps the command's existing exit status and prints exactly one versioned document to stdout. In JSON mode stderr stays empty except for sign-in instructions and check consent notices. The command-specific `code` identifies the rule; `message` explains what happened; `next` gives the next step.
diff --git a/src/cli.js b/src/cli.js
index 0af98331..6390e4be 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -19,6 +19,7 @@ import { checkRulesAt, doctrineReport, hasSubmitRules, holdDoctrine, ruleLine }
import { AGENT_SESSION_IDS, agentSessionDigest, requirePersonChannel } from './person.js';
import { bindLocalSession, localSessionMatches, localSessionSeats } from './agent-session.js';
import { decisionAnswer, decisionProjection, handAnsweredQuestions, pendingAnswers, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';
+import { draftRow } from './spec-draft.js';
import { digestOf, gateReport, refuseSandboxBlocked, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';
import { checkNeedsBrowser, explicitCheckFiles } from './browser-admission.js';
import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';
@@ -50,11 +51,9 @@ import { promptFor, skillProblems, updateSkills } from './skills.js';
import {
frozenCriterion,
idProblems,
- insertSectionRows,
lintSpec,
loadSpec,
legacyDoctrineRenameBase,
- nextRowId,
permanenceProblems,
parseSpec,
readSignoffs,
@@ -78,6 +77,7 @@ import { commandOutput, refusalDocument } from './json.js';
import { forgetProject, listApiProjects, registerProjectAndLink, registeredProjectRootsSnapshot } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
import { rigorLines, rigorReport } from './rigor.js';
+import { rigorDraft } from './rigor-draft.js';
import { listResources, memoryVerdict, readMachineMemory, runnerResourceStatus } from './resources.js';
import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
import { exportView, serveView } from './serve.js';
@@ -321,6 +321,8 @@ const OPTIONS = {
'never-again': { type: 'boolean' },
implies: { type: 'string' },
owns: { type: 'string' },
+ red: { type: 'string' },
+ green: { type: 'string' },
help: { type: 'boolean', short: 'h' },
version: { type: 'boolean', short: 'v' },
};
@@ -2231,7 +2233,8 @@ function readCommands(io, { first, second, rest, values }) {
return 0;
},
rigor: () => {
- if (first || second || rest.length) throw new Refused('USAGE', 'pullboard rigor takes no arguments');
+ if (first === 'draft') return rigorDraftHere(io, { second, rest, values });
+ if (first || second || rest.length) throw new Refused('USAGE', 'pullboard rigor takes no arguments; to draft a rule: pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit>');
const ctx = context(io);
const report = withBoard(ctx, (board) => rigorReport(store.events(board), { person: store.PERSON }));
io.result?.(report);
@@ -2249,6 +2252,28 @@ function readCommands(io, { first, second, rest, values }) {
};
}
+/**
+ * Draft a rule from a repeated cause (#714): prove its check red then green on real commits, then
+ * write the pending row or rows through the spec draft writer. Nothing is approved or applied; the
+ * person approves the rows in pullboard view or with pullboard spec approve [D1,D3,S1].
+ *
+ * @param {any} io
+ * @param {{ second?: string, rest: string[], values: any }} args
+ * @returns {number}
+ */
+function rigorDraftHere(io, { second, rest, values }) {
+ if (rest.length > 1) throw new Refused('USAGE', 'pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit> [--section <letter>]');
+ const ctx = context(io);
+ const events = withBoard(ctx, (board) => store.events(board));
+ const result = rigorDraft({ root: ctx.info.root, config: ctx.config, events, person: store.PERSON },
+ { key: second, text: rest[0], check: values.check, red: values.red, green: values.green, section: values.section });
+ io.result?.(result);
+ io.say(`proved ${result.key}: red at ${result.proof.red.commit.slice(0, 12)} (${result.proof.red.problems} problem lines, exit ${result.proof.red.exit}), green at ${result.proof.green.commit.slice(0, 12)} (exit ${result.proof.green.exit})`);
+ for (const draft of result.drafts) io.say(`${draft.file}: ${draft.line}`);
+ io.say(`next: the person approves ${result.drafts.map((draft) => draft.id).join(' or ')} in pullboard view or with pullboard spec approve; commit ${[...new Set(result.drafts.map((draft) => draft.file))].join(' and ')}`);
+ return 0;
+}
+
/**
* Submit: a clean tree, nothing untracked, the gate green at HEAD, then the board (V4).
*
@@ -3570,28 +3595,9 @@ async function specCommand(io, { first, second, rest, values }) {
return 0;
}
if (values.source !== undefined) throw new Refused('FLAG_NOT_ALLOWED', 'spec draft --source belongs to --doctrine; use both when proposing a ruling');
- if (!spec.sections.length) throw new Refused('NO_SECTION', `no section in ${ctx.config.spec}; add a section heading, then draft the requirement`);
- const sections = spec.sections.map(section => ({ ...section,
- prefix: /^([A-Z][A-Z0-9]*)\s*[·.:-]/u.exec(section.name)?.[1] })).filter(section => section.prefix);
- const requested = values.section ?? 'G';
- const section = sections.find(section => section.prefix === requested);
- if (!section) throw new Refused('SPEC_SECTION', `unknown section "${requested}" in ${ctx.config.spec}; ${sections.length
- ? `choose one of: ${sections.map(section => section.prefix).join(', ')}`
- : 'add a section heading with an id prefix such as G · Goals'}`);
- const { prefix } = section;
- const malformed = [[spec.file, spec.problems], [practice.repo.file, practice.repo.problems]].find(([, problems]) => problems.length);
- if (malformed) {
- throw new Refused('SPEC_INVALID', `fix the unparsed row in ${malformed[0]} before drafting; an existing id may be ambiguous`);
- }
- const id = nextRowId(prefix, [...spec.rows, ...practice.repo.rows]);
const tier = values.aim ? 'aim' : 'must';
- const gate = values.gate?.trim() ?? 'review';
- const row = `- ${id} [draft, ${tier}] ${second.trim()} | gate: ${gate}`;
- const source = readFileSync(spec.file, 'utf8');
- const after = insertSectionRows(source, spec, section, [row]);
- writeRowApply(ctx.info.root, { records: [], files: [{ file: ctx.config.spec, before: source, after }],
- signoffs: { before: null, receipts: [] } });
- io.result?.({ id, row: { id, status: 'draft', tier, text: second.trim(), gate, section: section.name } });
+ const { id, row } = draftRow(ctx.info.root, ctx.config, { target: 'spec', text: second.trim(), gate: values.gate?.trim() ?? 'review', tier, section: values.section });
+ io.result?.({ id, row });
io.say(id);
return 0;
}
diff --git a/src/help.js b/src/help.js
index 62625747..84d0451a 100644
--- a/src/help.js
+++ b/src/help.js
@@ -176,6 +176,9 @@ Receipts
pullboard log [id] every move, in order
pullboard rigor failure causes that repeated: on 2 items, or 1 item at 2 commits;
each with its items and whether it reads as work, product or both
+ pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit> [--section <letter>]
+ prove the check red at --red and green at --green, then draft a
+ Doctrine row (work), a spec row (product) or both; only the person approves
Spec
pullboard spec --json parsed SPEC.md and doctrine rows as JSON
@@ -221,7 +224,7 @@ const HELP_NAMES = [
'tour', 'init', 'worktree', 'join', 'takeover', 'whoami', 'lanes', 'lane', 'lane add', 'status', 'resources', 'settings', 'view', 'view export',
'serve', 'mcp', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'health', 'skills', 'show', 'next', 'land',
'check', 'check accept', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'why', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'watch', 'export', 'digest', 'import',
- 'sweep', 'merged', 'withdraw', 'refreeze', 'reopen', 'hold', 'stats', 'ledger', 'log', 'rigor', 'spec', 'spec check', 'spec view',
+ 'sweep', 'merged', 'withdraw', 'refreeze', 'reopen', 'hold', 'stats', 'ledger', 'log', 'rigor', 'rigor draft', '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',
@@ -250,7 +253,7 @@ const HELP_EXAMPLES = {
status: 'pullboard status', view: 'pullboard view', digest: 'pullboard digest --out briefing.md', mcp: 'pullboard mcp', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',
relay: 'pullboard relay on --all', 'relay recover': 'pullboard relay recover --skip 12',
'lane add': 'pullboard lane add web --owns apps/web/', lane: 'pullboard lane add web --owns apps/web/',
- roadmap: 'pullboard roadmap', rigor: 'pullboard rigor', milestone: 'pullboard milestone add "0.7.0" --items 12,13',
+ roadmap: 'pullboard roadmap', rigor: 'pullboard rigor', 'rigor draft': 'pullboard rigor draft "refusal:MERGE_LOST" "Merges keep every hunk" --check "node bin/checks/merges.js" --red 0123456 --green 89abcde', milestone: 'pullboard milestone add "0.7.0" --items 12,13',
runner: 'pullboard runner add studio --slots 2 --browser 1', 'runner add': 'pullboard runner add studio --slots 2 --browser 1',
edit: 'pullboard edit 12 --brief "Add the upload page"', release: 'pullboard release 12',
land: 'pullboard land --max 4',
diff --git a/src/json.js b/src/json.js
index b3017c80..c7afdc70 100644
--- a/src/json.js
+++ b/src/json.js
@@ -43,6 +43,7 @@ export const JSON_SHAPES = {
ledger: shape({ items: 'array', stats: 'object' }),
log: shape({ events: 'array' }),
rigor: shape({ causes: 'array', uncaused: 'number' }),
+ 'rigor draft': shape({ key: 'string', reads: 'string', evidence: 'object', proof: 'object', drafts: 'array' }),
add: shape({ item: 'object' }),
edit: shape({ item: 'object' }),
fact: shape({ item: 'number', fact: 'object' }),
diff --git a/src/next-steps.js b/src/next-steps.js
index dab0862c..4f771503 100644
--- a/src/next-steps.js
+++ b/src/next-steps.js
@@ -211,6 +211,8 @@ export const NEXT_STEPS = Object.freeze({
NOT_VERIFIED: 'merge only verified items; see pullboard list --all',
NOT_YOURS: 'shout its holder or the coordinator: pullboard shout coordinator "<what you need>"',
NOT_YOUR_CHECKOUT: 'make an independent checkout with git worktree add -b <lane>/<n> ../<repo>-<lane>-<n>, then run pullboard join <lane> --model "<model name>" there; the same agent in a new session should run pullboard takeover from its own shell',
+ RIGOR_UNNOTICED: 'run pullboard rigor and draft a cause it lists, or wait until the cause repeats',
+ RIGOR_UNPROVEN: 'name a check that fails at --red and passes at --green: pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit>',
RIGOR_PERSON_ONLY: 'ask the person to mark it from the main checkout: pullboard fact <id> root-cause "<why>" --cause <key> --never-again --as person',
SANDBOX_BLOCKED: 'ask the person to allow the named operation, or run the gate outside the sandbox; keep the tests unchanged',
NOT_YOUR_DECISION: 'answer only decisions addressed to you; see pullboard inbox',
diff --git a/src/rigor-draft.js b/src/rigor-draft.js
new file mode 100644
index 00000000..90fc6b8c
--- /dev/null
+++ b/src/rigor-draft.js
@@ -0,0 +1,102 @@
+/**
+ * Rigor's second step: a repeated cause becomes a draft row with its proof [D1,D3,S1]. A work cause
+ * becomes a Doctrine row whose check holds a count of 0; a product cause becomes a spec row gated
+ * by its failing test; a cause that reads as both drafts one of each, and the person picks. The
+ * proof is the check run on real commits: red on the bad one, green on the fix. Nothing here
+ * approves or applies a row.
+ */
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { cleanGitEnvironment, resolveCommit, tryGit } from './git.js';
+import { Refused } from './refused.js';
+import { causeProblem, rigorReport } from './rigor.js';
+import { draftRow } from './spec-draft.js';
+
+// budget: one proof run of a check at one commit; a check slower than this cannot gate a row.
+const CHECK_TIMEOUT_MS = 10 * 60_000;
+
+/** The refusal for a draft without a proof, naming what is missing and the full command shape. */
+function unproven(why, key) {
+ return new Refused('RIGOR_UNPROVEN', `${why}; a draft needs its proof: pullboard rigor draft "${key}" "<rule>" --check "<command>" --red <commit where it fails> --green <commit where it passes>`);
+}
+
+/**
+ * Run a check in a throwaway detached worktree at one commit and report its exit status and the
+ * problem lines it printed (one nonblank stdout line per problem).
+ *
+ * @param {string} root
+ * @param {string} commit
+ * @param {string} check
+ * @returns {{ commit: string, exit: number | null, problems: number, timedOut: boolean }}
+ */
+export function runCheckAt(root, commit, check) {
+ const dir = mkdtempSync(join(tmpdir(), 'pullboard-rigor-proof-'));
+ const tree = join(dir, 'tree');
+ const added = tryGit(root, ['worktree', 'add', '--detach', '--quiet', tree, commit]);
+ try {
+ if (added.status !== 0) throw new Refused('RIGOR_UNPROVEN', `cannot check out ${commit.slice(0, 12)} to prove the check: ${added.stderr || 'git worktree add failed'}; fetch the commit and retry`);
+ const run = spawnSync('sh', ['-c', check], { cwd: tree, env: cleanGitEnvironment(), encoding: 'utf8', timeout: CHECK_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 });
+ const problems = String(run.stdout ?? '').split(/\r?\n/u).filter((line) => line.trim()).length;
+ return { commit, exit: run.status, problems, timedOut: Boolean(run.error) };
+ } finally {
+ if (added.status === 0) tryGit(root, ['worktree', 'remove', '--force', tree]);
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+/**
+ * Prove a check red on the bad commit and green on the fix. A work check counts problems: it exits
+ * 0 or 1 and prints at least one problem line at red and none at green. A product check is a test:
+ * it exits nonzero at red and 0 at green. A cause that reads as both needs both.
+ *
+ * @param {string} root
+ * @param {{ key: string, reads: string, check?: string, red?: string, green?: string }} request
+ * @returns {{ check: string, red: object, green: object }}
+ */
+export function proveCheck(root, { key, reads, check, red, green }) {
+ if (!check?.trim()) throw unproven('no --check names the command that proves it', key);
+ if (!red || !green) throw unproven(`no ${!red ? '--red' : '--green'} names the commit where the check ${!red ? 'fails' : 'passes'}`, key);
+ const commits = [red, green].map((ref) => {
+ const commit = resolveCommit(root, ref);
+ if (!commit) throw unproven(`${ref} is not a commit in this repository`, key);
+ return commit;
+ });
+ const [atRed, atGreen] = commits.map((commit) => runCheckAt(root, commit, check));
+ for (const run of [atRed, atGreen]) if (run.timedOut) throw unproven(`the check did not finish at ${run.commit.slice(0, 12)}`, key);
+ const work = reads !== 'product';
+ const product = reads !== 'work';
+ const counted = (run) => run.exit === 0 || run.exit === 1;
+ if (work && (!counted(atRed) || !counted(atGreen))) throw unproven(`a work check exits 0 or 1 and prints one line per problem; it exited ${atRed.exit} at red and ${atGreen.exit} at green`, key);
+ if (work && (atRed.problems < 1 || atGreen.problems > 0)) throw unproven(`the check printed ${atRed.problems} problems at red ${atRed.commit.slice(0, 12)} and ${atGreen.problems} at green ${atGreen.commit.slice(0, 12)}; red needs at least 1 and green none`, key);
+ if (product && (atRed.exit === 0 || atGreen.exit !== 0)) throw unproven(`the test exited ${atRed.exit} at red ${atRed.commit.slice(0, 12)} and ${atGreen.exit} at green ${atGreen.commit.slice(0, 12)}; red needs a failure and green a pass`, key);
+ return { check: check.trim(), red: atRed, green: atGreen };
+}
+
+/**
+ * Draft the rows for a repeated cause, after proving its check. Refused when the key is malformed,
+ * has not repeated (pullboard rigor does not list it), the rule text is not one line, or the proof
+ * does not hold. Returns the drafts with their evidence and proof.
+ *
+ * @param {{ root: string, config: any, events: any[], person: string }} board
+ * @param {{ key: string, text: string, check?: string, red?: string, green?: string, section?: string }} request
+ * @returns {{ key: string, reads: string, evidence: { items: { id: number, commits: string[] }[], occurrences: number, neverAgain: boolean }, proof: object, drafts: object[] }}
+ */
+export function rigorDraft({ root, config, events, person }, { key, text, check, red, green, section }) {
+ const malformed = causeProblem(key ?? '');
+ if (malformed) throw malformed;
+ const cause = rigorReport(events, { person }).causes.find((entry) => entry.key === key);
+ if (!cause) throw new Refused('RIGOR_UNNOTICED', `${key} has not repeated, so there is nothing to draft yet; pullboard rigor lists the causes that can become rules`);
+ if (!text?.trim() || /[\r\n|]/u.test(text)) throw new Refused('USAGE', 'give the rule as one nonempty line without a field separator: pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit>');
+ if (cause.reads !== 'work' && / \| /u.test(check ?? '')) throw new Refused('USAGE', 'a spec row gate cannot hold " | "; put the pipeline in a script and name the script in --check');
+ const proof = proveCheck(root, { key, reads: cause.reads, check, red, green });
+ const items = cause.items.map((item) => `#${item.id}`).join(', ');
+ const why = `Why: rigor ${key.replaceAll('|', '/')} ${cause.neverAgain ? 'was marked never again by the person' : `failed on ${items}`}; red at ${proof.red.commit.slice(0, 12)}, green at ${proof.green.commit.slice(0, 12)}.`;
+ const rowText = `${text.trim()} ${why}`;
+ const drafts = [];
+ if (cause.reads !== 'product') drafts.push(draftRow(root, config, { target: 'doctrine', text: rowText, gate: `check ${proof.check}`, fields: ['count: 0'], section }));
+ if (cause.reads !== 'work') drafts.push(draftRow(root, config, { target: 'spec', text: rowText, gate: proof.check, section }));
+ return { key, reads: cause.reads, evidence: { items: cause.items, occurrences: cause.occurrences, neverAgain: cause.neverAgain },
+ proof: { check: proof.check, red: proof.red, green: proof.green }, drafts };
+}
diff --git a/src/spec-draft.js b/src/spec-draft.js
new file mode 100644
index 00000000..488f1843
--- /dev/null
+++ b/src/spec-draft.js
@@ -0,0 +1,54 @@
+/**
+ * Write one draft row into SPEC.md or the doctrine file, under a section, with the next free id
+ * (spec draft, rigor draft) [S1,D1]. A draft is never approved here: only the person approves.
+ */
+import { readFileSync } from 'node:fs';
+import { loadDoctrine } from './doctrine.js';
+import { Refused } from './refused.js';
+import { writeRowApply } from './row-decisions.js';
+import { insertSectionRows, loadSpec, nextRowId } from './spec.js';
+
+/**
+ * The sections of a parsed row file that carry an id prefix, such as G in "G · Goals".
+ *
+ * @param {{ sections: { name: string, line: number }[] }} parsed
+ * @returns {{ name: string, line: number, prefix: string }[]}
+ */
+function prefixedSections(parsed) {
+ return parsed.sections.map((section) => ({ ...section, prefix: /^([A-Z][A-Z0-9]*)\s*[·.:-]/u.exec(section.name)?.[1] }))
+ .filter((section) => section.prefix);
+}
+
+/**
+ * Append one draft row and return what was written. `target` is spec (the config's SPEC.md) or
+ * doctrine (the repo's doctrine file). The id is the next free one across both files, so a spec
+ * row and a doctrine row never share an id. `fields` are trailing fields after the gate, such as
+ * a check's count.
+ *
+ * @param {string} root
+ * @param {any} config
+ * @param {{ target: 'spec' | 'doctrine', text: string, gate: string, tier?: string, section?: string, fields?: string[] }} draft
+ * @returns {{ id: string, file: string, line: string, row: { id: string, status: string, tier: string, text: string, gate: string, section: string } }}
+ */
+export function draftRow(root, config, { target, text, gate, tier = 'must', section: requested, fields = [] }) {
+ const spec = loadSpec(root, config);
+ const practice = loadDoctrine(root, config);
+ const parsed = target === 'doctrine' ? practice.repo : spec;
+ const name = target === 'doctrine' ? practice.name : config.spec;
+ if (!parsed.exists) throw new Refused('NO_SPEC', `no ${name}; run: pullboard init`);
+ if (!parsed.sections.length) throw new Refused('NO_SECTION', `no section in ${name}; add a section heading, then draft the requirement`);
+ const sections = prefixedSections(parsed);
+ const wanted = requested ?? (target === 'doctrine' ? sections[0]?.prefix : 'G');
+ const section = sections.find((entry) => entry.prefix === wanted);
+ if (!section) throw new Refused('SPEC_SECTION', `unknown section "${wanted}" in ${name}; ${sections.length
+ ? `choose one of: ${sections.map((entry) => entry.prefix).join(', ')}`
+ : 'add a section heading with an id prefix such as G · Goals'}`);
+ const malformed = [[spec.file, spec.problems], [practice.repo.file, practice.repo.problems]].find(([, problems]) => problems.length);
+ if (malformed) throw new Refused('SPEC_INVALID', `fix the unparsed row in ${malformed[0]} before drafting; an existing id may be ambiguous`);
+ const id = nextRowId(section.prefix, [...spec.rows, ...practice.repo.rows]);
+ const line = [`- ${id} [draft, ${tier}] ${text} | gate: ${gate}`, ...fields].join(' | ');
+ const source = readFileSync(parsed.file, 'utf8');
+ const after = insertSectionRows(source, parsed, section, [line]);
+ writeRowApply(root, { records: [], files: [{ file: name, before: source, after }], signoffs: { before: null, receipts: [] } });
+ return { id, file: name, line, row: { id, status: 'draft', tier, text, gate, section: section.name } };
+}
diff --git a/src/templates.js b/src/templates.js
index b7b0d1da..7c44a944 100644
--- a/src/templates.js
+++ b/src/templates.js
@@ -127,7 +127,7 @@ It prints the folder to work in and what to run there first. Every join needs th
3. Build inside your lane's folders (\`pullboard lanes\`). Pre-commit refuses anything else; shout the owner instead.
4. Commit, then \`pullboard submit <id>\`. It needs a clean tree and the gate green at HEAD.
5. A different agent verifies: \`pullboard next --verify\` names the next item to check. It checks out the submitted commit and runs \`pullboard verify <id> accept --note "how it proved it"\`, or \`pullboard verify <id> reject --reason TEST_FAILURE --note "what failed"\`.
-When a reject names a structured cause, add \`--cause <key>\` (\`test:<file>::<title>\`, \`refusal:<CODE>\`, \`row:<id>\` or \`doctrine:<id>\`) so \`pullboard rigor\` can notice when the same cause repeats.
+When a reject names a structured cause, add \`--cause <key>\` (\`test:<file>::<title>\`, \`refusal:<CODE>\`, \`row:<id>\` or \`doctrine:<id>\`) so \`pullboard rigor\` can notice when the same cause repeats; the coordinator turns a repeated cause into a draft rule with \`pullboard rigor draft <key> "<rule>" --check "<command>" --red <commit> --green <commit>\`, which proves the check red, then green, before the person decides.
6. A reject reopens the item. Fix it, commit, claim, submit again; the same head is refused. If you cannot get an item green, do not force it: \`pullboard escalate <id> --note "what you tried and how it failed"\` hands it one tier up.
7. Your lane is done when its items are verified, not when they are submitted. After your last submit, keep running \`pullboard next --wait 9\`: a rejected item comes back to your lane.
diff --git a/test/api.test.js b/test/api.test.js
index 448e5bbd..49f94951 100644
--- a/test/api.test.js
+++ b/test/api.test.js
@@ -1017,6 +1017,20 @@ test('[A1] every catalog command and subcommand has a real CLI exercise', () =>
json(source, source.repo, 'claim', [String(reopenItem.item_id)]);
json(source, source.repo, 'submit', [String(reopenItem.item_id)]);
json(source, source.repo, 'reopen', [String(reopenItem.item_id), '--note', 'exercise the versioned reopen result']);
+ // A cause repeated on two items becomes a draft row once its check is proved red, then green (#714).
+ for (const title of ['Rigor catalog one', 'Rigor catalog two']) {
+ const caused = json(source, source.repo, 'add', ['coordinator', title, '--criterion', 'Exercise a caused reopen.', '--check', 'true'], 'add').item;
+ json(source, source.repo, 'claim', [String(caused.item_id)]);
+ json(source, source.repo, 'submit', [String(caused.item_id)]);
+ json(source, source.repo, 'reopen', [String(caused.item_id), '--note', 'the bar cites the wrong row', '--cause', 'row:G1']);
+ }
+ const red = source.git(source.repo, 'rev-parse', 'HEAD').stdout.trim();
+ mkdirSync(join(source.repo, 'app'), { recursive: true });
+ writeFileSync(join(source.repo, 'app', 'fixed.txt'), 'fixed\n');
+ source.git(source.repo, 'add', 'app/fixed.txt');
+ source.git(source.repo, 'commit', '-q', '-m', 'feat(app): add the fixed file [G1]');
+ const drafted = json(source, source.repo, 'rigor', ['draft', 'row:G1', 'The fixed file exists', '--check', 'test -f app/fixed.txt', '--red', red, '--green', 'HEAD'], 'draft');
+ assert.equal(drafted.drafts.length, 1);
json(source, source.repo, 'spec', ['approve', 'G1'], 'approve');
json(source, source.repo, 'spec', ['decline', 'G1', '--reason', 'Catalog decline'], 'decline');
writeFileSync(join(source.repo, 'SPEC.md'), `${readFileSync(join(source.repo, 'SPEC.md'), 'utf8')}- G2 [pending, must] Which store holds the catalog: SQLite. Choices: SQLite, Postgres. | gate: review\n`);
diff --git a/test/rigor.test.js b/test/rigor.test.js
index 77c1b3ae..49a8a261 100644
--- a/test/rigor.test.js
+++ b/test/rigor.test.js
@@ -40,7 +40,7 @@ function freshBoard() {
});
const repo = join(dir, 'repo');
mkdirSync(repo);
- const git = (...args) => runFixtureGit(args, { cwd: repo, env });
+ const git = (...args) => runFixtureGit(args, { cwd: repo, env, encoding: 'utf8' });
const run = (...args) => runFixtureChild(process.execPath, [BIN, ...args], { cwd: repo, env, encoding: 'utf8' });
git('init', '-q', '-b', 'main');
const init = run('init', '--model', 'Rigor coordinator');
@@ -289,3 +289,74 @@ test('reject, reopen and fact moves without a cause replay unchanged from engine
(error) => error.code === 'ENGINE_VERSION', `the engine-${version} client refuses a cause move before interpreting it`);
}
});
+
+test('a repeated cause becomes a draft row with its proof [D1,D3,S1]', () => {
+ const box = freshBoard();
+ // Two real commits: the bad one has a TODO and no fixed file; the fix removes the TODO and adds it.
+ mkdirSync(join(box.repo, 'src'), { recursive: true });
+ writeFileSync(join(box.repo, 'src', 'page.js'), '// TODO: escape the title\nexport const page = 1;\n');
+ box.git('add', 'src/page.js');
+ box.git('commit', '-q', '-m', 'chore: add the page');
+ const bad = box.git('rev-parse', 'HEAD').stdout.trim();
+ writeFileSync(join(box.repo, 'src', 'page.js'), 'export const page = 1;\n');
+ writeFileSync(join(box.repo, 'fixed.txt'), 'fixed\n');
+ box.git('add', 'src/page.js', 'fixed.txt');
+ box.git('commit', '-q', '-m', 'chore: escape the title');
+ const fix = box.git('rev-parse', 'HEAD').stdout.trim();
+
+ const board = history(box.file);
+ const items = ['Work one', 'Work two', 'Product one', 'Product two', 'Both one', 'Both two', 'Lonely'].map(board.add);
+ const [workA, workB, productA, productB, bothA, bothB, lonely] = items;
+ const bothKey = 'test:test/page.test.js::[G1] the page title is escaped';
+ for (const [id, cause] of [[workA, 'doctrine:C3'], [workB, 'doctrine:C3'], [productA, 'row:G1'], [productB, 'row:G1'], [bothA, bothKey], [bothB, bothKey], [lonely, 'refusal:LONELY']]) {
+ board.submit(id); board.reject(id, cause);
+ }
+ board.close();
+ const specBefore = readFileSync(join(box.repo, 'SPEC.md'), 'utf8');
+ const doctrineBefore = readFileSync(join(box.repo, 'DOCTRINE.md'), 'utf8');
+
+ // Without proof, or with a proof that is not red then green, nothing is drafted.
+ const flags = (check, red, green) => ['--check', check, '--red', red, '--green', green];
+ refused(box.run('rigor', 'draft', 'doctrine:C3', 'No TODO markers in shipped source', '--json'), 'RIGOR_UNPROVEN', 'a draft without a check is unproven');
+ refused(box.run('rigor', 'draft', 'doctrine:C3', 'No TODO markers in shipped source', '--check', 'grep -rn TODO src', '--red', bad, '--json'), 'RIGOR_UNPROVEN', 'a draft without its green commit is unproven');
+ refused(box.run('rigor', 'draft', 'doctrine:C3', 'No TODO markers in shipped source', ...flags('grep -rn TODO src', fix, bad), '--json'), 'RIGOR_UNPROVEN', 'a check green at red and red at green proves nothing');
+ refused(box.run('rigor', 'draft', 'row:G1', 'The fixed file exists', ...flags('true', bad, fix), '--json'), 'RIGOR_UNPROVEN', 'a test that never fails proves nothing');
+ refused(box.run('rigor', 'draft', 'refusal:LONELY', 'Lonely rule', ...flags('test -f fixed.txt', bad, fix), '--json'), 'RIGOR_UNNOTICED', 'a cause that has not repeated cannot be drafted');
+ assert.equal(readFileSync(join(box.repo, 'SPEC.md'), 'utf8'), specBefore, 'a refused draft writes no spec row');
+ assert.equal(readFileSync(join(box.repo, 'DOCTRINE.md'), 'utf8'), doctrineBefore, 'a refused draft writes no doctrine row');
+
+ // A work cause becomes a Doctrine row: gate: check, count: 0, its evidence and its proof.
+ const work = json(box, 'rigor', 'draft', 'doctrine:C3', 'No TODO markers in shipped source', ...flags('grep -rn TODO src', bad, fix));
+ assert.equal(work.reads, 'work');
+ assert.deepEqual(work.evidence.items.map((item) => item.id), [workA, workB]);
+ assert.deepEqual([work.proof.red.commit, work.proof.red.problems, work.proof.green.commit, work.proof.green.problems], [bad, 1, fix, 0]);
+ assert.equal(work.drafts.length, 1);
+ const [doctrineRow] = work.drafts;
+ assert.equal(doctrineRow.file, 'DOCTRINE.md');
+ assert.equal(doctrineRow.line, `- ${doctrineRow.id} [draft, must] No TODO markers in shipped source Why: rigor doctrine:C3 failed on #${workA}, #${workB}; red at ${bad.slice(0, 12)}, green at ${fix.slice(0, 12)}. | gate: check grep -rn TODO src | count: 0`);
+ assert.ok(readFileSync(join(box.repo, 'DOCTRINE.md'), 'utf8').includes(doctrineRow.line), 'the row is written into DOCTRINE.md');
+ assert.equal(readFileSync(join(box.repo, 'SPEC.md'), 'utf8'), specBefore, 'a work cause writes no spec row');
+
+ // A product cause becomes a spec row gated by its failing test.
+ const product = json(box, 'rigor', 'draft', 'row:G1', 'The fixed file exists', ...flags('test -f fixed.txt', bad, fix));
+ assert.equal(product.reads, 'product');
+ assert.deepEqual([product.proof.red.exit, product.proof.green.exit], [1, 0], 'the test fails on the bad commit and passes on the fix');
+ assert.equal(product.drafts.length, 1);
+ const [specRow] = product.drafts;
+ assert.equal(specRow.file, 'SPEC.md');
+ assert.equal(specRow.line, `- ${specRow.id} [draft, must] The fixed file exists Why: rigor row:G1 failed on #${productA}, #${productB}; red at ${bad.slice(0, 12)}, green at ${fix.slice(0, 12)}. | gate: test -f fixed.txt`);
+
+ // An unclear cause drafts both, and the person picks.
+ const both = json(box, 'rigor', 'draft', bothKey, 'Page titles are escaped', ...flags('! grep -rn TODO src', bad, fix));
+ assert.equal(both.reads, 'both');
+ assert.deepEqual(both.drafts.map((draft) => draft.file), ['DOCTRINE.md', 'SPEC.md']);
+
+ // Nothing is approved or applied: every drafted row is a draft, and the board records no decision.
+ const rows = json(box, 'spec').rows.filter((row) => [doctrineRow.id, specRow.id, ...both.drafts.map((draft) => draft.id)].includes(row.id));
+ assert.equal(rows.length, 4);
+ assert.ok(rows.every((row) => row.status === 'draft'), 'every drafted row is still a draft');
+ assert.equal(rows.find((row) => row.id === doctrineRow.id).gate, 'check grep -rn TODO src');
+ const check = box.run('spec', 'check');
+ assert.equal(check.status, 0, `the drafted rows parse cleanly: ${check.stdout}${check.stderr}`);
+ assert.ok(!json(box, 'log').events.some((event) => ['row_decision', 'row_apply'].includes(event.event_kind)), 'the command approved and applied nothing');
+});