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(doctrine): a rule's check holds a count that only falls [D1,D3]
Corey Olsond32f48ed3dae
diff --git a/docs/api.md b/docs/api.mdindex dbafe4db..f55c34e9 100644--- a/docs/api.md+++ b/docs/api.md@@ -116,6 +116,7 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec| `spec approve` | `version:number`, `decisions:array` || `spec decline` | `version:number`, `decisions:array` || `spec apply` | `version:number`, `applied:array`, `files:array` |+| `doctrine check` | `version:number`, `rules:array` || `hook pre-commit` | `version:number`, `messages:array` || `hook pre-merge-commit` | `version:number`, `messages:array` || `hook commit-msg` | `version:number`, `messages:array` |diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex b2af58f0..3cc4f580 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -54,7 +54,7 @@ Each move checks its guards in this order and refuses with the first one that do| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) || release | claimed | open | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) || lapse | claimed | open | clock, when its lease runs out | none |-| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), correctionRefrozen (PENDING_REFREEZE), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), gateConfigured (NO_GATE), gateGreen (GATE_RED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |+| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), correctionRefrozen (PENDING_REFREEZE), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), doctrineHolds (RATCHET_ROSE), gateConfigured (NO_GATE), gateGreen (GATE_RED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) || reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), roadmapReadable (MILESTONES_CORRUPT), itemExists (NO_ITEM), inState (NOT_SUBMITTED), reviewCooldownElapsed (REVIEW_COOLDOWN), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD) || accept | submitted | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), itemCheckGreen (CHECK_RED or CHECK_UNVERIFIED), proofNoted (PROOF_REQUIRED) || reject | submitted | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED) |@@ -120,6 +120,7 @@ Each move checks its guards in this order and refuses with the first one that do| NO_POLICY | the candidate merges cleanly into the current primary branch without changing an index or worktree | restore the primary repository metadata || NO_TRUNK | the candidate merges cleanly into the current primary branch without changing an index or worktree | check out the trunk branch in the main checkout once and run pullboard inbox || STACKED_ON_UNVERIFIED | the candidate range contains no other item's unverified submitted commit | wait for that item to be accepted, or rebuild without its commits |+| RATCHET_ROSE | no touched doctrine check rises above its committed count and no changed file gains a problem; watch-mode rules only count, only when accepted main has an approved doctrine rule with gate: check | fix the new problems, commit, submit again; only the person's signature raises count: || CHECK_RED | the frozen item check passes at the exact submitted commit | reject the failing behavior; the builder fixes and resubmits || CHECK_UNVERIFIED | the frozen item check passes at the exact submitted commit | restore the frozen install or check environment and retry || GATE_RED | the gate, which submit runs itself every time, is green at HEAD | fix what the digest names, commit, submit again |diff --git a/src/approved-rows.js b/src/approved-rows.jsindex 3d468fb6..56c16104 100644--- a/src/approved-rows.js+++ b/src/approved-rows.js@@ -8,6 +8,7 @@ import { boardBusyError, openBoardReadOnly, rowDecisions } from './board.js';import { hasSignerFile, verifySignedRecords } from './signature.js';import { Refused } from './refused.js';import { CONFIG_FILE, configFromSource } from './config.js';+import { checkLoosening } from './doctrine-checks.js';const TRUST_FILES = ['.pullboard/signers', '.pullboard/first-commit', '.pullboard/signers.initial', SIGNOFFS_FILE];@@ -80,8 +81,10 @@ export function approvedRowProblems(root, config, boardFile) {// Historical grammar declarations must not prevent a repair to the supported staged grammar.for (const old of parseSpec(before.text, { strictGrammarVersion: false }).rows.filter((row) => row.status === 'approved')) {const matches = rows.rows.filter((row) => row.id === old.id);- if (matches.length === 1 && matches[0].text === old.text) continue;- changes.push({ kind, file: staged.file, files: [before.file, staged.file], row: matches[0] ?? old, ambiguous: matches.length !== 1,+ // A check that lets more problems through is as much the person's call as new wording [D1].+ const loosened = matches.length === 1 ? checkLoosening(old, matches[0]) : '';+ if (matches.length === 1 && matches[0].text === old.text && !loosened) continue;+ changes.push({ kind, file: staged.file, files: [before.file, staged.file], row: matches[0] ?? old, ambiguous: matches.length !== 1, loosened,target: matches.length === 1 ? staged.text.split(/\r?\n/u)[matches[0].line - 1] : '' });}}@@ -89,16 +92,19 @@ export function approvedRowProblems(root, config, boardFile) {try {const decisions = boardApprovals(boardFile);const trust = stagedApprovals(root, decisions);- return changes.filter(({ kind, files, row, target, ambiguous }) => {+ return changes.filter(({ kind, files, row, target, ambiguous, loosened }) => {if (ambiguous) return true;const approved = decisions.some((record) => record.kind === kind && record.id === row.id && files.includes(record.file)&& record.replacement === target && record.text === row.text && (!trust.signed || record.decision === 'decline' || record.signature));+ // Unchanged text keeps old sign-offs valid, so a loosened check needs a receipt for its exact new row.const signed = trust.records.some((record) => record.id === row.id && record.text === row.text- && (record.type === 'row-decision' ? record.kind === kind && files.includes(record.file) : kind === 'spec'));+ && (record.type === 'row-decision' ? record.kind === kind && files.includes(record.file) && (!loosened || record.replacement === target) : kind === 'spec' && !loosened));return !approved && !signed;- }).map(({ kind, file, row, ambiguous }) => ambiguous+ }).map(({ kind, file, row, ambiguous, loosened }) => ambiguous? `${file}: approved row ${row.id} is missing or duplicated; restore exactly one row with its permanent id before committing`- : `${file}: ${row.id} changes approved text without the person's exact approval; ask the person to approve ${kind === 'doctrine' ? 'doctrine:' : ''}${row.id} in pullboard view or sign its new text, then stage the signed receipt`);+ : loosened+ ? `${file}: ${row.id} ${loosened} without the person's signature; lowering count: is free, anything looser is theirs: ask the person to approve ${kind === 'doctrine' ? 'doctrine:' : ''}${row.id} in pullboard view or sign its new row, then stage the signed receipt`+ : `${file}: ${row.id} changes approved text without the person's exact approval; ask the person to approve ${kind === 'doctrine' ? 'doctrine:' : ''}${row.id} in pullboard view or sign its new text, then stage the signed receipt`);} catch (error) {return [`approved-row authorization cannot be checked: ${error.message}; restore valid staged SSH trust files and signed receipts before committing`];}diff --git a/src/board.js b/src/board.jsindex 0cefd895..5e4042d1 100644--- a/src/board.js+++ b/src/board.js@@ -1201,6 +1201,7 @@ export function submit(board, id, { agentId, commit, tree, files = [], policyComwithinLane: null,trunkMergeClean: null,noUnverifiedStack: null,+ doctrineHolds: null,gateConfigured: null,gateGreen: null,treeStillDuringGate: null,diff --git a/src/cli.js b/src/cli.jsindex 9ccc8f9c..d541f00c 100644--- a/src/cli.js+++ b/src/cli.js@@ -14,6 +14,7 @@ import * as store from './board.js';import { CONFIG_FILE, COORDINATOR, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE, loadConfig } from './config.js';import { displayAgentName } from './agent-names.js';import { doctrineHistory, loadDoctrine } from './doctrine.js';+import { checkRulesAt, doctrineReport, hasSubmitRules, holdDoctrine, ruleLine } from './doctrine-checks.js';import { agentSessionDigest, requirePersonChannel } from './person.js';import { bindLocalSession, localSessionMatches } from './agent-session.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';@@ -1774,6 +1775,18 @@ function refuseUncommittedSetup(mainRoot, config) {*/function readCommands(io, { first, second, rest, values }) {return {+ doctrine: async () => {+ if (first !== 'check' || second || rest.length) throw new Refused('USAGE', 'pullboard doctrine check');+ const ctx = context(io);+ // Only a repo whose committed doctrine carries a check takes a machine slot for it.+ const rules = checkRulesAt(ctx.info.root, 'HEAD', ctx.config.practice).length+ ? await withGateSlot(ctx.info.root, () => doctrineReport(ctx.info.root, ctx.config), { itemCheck: true, agent: resourceAgent(ctx), kind: 'doctrine', onWait: gateWaitReporter(io) })+ : [];+ io.result?.({ rules });+ if (!rules.length) io.say('no committed doctrine rule carries a check; add one as | gate: check <command> | count: N');+ for (const rule of rules) io.say(ruleLine(rule));+ return rules.every((rule) => rule.holds) ? 0 : 1;+ },skills: () => {if (first || second || rest.length || !values.update) throw new Refused('USAGE', 'pullboard skills --update');const ctx = context(io);@@ -2134,6 +2147,12 @@ async function submitHere(ctx, id) {if (!commit) throw new Refused('NO_COMMIT', 'nothing committed yet');const trunk = requireTrunkMerge(root, commit);withBoard(ctx, (board) => refuseUnverifiedStack(root, board, held, commit, trunk));+ // Doctrine counts only fall: accepted main's rules, at this exact commit (D1). No rule, no change.+ const doctrine = hasSubmitRules(root, acceptedMain.commit, acceptedMain.config.practice)+ ? await withGateSlot(root, () => holdDoctrine(root, { mainCommit: acceptedMain.commit, commit, practice: acceptedMain.config.practice, timeoutMs: acceptedMain.config.check?.timeoutMs }),+ { itemCheck: true, agent: me.id, item: String(id), kind: 'doctrine', onWait: gateWaitReporter(ctx.io) })+ : [];+ for (const rule of doctrine) ctx.io.say(`doctrine: ${ruleLine(rule)}`);// Every submit proves its frozen check and reachable tests anew on this exact commit (V4,V16).// A full-gate stamp never substitutes for either proof; only an actual full fallback may stamp.const submitConfig = { ...ctx.config, submitGate: acceptedMain.config.submitGate };@@ -2161,15 +2180,15 @@ async function submitHere(ctx, id) {...(gate.deferred ? { note: 'full suite deferred to the landing gate' } : {}) }]);});return reportSubmission(ctx, id, commit, { green: gate.isGreen, report: submitGateReport(gate), files: gate.files, full: gate.full, deferred: gate.deferred, deferFullFallback: gate.deferFullFallback, reason: gate.reason, check: gate.check,- log: gate.log, profile: gate.profile, profilePath: gate.profilePath, proofLog: gate.proofLog, proofProfilePath: gate.proofProfilePath });+ log: gate.log, profile: gate.profile, profilePath: gate.profilePath, proofLog: gate.proofLog, proofProfilePath: gate.proofProfilePath }, doctrine);}/** Report and pin the original submitted commit, including a recovered acknowledged outcome. */-function reportSubmission(ctx, id, commit, gate) {+function reportSubmission(ctx, id, commit, gate, doctrine = []) {const { root } = ctx.info;const pin = `refs/pullboard/items/${id}/${commit.slice(0, 12)}`;git(root, ['update-ref', pin, commit]);- ctx.io.result?.({ id, commit, pin, gate });+ ctx.io.result?.({ id, commit, pin, gate, ...(doctrine.length ? { doctrine } : {}) });ctx.io.say(`submitted #${id} at ${commit.slice(0, 12)}; ${gate.report}`);ctx.io.say(`pinned as ${pin}, so this work can't be lost; keep your worktree until it is merged`);ctx.io.say(`next: another agent checks out ${commit.slice(0, 12)} and runs: pullboard verify ${id} accept|reject`);diff --git a/src/doctrine-checks.js b/src/doctrine-checks.jsnew file mode 100644index 00000000..6badd64b--- /dev/null+++ b/src/doctrine-checks.js@@ -0,0 +1,269 @@+/**+ * Doctrine checks with a count that only falls (D1, D3). A rule row may carry+ * `| gate: check <command> | count: N`; the command prints one line per problem. Submit holds+ * every touched rule's count at or below its committed count and refuses a changed file that+ * gains a problem. Rules come only from committed doctrine: accepted main's at submit, HEAD's for+ * `pullboard doctrine check`, never a working-tree edit.+ */+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DOCTRINE_FILE, LEGACY_DOCTRINE_FILE } from './config.js';+import { cleanGitEnvironment, gitChildEnv, invalidateGitFacts } from './git.js';+import { Refused } from './refused.js';+import { checkFieldFindings, parseSpec } from './spec.js';++const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;++/**+ * A row's check rule, or null when the row carries no well-formed check. Malformed check fields+ * are lint errors in `pullboard spec check`; here they simply carry no rule.+ *+ * @param {any} row+ * @returns {{ id: string, text: string, status: string, command: string, count: number, runs: string, mode: string } | null}+ */+export function checkRule(row) {+ if (!/^check\s/u.test(row?.gate ?? '') || checkFieldFindings(row).length) return null;+ return { id: row.id, text: row.text, status: row.status, command: row.gate.slice('check'.length).trim(),+ count: Number(row.count), runs: row.runs ?? 'submit', mode: row.mode ?? 'hold' };+}++/**+ * How an approved row's new version loosens its check, or '' when it does not. Lowering count:+ * is free; anything that lets more problems through needs the person's signature.+ *+ * @param {any} before - The committed row.+ * @param {any} after - The staged row with the same id.+ * @returns {string}+ */+export function checkLoosening(before, after) {+ const old = checkRule(before);+ if (!old) return '';+ const next = checkRule(after);+ if (!next) return 'drops its check';+ if (next.command !== old.command) return 'changes its check command';+ if (next.count > old.count) return `raises count: from ${old.count} to ${next.count}`;+ if (old.mode === 'hold' && next.mode === 'watch') return 'sets mode: watch';+ if (old.runs === 'submit' && next.runs === 'nightly') return 'moves its check to runs: nightly';+ return '';+}++/** Read one file's committed bytes at a revision, or null when the revision lacks it. */+function gitShow(root, revision, file) {+ const result = spawnSync('git', ['--no-replace-objects', 'show', `${revision}:${file}`], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ return result.status === 0 ? result.stdout : null;+}++/** Run git for a list of names or a commit id, or null when git refuses. */+function gitOut(root, args) {+ const result = spawnSync('git', ['--no-replace-objects', '-c', 'core.quotepath=false', ...args], { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ return result.status === 0 ? result.stdout : null;+}++/**+ * The approved check rules in the doctrine committed at a revision, following the conventional+ * DOCTRINE.md / PRACTICE.md rename so a renamed file keeps its rules.+ *+ * @param {string} root+ * @param {string} revision+ * @param {string} [name] - The configured doctrine file.+ * @returns {ReturnType<typeof checkRule>[]}+ */+export function checkRulesAt(root, revision, name = DOCTRINE_FILE) {+ let source = gitShow(root, revision, name);+ if (source === null && [DOCTRINE_FILE, LEGACY_DOCTRINE_FILE].includes(name)) {+ source = gitShow(root, revision, name === DOCTRINE_FILE ? LEGACY_DOCTRINE_FILE : DOCTRINE_FILE);+ }+ if (source === null) return [];+ let parsed;+ try { parsed = parseSpec(source, { strictGrammarVersion: false }); } catch { return []; }+ return parsed.rows.filter((row) => row.status === 'approved').map(checkRule).filter(Boolean);+}++/**+ * Run one check where it stands and keep each non-empty output line as a problem. The exit status+ * is not read: `grep` exits 1 when it finds nothing, which is zero problems.+ *+ * @param {string} cwd+ * @param {string} command+ * @param {number} timeoutMs+ * @returns {{ problems: string[], broken: string, seconds: number }}+ */+export function runRuleCheck(cwd, command, timeoutMs = DEFAULT_TIMEOUT_MS) {+ const started = Date.now();+ const result = spawnSync(`(\n${command}\n) 2>&1`, {+ cwd, env: gitChildEnv(cwd), shell: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8',+ timeout: timeoutMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 * 1024,+ });+ invalidateGitFacts();+ const seconds = Math.round((Date.now() - started) / 1000);+ if (result.error) {+ const broken = result.error.code === 'ETIMEDOUT' ? `timed out after ${Math.round(timeoutMs / 1000)}s` : `could not run (${result.error.code ?? 'error'})`;+ return { problems: [], broken, seconds };+ }+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`;+ return { problems: output.split(/\r?\n/u).map((line) => line.trimEnd()).filter((line) => line.trim()), broken: '', seconds };+}++/**+ * The repo paths a check command names at a revision: the files it watches. A command that names+ * no existing path watches the whole repo.+ *+ * @param {string} root+ * @param {string} revision+ * @param {string} command+ * @returns {string[]}+ */+export function ruleScope(root, revision, command) {+ const words = command.split(/\s+/u)+ .map((word) => word.replace(/^['"]|['"]$/gu, '').replace(/^\.\//u, '').replace(/\/+$/u, ''))+ .filter((word) => word && !word.startsWith('-') && !/[*?[\]{}$`|;&<>()]/u.test(word) && !word.startsWith('/') && !word.split('/').includes('..'));+ return [...new Set(words)].filter((word) => gitOut(root, ['rev-parse', '--verify', '--quiet', `${revision}:${word}`]) !== null);+}++/** True when a changed path is one of a rule's watched paths or lies under one. */+function inScope(scope, path) {+ return !scope.length || scope.some((watched) => path === watched || path.startsWith(`${watched}/`));+}++/** True when a problem line names a file, as `path:...`, `./path:...` or the bare path. */+function namesFile(line, file) {+ const text = line.trim();+ return text === file || text.startsWith(`${file}:`) || text.startsWith(`./${file}:`) || text.includes(` ${file}:`) || text.includes(` ./${file}:`);+}++/** A problem line without its line number, so a moved problem is not counted as new. */+function problemKey(line) {+ return line.replace(/:\d+:/u, '::').trim();+}++/** The lines in `after` beyond those in `before`, compared without line numbers. */+function newLines(before, after) {+ const left = new Map();+ for (const line of before) left.set(problemKey(line), (left.get(problemKey(line)) ?? 0) + 1);+ return after.filter((line) => {+ const key = problemKey(line);+ const remaining = left.get(key) ?? 0;+ if (remaining > 0) { left.set(key, remaining - 1); return false; }+ return true;+ });+}++/**+ * One rule's line, as `pullboard doctrine check` and submit print it:+ * `D9 No silent catch · 9, was 12 · holding`.+ *+ * @param {{ id: string, text: string, count: number, committed: number, state: string, broken?: string }} result+ * @returns {string}+ */+export function ruleLine(result) {+ const counts = result.broken ? `check ${result.broken}` : `${result.count}, was ${result.committed}`;+ return `${result.id} ${result.text} · ${counts} · ${result.state}`;+}++/** Name how a counted rule stands: watching never refuses; holding is at or below its count. */+function ruleState(rule, count, committed, broken) {+ if (rule.mode === 'watch') return 'watching';+ if (broken) return 'broken';+ return count <= committed ? 'holding' : 'rose';+}++/**+ * Count every committed rule's problems in this checkout (`pullboard doctrine check`). Rules come+ * from HEAD's committed doctrine; the command runs over the working tree, so a builder sees the+ * count its next commit would carry.+ *+ * @param {string} root+ * @param {{ practice?: string, check?: { timeoutMs?: number } }} config+ * @returns {{ id: string, text: string, command: string, count: number, committed: number, holds: boolean, state: string, mode: string, runs: string, problems: string[], broken: string }[]}+ */+export function doctrineReport(root, config) {+ return checkRulesAt(root, 'HEAD', config.practice).map((rule) => {+ const run = runRuleCheck(root, rule.command, config.check?.timeoutMs);+ const count = run.problems.length;+ const state = ruleState(rule, count, rule.count, run.broken);+ return { id: rule.id, text: rule.text, command: rule.command, count, committed: rule.count,+ holds: state === 'holding' || state === 'watching', state, mode: rule.mode, runs: rule.runs, problems: run.problems, broken: run.broken };+ });+}++/** True when the accepted main doctrine has a rule submit must run; a repo without one skips it all. */+export function hasSubmitRules(root, mainCommit, practice) {+ return checkRulesAt(root, mainCommit, practice).some((rule) => rule.runs === 'submit');+}++/** Run a check at an exact commit in a private shared clone, leaving every live worktree alone. */+function runAtCommit(root, commit, command, timeoutMs) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-doctrine-base-'));+ const checkout = join(directory, 'checkout');+ const env = gitChildEnv(root);+ try {+ const clone = spawnSync('git', ['clone', '--quiet', '--shared', '--no-checkout', '--', root, checkout], { env, stdio: 'ignore' });+ const selected = clone.status === 0 && spawnSync('git', ['-c', 'core.hooksPath=/dev/null', 'checkout', '--quiet', '--detach', commit], { cwd: checkout, env, stdio: 'ignore' });+ if (!selected || selected.status !== 0) return { problems: [], broken: 'could not check out the base commit', seconds: 0 };+ return runRuleCheck(checkout, command, timeoutMs);+ } finally {+ rmSync(directory, { recursive: true, force: true });+ }+}++/**+ * Hold the doctrine's counts for a submission. Rules, commands and modes come from accepted main;+ * the submitted commit may only lower a count. Each touched rule runs at the clean submitted+ * checkout; a changed file's problems are compared with the merge base only when it has any.+ * Refuses RATCHET_ROSE with the rule, its counts and the new problem lines.+ *+ * @param {string} root - The clean submitting checkout, at `commit`.+ * @param {{ mainCommit: string, commit: string, practice?: string, timeoutMs?: number }} options+ * @returns {ReturnType<typeof doctrineReport>}+ */+export function holdDoctrine(root, { mainCommit, commit, practice = DOCTRINE_FILE, timeoutMs = DEFAULT_TIMEOUT_MS }) {+ const rules = checkRulesAt(root, mainCommit, practice).filter((rule) => rule.runs === 'submit');+ if (!rules.length) return [];+ const lowered = new Map(checkRulesAt(root, commit, practice).map((rule) => [rule.id, rule.count]));+ const base = (gitOut(root, ['merge-base', mainCommit, commit]) ?? '').trim() || mainCommit;+ const changed = (gitOut(root, ['diff', '-z', '--no-renames', '--name-only', base, commit, '--']) ?? '').split('\0').filter(Boolean);+ const results = [];+ const refusals = [];+ for (const rule of rules) {+ const scope = ruleScope(root, commit, rule.command);+ if (!changed.some((path) => inScope(scope, path))) continue;+ const committed = Math.min(rule.count, lowered.get(rule.id) ?? rule.count);+ const run = runRuleCheck(root, rule.command, timeoutMs);+ const count = run.problems.length;+ const state = ruleState(rule, count, committed, run.broken);+ const result = { id: rule.id, text: rule.text, command: rule.command, count, committed,+ holds: state === 'holding' || state === 'watching', state, mode: rule.mode, runs: rule.runs, problems: run.problems, broken: run.broken };+ results.push(result);+ if (rule.mode === 'watch') continue;+ const name = `${rule.id} ${rule.text}`;+ if (run.broken) {+ refusals.push(`${name} cannot count: its check ${run.broken}`);+ continue;+ }+ const touched = changed.filter((path) => run.problems.some((line) => namesFile(line, path)));+ const before = touched.length ? runAtCommit(root, base, rule.command, timeoutMs) : { problems: [], broken: '' };+ if (count > committed) {+ const fresh = newLines(before.broken ? [] : before.problems, run.problems);+ refusals.push(`${name} rose to ${count}, was ${committed}; new problems:\n${(fresh.length ? fresh : run.problems).map((line) => ` ${line}`).join('\n')}`);+ continue;+ }+ if (before.broken) {+ refusals.push(`${name} cannot compare changed files: its check ${before.broken} at the base`);+ continue;+ }+ for (const path of touched) {+ const now = run.problems.filter((line) => namesFile(line, path));+ const then = before.problems.filter((line) => namesFile(line, path));+ if (now.length <= then.length) continue;+ const gained = now.length - then.length;+ const fresh = newLines(then, now);+ refusals.push(`${name}: ${path} gains ${gained} problem${gained === 1 ? '' : 's'}, had ${then.length}:\n${(fresh.length ? fresh : now).map((line) => ` ${line}`).join('\n')}`);+ }+ }+ if (refusals.length) {+ throw new Refused('RATCHET_ROSE', `${refusals.join('\n')}\nthe doctrine holds these counts; fix the new problems, commit, and submit again; only the person's signature raises count:`);+ }+ return results;+}diff --git a/src/help.js b/src/help.jsindex d2485849..caed775e 100644--- a/src/help.js+++ b/src/help.js@@ -155,6 +155,9 @@ Specpullboard spec approve <ids> | decline <ids> --reason "why" the person's exact-row decisionapprove <id> --text "new wording" approves an exact rewritepullboard spec apply coordinator applies recorded row decisions to the files+ pullboard doctrine check each doctrine rule's check: its count, its committed count, whether it holds+ a rule row adds | gate: check <command> | count: N; the command prints one line per problem+ submit refuses a touched rule whose count rises; runs: nightly skips submit, mode: watch only countsRole guidespullboard prompt decompose|plan|signoff|review|verify how to do each role; Claude Code gets them as skills@@ -173,7 +176,7 @@ const HELP_NAMES = ['serve', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'skills', 'show', 'next', 'land','check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import','sweep', 'merged', 'withdraw', 'refreeze', 'reopen', 'hold', 'stats', 'ledger', 'log', 'spec', 'spec check', 'spec view',- 'spec show', 'spec unmet', 'spec signoff', 'spec draft', 'spec signers', 'spec signers add', 'forget', 'prompt', 'gate', 'hook',+ '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',];@@ -201,6 +204,7 @@ const HELP_EXAMPLES = {escalate: 'pullboard escalate 12 --note "needs a manual step"', next: 'pullboard next',run: 'pullboard run --agent "node agent.js"', 'view export': 'pullboard view --export ./site','spec check': 'pullboard spec check',+ doctrine: 'pullboard doctrine check', 'doctrine check': 'pullboard doctrine check','spec view': 'pullboard spec view', 'spec show': 'pullboard spec show G1','spec draft': 'pullboard spec draft "Describe the first requirement"','spec unmet': 'pullboard spec unmet', 'spec signoff': 'pullboard spec signoff G1',@@ -223,6 +227,7 @@ const HELP_ALIASES = {'spec signoff': { usage: 'pullboard spec signoff <ids> [--by <principal>] [--note "..."] [--note-file <file>]', source: 'spec show', onlyFlags: ['--by', '--note', '--note-file'], extraFlags: ['--note-file <file>'] },'spec signers': { usage: 'pullboard spec signers add [--key <path>] [--by <principal>]', source: 'spec signers add' },'spec signers add': { usage: 'pullboard spec signers add [--key <path>] [--by <principal>]', source: 'spec signers add' },+ doctrine: { usage: 'pullboard doctrine check', source: 'doctrine check' },hook: { usage: 'pullboard hook pre-commit|pre-merge-commit|commit-msg|pre-push', source: 'hook' },'hook pre-commit': { usage: 'pullboard hook pre-commit', source: 'hook' },'hook pre-merge-commit': { usage: 'pullboard hook pre-merge-commit', source: 'hook' },diff --git a/src/json.js b/src/json.jsindex cb556f2c..9da3391e 100644--- a/src/json.js+++ b/src/json.js@@ -81,6 +81,7 @@ export const JSON_SHAPES = {'spec approve': shape({ decisions: 'array' }),'spec decline': shape({ decisions: 'array' }),'spec apply': shape({ applied: 'array', files: 'array' }),+ 'doctrine check': shape({ rules: 'array' }),'hook pre-commit': shape({ messages: 'array' }),'hook pre-merge-commit': shape({ messages: 'array' }),'hook commit-msg': shape({ messages: 'array' }),diff --git a/src/machine.js b/src/machine.jsindex d8548350..c7e51c1e 100644--- a/src/machine.js+++ b/src/machine.js@@ -120,6 +120,7 @@ export const GUARDS = [{ id: 'withinLane', refuse: 'OUTSIDE_LANE', alsoRefuses: [{ code: 'NO_POLICY', next: 'restore the claim base or ask the coordinator to refreeze' }, { code: 'BAD_CONFIG', next: 'restore the committed coordinator configuration' }, { code: 'GIT_GRAFTS', next: 'ask the coordinator to remove the Git graft file before retrying' }], rule: 'the full claimed diff respects committed coordinator ownership', next: 'restore foreign paths or shout their owner', source: 'cli' },{ id: 'trunkMergeClean', refuse: 'MERGE_CONFLICT', alsoRefuses: [{ code: 'MERGE_CHECK_FAILED', next: 'use Git 2.38 or newer, restore its objects and retry' }, { code: 'NO_POLICY', next: 'restore the primary repository metadata' }, { code: 'NO_TRUNK', next: 'check out the trunk branch in the main checkout once and run pullboard inbox' }], rule: 'the candidate merges cleanly into the current primary branch without changing an index or worktree', next: 'merge the trunk into your branch, resolve conflicts, commit and resubmit', source: 'cli' },{ id: 'noUnverifiedStack', refuse: 'STACKED_ON_UNVERIFIED', rule: "the candidate range contains no other item's unverified submitted commit", next: 'wait for that item to be accepted, or rebuild without its commits', source: 'cli' },+ { id: 'doctrineHolds', refuse: 'RATCHET_ROSE', rule: "no touched doctrine check rises above its committed count and no changed file gains a problem; watch-mode rules only count", next: "fix the new problems, commit, submit again; only the person's signature raises count:", source: 'cli', when: 'only when accepted main has an approved doctrine rule with gate: check' },{ id: 'itemCheckGreen', refuse: 'CHECK_RED', alsoRefuses: [{ code: 'CHECK_UNVERIFIED', next: 'restore the frozen install or check environment and retry' }], rule: 'the frozen item check passes at the exact submitted commit', next: 'reject the failing behavior; the builder fixes and resubmits', source: 'cli' },{ id: 'gateGreen', refuse: 'GATE_RED', alsoRefuses: [{ code: 'PIPEFAIL_UNAVAILABLE', next: 'rewrite the gate without a pipe' }], rule: 'the gate, which submit runs itself every time, is green at HEAD', next: 'fix what the digest names, commit, submit again', source: 'cli' },@@ -155,7 +156,7 @@ export const MOVES = [{ verb: 'lapse', from: ['claimed'], to: 'open', by: ['clock'], guards: [], when: 'its lease runs out' },{verb: 'submit', from: ['claimed'], to: 'submitted', by: ['agent', 'coordinator'], refuse: 'NOT_YOURS',- guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'correctionRefrozen', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'noUnverifiedStack', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],+ guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'correctionRefrozen', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'noUnverifiedStack', 'doctrineHolds', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'childrenDone', 'headIsNew'],sets: ['item_built_by', 'item_commit'], command: 'pullboard submit <id>',},{diff --git a/src/spec.js b/src/spec.jsindex 00ac4d4b..3fa4966a 100644--- a/src/spec.js+++ b/src/spec.js@@ -30,19 +30,33 @@ const SECTION_RE = /^##\s+(.+)$/;const SIGNER_RE = /^(?!#)[^\s,]+$/u;const LEGACY_SIGNER_RE = /^[A-Z][A-Za-z]{1,11}$/;+const FIELD_NAMES = ['gate', 'serves', 'signers', 'count', 'runs', 'mode'];+/*** One row's trailing fields, after the text: `| gate: ...`, `| serves: a, b` and `| signers: CO,AB`.+ * A doctrine rule may add `| count: N`, `| runs: nightly` and `| mode: watch` to a `gate: check`;+ * those keys appear on the row only when written, so rows without them parse exactly as before.+ * A check command may itself contain ` | `: a part that names no known field continues it.** @param {string} rest- * @returns {{ text: string, gate: string, serves: string[], signers: string[], unknown: string[] }}+ * @returns {{ text: string, gate: string, serves: string[], signers: string[], unknown: string[], count?: string, runs?: string, mode?: string }}*/function splitFields(rest) {const [text = '', ...parts] = rest.split(' | ');const fields = { text: text.trim(), gate: '', serves: [], signers: [], unknown: [] };+ let inCheck = false;for (const part of parts) {const [key = '', ...value] = part.split(':');const joined = value.join(':').trim();- if (key.trim() === 'gate') fields.gate = joined;+ if (inCheck && !FIELD_NAMES.includes(key.trim())) {+ fields.gate += ` | ${part.trim()}`;+ continue;+ }+ inCheck = false;+ if (key.trim() === 'gate') {+ fields.gate = joined;+ inCheck = /^check(\s|$)/u.test(joined);+ } else if (['count', 'runs', 'mode'].includes(key.trim())) fields[key.trim()] = joined;else if (key.trim() === 'serves') {fields.serves = joined.split(',').map((id) => id.trim()).filter(Boolean);} else if (key.trim() === 'signers') {@@ -176,10 +190,33 @@ function rowFindings(row, maxWords) {if (new Set(row.signers ?? []).size !== (row.signers ?? []).length) add('error', 'signers are unique on a row');const words = row.text.split(/\s+/).filter(Boolean).length;if (words > maxWords) add('warning', `${words} words; rows stay under ${maxWords}, the why goes elsewhere`);- for (const part of row.unknown) add('error', `unknown field "${part}"; fields are gate, serves and signers`);+ for (const part of row.unknown) add('error', `unknown field "${part}"; fields are gate, serves, signers, count, runs and mode`);+ findings.push(...checkFieldFindings(row).map((message) => ({ level: 'error', line: row.line, id: row.id, message })));return findings;}+/**+ * Problems with a row's check fields: a `gate: check` names its command and a whole-number count,+ * `runs` is submit or nightly, `mode` is hold or watch, and none of them stands without a check.+ *+ * @param {any} row+ * @returns {string[]}+ */+export function checkFieldFindings(row) {+ const isCheck = /^check(\s|$)/u.test(row.gate ?? '');+ const problems = [];+ if (!isCheck) {+ if (['count', 'runs', 'mode'].some((key) => row[key] !== undefined)) problems.push('count, runs and mode belong to a row whose gate is check <command>');+ return problems;+ }+ if (!row.gate.slice('check'.length).trim()) problems.push('gate: check names the command that prints one line per problem');+ if (row.count === undefined) problems.push('a check row names its committed count: | count: N');+ else if (!/^\d+$/u.test(row.count)) problems.push(`count "${row.count}" is a whole number`);+ if (row.runs !== undefined && !['submit', 'nightly'].includes(row.runs)) problems.push(`runs "${row.runs}" is submit or nightly`);+ if (row.mode !== undefined && !['hold', 'watch'].includes(row.mode)) problems.push(`mode "${row.mode}" is hold or watch`);+ return problems;+}+/*** The first cycle in the serves graph, as the ids around it, or null.*diff --git a/src/templates.js b/src/templates.jsindex 4ca3e3fe..c69a226a 100644--- a/src/templates.js+++ b/src/templates.js@@ -102,7 +102,7 @@ This repo runs on pullboard: a work board, lanes and a spec that live in git. No**Source of truth.** \`SPEC.md\` holds every requirement as a row with an id, like \`G1.2\`. Code follows the spec. Commits cite the ids they serve: \`feat(scope): subject [G1.2]\`. Only a person approves or changes an approved row. Ids are permanent: a row the person cuts stays, marked \`wont\` (won't build), so every commit that cites it keeps its meaning. Propose each requirement with \`pullboard spec draft "<text>"\`; it returns the draft row id for the person to approve.-**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. Run pullboard spec --json to read the current merged rules. Re-run pullboard init after changing the doctrine to refresh this managed guidance.+**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.### Current doctrinediff --git a/test/api.test.js b/test/api.test.jsindex 965afe14..9f87bd93 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -619,6 +619,7 @@ test('[A1] command results match the catalog across roots and subcommands', () =json(box, repo, 'spec', ['--json']);json(box, repo, 'spec', ['check'], 'check');+ assert.deepEqual(json(box, repo, 'doctrine', ['check'], 'check').rules, [], 'a repo with no check rows reports no rules [D1]');json(box, repo, 'spec', ['view', '--out', join(box.dir, 'spec.html')], 'view');json(box, repo, 'spec', ['show', 'G1'], 'show');json(box, repo, 'spec', ['unmet'], 'unmet');diff --git a/test/doctrine-checks.test.js b/test/doctrine-checks.test.jsnew file mode 100644index 00000000..c06858a4--- /dev/null+++ b/test/doctrine-checks.test.js@@ -0,0 +1,108 @@+/** A doctrine rule can carry a check whose count only falls, held at submit [D1,D3]. */+import assert from 'node:assert/strict';+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { after, test } from 'node:test';+import { createE2eHelpers } from './e2e-helpers.js';++const e2e = createE2eHelpers();+after(e2e.cleanup);+const { project } = e2e;++const RULE = '- Q1 [approved, must] Web pages carry no TODO markers. | gate: check grep -rn TODO web';++/**+ * A project whose doctrine has one check rule with the given trailing fields, two problems on+ * main, a web worktree that carries main, and a claimed web item.+ */+function checkedProject(fields, extraRows = []) {+ const box = project();+ appendFileSync(join(box.repo, 'DOCTRINE.md'), `\n## Q · Quality\n${[`${RULE} | ${fields}`, ...extraRows].join('\n')}\n`);+ mkdirSync(join(box.repo, 'web'));+ writeFileSync(join(box.repo, 'web', 'a.html'), 'TODO one\nTODO two\n');+ box.git(box.repo, 'add', '-A');+ box.git(box.repo, 'commit', '-q', '-m', 'chore: add the quality doctrine');+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');+ assert.equal(box.run(box.repo, 'add', 'web', 'Page', '--specs', 'G1').code, 0);+ assert.equal(box.run(box.web, 'claim', '1').code, 0);+ return box;+}++/** Write web files in the worktree and commit them through its hooks. */+function commitWeb(box, files, message) {+ for (const [name, text] of Object.entries(files)) writeFileSync(join(box.web, 'web', name), text);+ box.git(box.web, 'add', '-A');+ const committed = box.tryGit(box.web, 'commit', '-q', '-m', message);+ assert.equal(committed.status, 0, `${committed.stdout}${committed.stderr}`);+}++/** Replace the rule's committed fields on main and try to commit them through the hooks. */+function editRule(box, from, to) {+ const file = join(box.repo, 'DOCTRINE.md');+ const before = readFileSync(file, 'utf8');+ assert.ok(before.includes(from), `the doctrine holds ${from}`);+ writeFileSync(file, before.replace(from, to));+ box.git(box.repo, 'add', 'DOCTRINE.md');+ return box.tryGit(box.repo, 'commit', '-q', '-m', 'chore: change the quality count');+}++test("a doctrine rule's check holds its count [D1,D3]", () => {+ const box = checkedProject('count: 2');++ // A rise above the committed count is refused, naming the rule, the counts and the new line.+ commitWeb(box, { 'b.html': 'TODO three\n' }, 'feat(web): add a page [G1]');+ const rose = box.run(box.web, 'submit', '1');+ assert.equal(rose.code, 1, rose.out);+ assert.match(rose.err, /RATCHET_ROSE/);+ assert.match(rose.err, /Q1 Web pages carry no TODO markers\. rose to 3, was 2/);+ assert.match(rose.err, /web\/b\.html:1:TODO three/);+ assert.doesNotMatch(rose.err, /web\/a\.html:1:TODO one/, 'only the new problem lines are named');++ // A changed file that gains a problem is refused even when the total falls.+ commitWeb(box, { 'a.html': 'done\n' }, 'feat(web): clear the old markers [G1]');+ const gained = box.run(box.web, 'submit', '1');+ assert.equal(gained.code, 1, gained.out);+ assert.match(gained.err, /RATCHET_ROSE/);+ assert.match(gained.err, /web\/b\.html gains 1 problem/);+ assert.match(gained.err, /web\/b\.html:1:TODO three/);++ // A fall passes and is shown as N, was M.+ commitWeb(box, { 'a.html': 'TODO two\n', 'b.html': 'done\n' }, 'feat(web): finish the page [G1]');+ const fell = box.run(box.web, 'submit', '1');+ assert.equal(fell.code, 0, fell.err);+ assert.match(fell.out, /Q1 Web pages carry no TODO markers\. · 1, was 2 · holding/);+ const report = box.run(box.web, 'doctrine', 'check');+ assert.equal(report.code, 0, report.err);+ assert.equal(report.out.trim(), 'Q1 Web pages carry no TODO markers. · 1, was 2 · holding');+ const json = JSON.parse(box.run(box.web, 'doctrine', 'check', '--json').out);+ assert.deepEqual(json.rules.map(({ id, count, committed, holds }) => ({ id, count, committed, holds })),+ [{ id: 'Q1', count: 1, committed: 2, holds: true }]);+ assert.deepEqual(json.rules[0].problems, ['web/a.html:1:TODO two']);++ // Raising count: needs the person's signature; lowering it is a normal commit.+ const raised = editRule(box, 'count: 2', 'count: 3');+ assert.notEqual(raised.status, 0, 'an unsigned raise is refused');+ assert.match(raised.stderr, /Q1 raises count: from 2 to 3 without the person's signature/);+ const lowered = editRule(box, 'count: 3', 'count: 1');+ assert.equal(lowered.status, 0, `${lowered.stdout}${lowered.stderr}`);+ writeFileSync(join(box.repo, 'DOCTRINE.md'), readFileSync(join(box.repo, 'DOCTRINE.md'), 'utf8').replace('count: 1', 'count: 4'));+ const approved = box.run(box.repo, 'spec', 'approve', 'doctrine:Q1');+ assert.equal(approved.code, 0, approved.err);+ box.git(box.repo, 'add', 'DOCTRINE.md');+ const signed = box.tryGit(box.repo, 'commit', '-q', '-m', 'chore: the person raises the quality count');+ assert.equal(signed.status, 0, `a raise the person approved commits: ${signed.stdout}${signed.stderr}`);+});++test("a doctrine rule's check holds its count in watch mode and nightly [D1,D3]", () => {+ const box = checkedProject('count: 0 | mode: watch',+ ['- Q2 [approved, must] Web pages stay TODO-free overnight. | gate: check grep -rn TODO web | count: 0 | runs: nightly']);+ commitWeb(box, { 'b.html': 'TODO three\n' }, 'feat(web): add a page [G1]');+ const watched = box.run(box.web, 'submit', '1');+ assert.equal(watched.code, 0, watched.err);+ assert.match(watched.out, /Q1 Web pages carry no TODO markers\. · 3, was 0 · watching/);+ assert.doesNotMatch(watched.out, /Q2/, 'a nightly rule does not run at submit');+ const report = box.run(box.web, 'doctrine', 'check');+ assert.equal(report.code, 1, 'the nightly rule that rose fails doctrine check');+ assert.match(report.out, /^Q1 Web pages carry no TODO markers\. · 3, was 0 · watching$/m);+ assert.match(report.out, /^Q2 Web pages stay TODO-free overnight\. · 3, was 0 · rose$/m);+});diff --git a/test/machine.test.js b/test/machine.test.jsindex 34cf542e..cc41cf27 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -69,10 +69,11 @@ const CALLBACKS = { 'board.js': { freeze: 'cli.js#freezer' } };/*** Calls whose refusals an entry point catches and reports as another: submit and verify read a* cited row taken out of force as a changed criterion, CRITERIA_CHANGED. Submit also keeps its- * original gate refusal when a best-effort main comparison or its attribution cannot be read.+ * original gate refusal when a best-effort main comparison or its attribution cannot be read, and+ * reads committed doctrine rules leniently: a doctrine it cannot parse carries no check [D1].*/const CAUGHT = {- 'cli.js#submitHere': ['cli.js#freezer', 'main-red.js#compareMainFailures', 'main-red.js#matchingReworks'],+ 'cli.js#submitHere': ['cli.js#freezer', 'main-red.js#compareMainFailures', 'main-red.js#matchingReworks', 'doctrine-checks.js#checkRulesAt'],'cli.js#verifyHere': ['cli.js#freezer'],};@@ -803,7 +804,7 @@ test('pullboard help lists each role\'s moves from the declaration, and pullboar/** Guards checked before the explicit transition: CLI facts and optional roadmap selection. */const PRECHECKED = {claim: ['joined'],- submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'noUnverifiedStack'],+ submit: ['joined', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'doctrineHolds', 'gateConfigured', 'gateGreen', 'treeStillDuringGate', 'noUnverifiedStack'],reserve: ['coordinatorSaysAs', 'joined', 'roadmapReadable'],accept: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit', 'trunkMergeClean', 'itemCheckGreen', 'noUnverifiedStack'],reject: ['coordinatorSaysAs', 'joined', 'atSubmittedCommit'],