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.

chore(core): merge main into doctrine rulings [D1,D3,B27]

Corey Olson9fa8de528e18
diff --cc docs/api.md
index b394ac44,6d09e627..3baf3b82
--- a/docs/api.md
+++ b/docs/api.md
@@@ -51,9 -63,10 +63,10 @@@ For example: `flow: review wait averag
| `join` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string`, `model:string`, `displayName:string` |
| `takeover` | `version:number`, `agent:string`, `path:string` |
| `worktree` | `version:number`, `agent:string`, `lane:string`, `route:string`, `path:string`, `branch:string`, `prompt:string`, `model:string`, `displayName:string` |
- | `resume` | `version:number`, `me:object`, `all:array`, `requests:array`, `holding:array`, `sentBack:array`, `awaiting:array`, `toVerify:array`, `toMerge:array`, `open:array`, `stale:array`, `doctrineNotes:array`, `holds:array`, `unread:number`, `newest:array`, `root:string`, `dirty:number`, `next:string` |
-| `resume` | `version:number`, `me:object`, `all:array`, `requests:array`, `holding:array`, `sentBack:array`, `awaiting:array`, `toVerify:array`, `toMerge:array`, `open:array`, `stale:array`, `holds:array`, `unread:number`, `newest:array`, `root:string`, `newWorktreeLocation:string`, `dirty:number`, `next:string` |
++| `resume` | `version:number`, `me:object`, `all:array`, `requests:array`, `holding:array`, `sentBack:array`, `awaiting:array`, `toVerify:array`, `toMerge:array`, `open:array`, `stale:array`, `doctrineNotes:array`, `holds:array`, `unread:number`, `newest:array`, `root:string`, `newWorktreeLocation:string`, `dirty:number`, `next:string` |
| `whoami` | `version:number`, `id:string`, `lane:string`, `path:string`, `model:string`, `displayName:string` |
| `lanes` | `version:number`, `lanes:object`, `shared:array`, `coordinator:string` |
+ | `lane add` | `version:number`, `lane:string`, `owns:array` |
| `resources` | `version:number`, `resources:array` |
| `settings` | `version:number`, `settings:object` |
| `runner` | `version:number`, `runner:object` |
@@@ -124,9 -140,7 +140,9 @@@
| `hook pre-push` | `version:number`, `messages:array` |
<!-- api-command-shapes:end -->
+`spec draft "<rule>" --doctrine --source "chat, 2026-10-16"` proposes a sourced doctrine row and returns a qualified `id`, such as `doctrine:DR1`, for the existing person approval commands. Resume adds `doctrineNotes`, an array of newly seen approved rules with `id`, `text` and `gate`; each checkout consumes its own notices. Drafts and pending applications are excluded. The shared approved doctrine also supplies frozen citations and stale-item comparisons in older checkouts.
+
- `hook pre-merge-commit` runs the same staged checks as `hook pre-commit` before Git creates an automatic merge commit. `init` and `hooks` install it; `doctor` names it when absent at Git's effective hook path. Lane ownership comes from `HEAD:pullboard.json`, so an unstaged configuration edit cannot grant a lane new folders. Lane-sensitive checks refuse a repository with `info/grafts` in its Git common directory because grafts alter ancestry even when replacement objects are disabled.
+ `hook pre-merge-commit` runs the same staged checks as `hook pre-commit` before Git creates an automatic merge commit. `init` and `hooks` install it; `doctor` names it when absent at Git's effective hook path. Lane ownership comes from `HEAD:pullboard.json`, so an unstaged configuration edit cannot grant a lane new folders. `lane add` writes the new lane to the working `pullboard.json` and returns `{ lane, owns }`; commit the file before the lane's ownership takes effect. `init` returns the lanes it proposes as `proposedLanes`, each `{ name, owns }`, and writes none of them. Lane-sensitive checks refuse a repository with `info/grafts` in its Git common directory because grafts alter ancestry even when replacement objects are disabled.
`join` and `worktree` require a free-text `--model` label or `PULLBOARD_MODEL` environment value; labels are not inferred from a provider or family. Rejoining the same worktree preserves its agent id; the model label is required on every join, and omitting the optional `--family` preserves its prior declaration. `pullboard.json` may set `agents.names` to `suffix` (the default, `web-1 (Claude)`) or `prefix` (`claude-web-1`). CLI `agent` fields remain stable ids; `displayName` shows the chosen style. `resume.me` and API state `agents[]` carry `model` and `displayName`; older agents with no model display `unknown`. Each event records the actor model in `event_detail.model` for a registered agent, with `unknown` for legacy agents without a declaration. `show` includes `item_builder_family` and each verdict's `verdict_verifier_family`. These family fields are `null` when the agent did not declare a family, and later declarations do not rewrite prior submissions or verdicts.
diff --cc src/cli.js
index 667f3718,ccf54309..d10b4c09
--- a/src/cli.js
+++ b/src/cli.js
@@@ -13,16 -13,12 +13,13 @@@ import { parseArgs } from 'node:util'
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 {
- appliedDoctrine,
- doctrineFromSource,
- doctrineHistory,
- loadDoctrine,
- } from './doctrine.js';
+ import { doctrineHistory, loadDoctrine } from './doctrine.js';
++import { agentDoctrine, proposeDoctrine, resumeDoctrineNotes, staleDoctrineRows } from './doctrine-rulings.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';
- import { digestOf, gateReport, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';
+ import { decisionAnswer, decisionProjection, handAnsweredQuestions, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';
+ import { digestOf, gateReport, refuseSandboxBlocked, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';
import { checkNeedsBrowser } 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';
import {
@@@ -1341,11 -1280,11 +1284,13 @@@ function boardSetup(ctx, card, identity
function resumeHere(io) {
const ctx = context(io);
const { root, isMain } = ctx.info;
+ const mainRoot = primaryCheckoutRoot(ctx.info);
+ const worktreeConfig = mainRoot ? (isMain ? ctx.config : loadConfig(mainRoot)) : null;
let setupScope;
+ let doctrine;
const card = withBoard(ctx, (board) => {
setupScope = setupIdentity(board);
+ doctrine = agentDoctrine(ctx, board);
const me = whoAmI(ctx, board);
const all = store.listItems(board, { all: true });
const toMerge = all.filter((item) => item.item_status === 'verified' && !item.item_merged_commit);
@@@ -1377,9 -1319,12 +1325,12 @@@
});
card.relayProblems = unlinkedRelayProjects();
card.hookProblems = unwiredHookProblems(root);
+ card.newWorktreeLocation = mainRoot
+ ? worktreeLocation(mainRoot, worktreeConfig)
+ : unavailableWorktreeLocation();
const { me } = card;
const name = (id) => agentDisplayName(card.agents, ctx.config, id);
- card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows, ctx.doctrine.rows).map((item) => ({ ...item, ...staleItemFinding(item) }));
+ card.stale = staleFrozenItems(card.all, loadSpec(root, ctx.config).rows, staleDoctrineRows(ctx, doctrine)).map((item) => ({ ...item, ...staleItemFinding(item) }));
if (isMain) {
card.staleFollowUps = { count: card.stale.length + card.staleIntegrations.length,
list: 'pullboard resume --json', items: card.stale, integrations: card.staleIntegrations };
@@@ -3262,12 -3366,13 +3374,13 @@@ async function specCommand(io, { first
unmet: ['must'],
signoff: ['by', 'note', 'note-file'],
signers: ['key', 'by'],
- draft: ['aim', 'gate', 'section'],
+ draft: ['aim', 'gate', 'section', 'doctrine', 'source'],
approve: ['by', 'text'],
decline: ['reason'],
+ answer: [],
apply: [],
}[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" | apply');
+ 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'])];
for (const flag of Object.keys(values)) {
if (!allowedFlags.includes(flag)) {
@@@ -3286,13 -3391,6 +3399,19 @@@
if (values.gate !== undefined && (!values.gate.trim() || /[\r\n|]/u.test(values.gate))) {
throw new Refused('USAGE', 'give one nonempty, single-line gate without a field separator, or omit --gate to use review');
}
+ if (values.doctrine) {
++ if (typeof values.source !== 'string' || !values.source.trim() || /[\r\n|]/u.test(values.source)) {
++ throw new Refused('USAGE', 'a doctrine ruling needs its source; give --source "shout 42" or --source "chat, 2026-10-16"');
++ }
++ withBoard(ctx, (board) => {
++ if (!ctx.info.isMain || whoAmI(ctx, board).id !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'only the coordinator proposes standing rulings; ask your coordinator to run spec draft --doctrine --source');
++ });
+ const result = proposeDoctrine(ctx, values, second);
+ io.result?.(result);
+ io.say(result.id);
+ 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);
diff --cc src/doctrine-rulings.js
index 00000000,00000000..8364df7d
new file mode 100644
--- /dev/null
+++ b/src/doctrine-rulings.js
@@@ -1,0 -1,0 +1,156 @@@
++/**
++ * Standing rulings the person approves become doctrine every agent reads [D1,D3,B27].
++ *
++ * The coordinator proposes a ruling as a sourced draft doctrine row; only the person approves or
++ * declines it, through the ordinary spec approve and decline commands. Once applied, every
++ * checkout reads it from the primary branch plus the person's applied row decisions, so an old
++ * worktree sees it without moving its branch, and each checkout's next resume names it once.
++ */
++import { createHash } from 'node:crypto';
++import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
++import { dirname, join } from 'node:path';
++import * as store from './board.js';
++import { CONFIG_FILE, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE } from './config.js';
++import { appliedDoctrine, doctrineFromSource, loadDoctrine } from './doctrine.js';
++import { git, mainCheckout, resolveCommit, tryGit } from './git.js';
++import { Refused } from './refused.js';
++import { writeRowApply } from './row-decisions.js';
++import { loadSpec } from './spec.js';
++import { policyAt, trunkRef } from './trusted-policy.js';
++
++/**
++ * Read one doctrine file at a commit, falling back to the other default name the way loadDoctrine
++ * does, so a repo that still uses the legacy file name keeps its rules.
++ *
++ * @param {string} root
++ * @param {string} commit
++ * @param {string} name
++ * @returns {{ name: string, source: string | null }}
++ */
++function doctrineAt(root, commit, name) {
++ const source = tryGit(root, ['show', `${commit}:${name}`]);
++ if (source.status === 0) return { name, source: source.stdout };
++ if ([DOCTRINE_FILE, LEGACY_DOCTRINE_FILE].includes(name)) {
++ const alias = name === DOCTRINE_FILE ? LEGACY_DOCTRINE_FILE : DOCTRINE_FILE;
++ const other = tryGit(root, ['show', `${commit}:${alias}`]);
++ if (other.status === 0) return { name: alias, source: other.stdout };
++ }
++ return { name, source: null };
++}
++
++/**
++ * The doctrine in force for any agent: the primary branch's committed doctrine plus the person's
++ * applied exact-row decisions. Why not this checkout's file: an old worktree would never see a
++ * ruling approved after it branched.
++ *
++ * @param {any} ctx the CLI context
++ * @param {any} board
++ * @returns {any} a composed doctrine, as loadDoctrine returns
++ */
++export function agentDoctrine(ctx, board) {
++ const root = ctx.info.root;
++ const primary = mainCheckout(root);
++ const retained = primary?.commit ? null : trunkRef(root);
++ const commit = primary?.commit ?? (retained ? resolveCommit(root, retained) : null);
++ let doctrine = ctx.doctrine;
++ let name = doctrine.name;
++ if (commit && tryGit(root, ['show', `${commit}:${CONFIG_FILE}`]).status === 0) {
++ const read = doctrineAt(root, commit, policyAt(root, commit).config.practice);
++ name = read.name;
++ doctrine = doctrineFromSource(read.source, name);
++ }
++ const entry = git(root, ['worktree', 'list', '--porcelain', '-z']).split('\0')[0];
++ const primaryRoot = entry.startsWith('worktree ') ? entry.slice('worktree '.length) : null;
++ const file = primaryRoot && join(primaryRoot, name);
++ const current = file && existsSync(file) ? readFileSync(file, 'utf8') : null;
++ return appliedDoctrine(doctrine, store.rowDecisions(board), current);
++}
++
++/**
++ * The doctrine rows a stale check compares frozen citations with: the shared rules, overlaid only
++ * with rows this checkout actually edited since HEAD. Why the overlay: a local edit must still
++ * flag its item stale, without the old local file hiding a newer shared ruling.
++ *
++ * @param {any} ctx the CLI context
++ * @param {any} doctrine the shared doctrine from agentDoctrine
++ * @returns {any[]}
++ */
++export function staleDoctrineRows(ctx, doctrine) {
++ const working = loadDoctrine(ctx.info.root, ctx.config);
++ const committed = doctrineFromSource(doctrineAt(ctx.info.root, 'HEAD', working.name).source, working.name);
++ const before = new Map(committed.rows.map(row => [row.id, row]));
++ const current = new Map(working.rows.map(row => [row.id, row]));
++ const rows = new Map(doctrine.rows.map(row => [row.id, row]));
++ for (const id of new Set([...before.keys(), ...current.keys()])) {
++ if (before.get(id)?.text === current.get(id)?.text) continue;
++ if (current.has(id)) rows.set(id, current.get(id));
++ else rows.delete(id);
++ }
++ return [...rows.values()];
++}
++
++/**
++ * The approved repo rulings this checkout has not yet been shown, recorded so each is named once.
++ * The record lives under this checkout's Git directory, so every other checkout keeps its own
++ * notice, the way resume release notes work.
++ *
++ * @param {{ gitDir: string }} info
++ * @param {any} doctrine the shared doctrine from agentDoctrine
++ * @returns {{ id: string, text: string, gate: string }[]}
++ */
++export function resumeDoctrineNotes(info, doctrine) {
++ const record = join(info.gitDir, 'pullboard-checkout', 'resume-doctrine.json');
++ let previous = {};
++ try { previous = JSON.parse(readFileSync(record, 'utf8')); } catch { /* First doctrine resume. */ }
++ if (!previous || typeof previous !== 'object' || Array.isArray(previous)) previous = {};
++ const approved = doctrine.rows.filter(row => row.origin === 'repo' && row.status === 'approved');
++ /** Identify the exact approved guidance this checkout has already displayed. */
++ const fingerprint = row => createHash('sha256').update(JSON.stringify([row.text, row.gate])).digest('hex');
++ const notes = approved.filter(row => previous[row.id] !== fingerprint(row))
++ .map(row => ({ id: 'doctrine:' + row.id, text: row.text, gate: row.gate }));
++ mkdirSync(dirname(record), { recursive: true });
++ writeFileSync(record, JSON.stringify({ ...previous, ...Object.fromEntries(approved.map(row => [row.id, fingerprint(row)])) }) + '\n', { mode: 0o600 });
++ return notes;
++}
++
++/**
++ * Append one sourced ruling as a draft doctrine row, never approving it or touching another row.
++ * The caller has already checked that the coordinator is asking.
++ *
++ * @param {any} ctx the CLI context
++ * @param {{ source?: string, section?: string, aim?: boolean, gate?: string }} values
++ * @param {string} text the ruling
++ * @returns {{ id: string, row: { id: string, status: string, tier: string, text: string, gate: string, section: string } }}
++ */
++export function proposeDoctrine(ctx, values, text) {
++ const doctrine = ctx.doctrine;
++ if (!doctrine.repoExists) throw new Refused('NO_SPEC', `no ${doctrine.name}; run pullboard init before proposing doctrine`);
++ if (doctrine.repo.problems.length) throw new Refused('SPEC_INVALID', `fix the unparsed row in ${doctrine.name} before proposing a ruling`);
++ const sections = doctrine.repo.sections.map(section => ({ ...section,
++ prefix: /^([A-Z][A-Z0-9]*)\s*[·.:-]/u.exec(section.name)?.[1] })).filter(section => section.prefix);
++ const prefix = values.section ?? 'DR';
++ const section = sections.find(section => section.prefix === prefix);
++ if (!section && values.section) throw new Refused('SPEC_SECTION', `unknown section "${prefix}" in ${doctrine.name}; use a declared section or omit --section for rulings`);
++ const used = [...loadSpec(ctx.info.root, ctx.config).rows, ...doctrine.rows];
++ const numbers = used.map(row => new RegExp(`^${prefix}(\\d+)$`, 'u').exec(row.id)?.[1]).filter(Boolean).map(Number);
++ const id = `${prefix}${Math.max(0, ...numbers) + 1}`;
++ const tier = values.aim ? 'aim' : 'must';
++ const gate = values.gate?.trim() ?? 'review';
++ const ruling = `${text.trim()} Source: ${values.source.trim()}`;
++ const row = `- ${id} [draft, ${tier}] ${ruling} | gate: ${gate}`;
++ const source = readFileSync(doctrine.repo.file, 'utf8');
++ const newline = source.includes('\r\n') ? '\r\n' : '\n';
++ const lines = source.split(/\r?\n/u);
++ if (section) {
++ const following = doctrine.repo.sections.find(entry => entry.line > section.line);
++ let insertion = following ? following.line - 1 : lines.length;
++ while (insertion > section.line && !lines[insertion - 1].trim()) insertion -= 1;
++ lines.splice(insertion, 0, row);
++ } else {
++ while (lines.length && !lines.at(-1).trim()) lines.pop();
++ lines.push('', '## DR · Rulings', row, '');
++ }
++ writeRowApply(ctx.info.root, { records: [], files: [{ file: doctrine.name, before: source, after: lines.join(newline) }],
++ signoffs: { before: null, receipts: [] } });
++ return { id: 'doctrine:' + id, row: { id, status: 'draft', tier, text: ruling, gate, section: section?.name ?? 'DR · Rulings' } };
++}
diff --cc src/help.js
index d445792b,f04bad16..0b461dc6
--- a/src/help.js
+++ b/src/help.js
@@@ -248,9 -273,9 +274,10 @@@ const HELP_FLAG_EXPLANATIONS =
'--blueprint': 'start from a bundled blueprint or a JSON file',
'--brief': 'what a cold agent needs',
'--check': 'the command that proves it',
+ '--doctrine': 'proposes a doctrine ruling; only the person can approve it',
'--family': 'records the family name',
'--model': 'identifies the agent model; required unless PULLBOARD_MODEL is set',
+ '--implies': 'each named item gets a fact citing this decision',
'--landing': 'prioritizes a trunk landing in the machine gate queue',
'--json': 'prints one versioned document',
'--note': 'what was checked stays with the receipt',
diff --cc src/json.js
index 845c1184,8397aaf0..0d6ea0a2
--- a/src/json.js
+++ b/src/json.js
@@@ -17,9 -17,10 +17,10 @@@ export const JSON_SHAPES =
join: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', model: 'string', displayName: 'string' }),
takeover: shape({ agent: 'string', path: 'string' }),
worktree: shape({ agent: 'string', lane: 'string', route: 'string', path: 'string', branch: 'string', prompt: 'string', model: 'string', displayName: 'string' }),
- resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', stale: 'array', doctrineNotes: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', dirty: 'number', next: 'string' }),
- resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', stale: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', newWorktreeLocation: 'string', dirty: 'number', next: 'string' }),
++ resume: shape({ me: 'object', all: 'array', requests: 'array', holding: 'array', sentBack: 'array', awaiting: 'array', toVerify: 'array', toMerge: 'array', open: 'array', stale: 'array', doctrineNotes: 'array', holds: 'array', unread: 'number', newest: 'array', root: 'string', newWorktreeLocation: 'string', dirty: 'number', next: 'string' }),
whoami: shape({ id: 'string', lane: 'string', path: 'string', model: 'string', displayName: 'string' }),
lanes: shape({ lanes: 'object', shared: 'array', coordinator: 'string' }),
+ 'lane add': shape({ lane: 'string', owns: 'array' }),
resources: shape({ resources: 'array' }),
settings: shape({ settings: 'object' }),
runner: shape({ runner: 'object' }),
diff --cc test/doctrine-rulings.test.js
index 95728643,00000000..0e9fea39
mode 100644,000000..100644
--- a/test/doctrine-rulings.test.js
+++ b/test/doctrine-rulings.test.js
@@@ -1,151 -1,0 +1,185 @@@
+/** Person-approved rulings reach independent, unadvanced Git checkouts [D1,D3,B27]. */
+import assert from 'node:assert/strict';
+import {
+ readFileSync,
+ writeFileSync,
+} from 'node:fs';
- import { join } from 'node:path';
++import { join, resolve } from 'node:path';
+import { test } from 'node:test';
++import { pathToFileURL } from 'node:url';
+import { createE2eHelpers } from './e2e-helpers.js';
++import { runFixtureChild } from './fixture-child.js';
+import { parseSpec } from '../src/spec.js';
+
++/** Send one move through the agent API's executeMove, as an agent tool or the relay would. */
++function apiMove(box, cwd, move) {
++ const api = pathToFileURL(resolve(import.meta.dirname, '../src/api.js')).href;
++ const cli = pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href;
++ const source = `
++ const { executeMove } = await import(${JSON.stringify(api)});
++ const { main } = await import(${JSON.stringify(cli)});
++ process.stdout.write(JSON.stringify(await executeMove(process.cwd(), ${JSON.stringify(move)}, main, undefined, 'api')));
++ `;
++ const child = runFixtureChild(process.execPath, ['--input-type=module', '-e', source], { cwd, env: box.env, encoding: 'utf8' });
++ assert.equal(child.status, 0, child.stdout + child.stderr);
++ return JSON.parse(child.stdout);
++}
++
++/** Run the real CLI with extra environment, such as an agent shell's marker. */
++function runWith(box, cwd, env, ...args) {
++ const result = runFixtureChild(process.execPath, [resolve(import.meta.dirname, '../bin/pullboard.js'), ...args],
++ { cwd, env: { ...box.env, ...env }, encoding: 'utf8' });
++ return { code: result.status, out: result.stdout, err: result.stderr };
++}
++
+test('a ruling the person approves reaches every agent once [D1,D3,B27]', (t) => {
+ const e2e = createE2eHelpers();
+ t.after(e2e.cleanup);
+ const box = e2e.project('true');
+ const other = join(box.dir, 'web-2');
+ box.git(box.repo, 'worktree', 'add', '-q', '-b', 'web/two', other);
+ const joined = box.run(other, 'join', 'web', '--model', 'Fixture');
+ assert.equal(joined.code, 0, joined.err || joined.out);
+ const checkouts = [box.repo, box.web, other];
+ const oldHeads = checkouts.map(path => box.git(path, 'rev-parse', 'HEAD'));
+ /** Run a real CLI command and require its public, versioned successful result. */
+ function json(path, ...args) {
+ const result = box.run(path, ...args, '--json');
+ assert.equal(result.code, 0, result.err || result.out);
+ return JSON.parse(result.out);
+ }
+ for (const path of checkouts) assert.deepEqual(json(path, 'resume').doctrineNotes ?? [], []);
+ const file = join(box.repo, 'DOCTRINE.md');
+ const before = readFileSync(file, 'utf8');
+ const missing = box.run(box.repo, 'spec', 'draft', 'Keep the approved ruling.', '--doctrine', '--json');
+ assert.notEqual(missing.code, 0, 'a proposal without its source is refused');
+ assert.equal(readFileSync(file, 'utf8'), before, 'a source-less proposal writes no row');
+
+ const rule = 'A builder escalates after two failed attempts.';
+ const drafted = json(box.repo, 'spec', 'draft', rule, '--doctrine', '--source', 'chat, 2026-10-16');
+ assert.match(JSON.parse(missing.out).error.message, /source/iu);
+ assert.equal(drafted.id, 'doctrine:' + drafted.row.id);
+ const row = parseSpec(readFileSync(file, 'utf8')).rows.find(row => row.id === drafted.row.id);
+ assert.equal(row.status, 'draft');
+ assert.ok(row.text.includes(rule) && row.text.includes('chat, 2026-10-16'), 'the proposed row keeps its source');
+ const foreign = box.run(box.web, 'spec', 'draft', 'A builder cannot propose standing rules.',
+ '--doctrine', '--source', 'shout 42', '--json');
+ assert.notEqual(foreign.code, 0);
+ assert.equal(JSON.parse(foreign.out).error.code, 'COORDINATOR_ONLY');
+ for (const path of checkouts) assert.deepEqual(json(path, 'resume').doctrineNotes, [], 'draft rulings are not announced');
++ const unchanged = readFileSync(file, 'utf8');
++ const shell = runWith(box, box.repo, { CLAUDECODE: '1' }, 'spec', 'approve', drafted.id, '--json');
++ assert.notEqual(shell.code, 0, 'an agent shell cannot approve a ruling');
++ assert.equal(JSON.parse(shell.out).error.code, 'B26_PERSON_CHANNEL');
++ const builder = box.run(box.web, 'spec', 'approve', drafted.id, '--json');
++ assert.notEqual(builder.code, 0, 'a builder worktree cannot approve a ruling');
++ assert.match(JSON.parse(builder.out).error.code, /^B26_PERSON/u);
++ const viaApi = apiMove(box, box.repo, { verb: 'spec-approve', args: { ids: drafted.id } });
++ assert.equal(viaApi.status, 409, JSON.stringify(viaApi));
++ assert.equal(viaApi.body.error.code, 'B26_PERSON_CHANNEL', 'the agent API is not the person channel');
++ assert.equal(readFileSync(file, 'utf8'), unchanged, 'refused approvals leave the draft alone');
+ box.git(box.repo, 'add', 'DOCTRINE.md');
+ box.git(box.repo, 'commit', '-q', '-m', 'docs(doctrine): propose ruling');
+ for (const path of checkouts) assert.deepEqual(json(path, 'resume').doctrineNotes, [], 'a committed draft is not in force either');
+ json(box.repo, 'spec', 'approve', drafted.id);
+ for (const path of checkouts) assert.deepEqual(json(path, 'resume').doctrineNotes, [], 'pending apply is not in force');
+ json(box.repo, 'spec', 'apply');
+ const mainNotes = json(box.repo, 'resume').doctrineNotes;
+ assert.equal(mainNotes.length, 1);
+ assert.equal(mainNotes[0].id, drafted.id);
+ assert.equal(mainNotes[0].text, row.text);
+ const text = box.run(box.web, 'resume');
+ assert.equal(text.code, 0, text.err || text.out);
+ assert.ok(text.out.includes(`new doctrine ${drafted.id} — ${row.text}`));
+ assert.deepEqual(json(other, 'resume').doctrineNotes, mainNotes, 'each checkout sees the same approved ruling');
+ for (const path of checkouts) assert.deepEqual(json(path, 'resume').doctrineNotes, [], 'the notice is consumed only in this checkout');
+ assert.equal(box.git(box.web, 'rev-parse', 'HEAD'), oldHeads[1]);
+ assert.equal(box.git(other, 'rev-parse', 'HEAD'), oldHeads[2]);
+ assert.ok(!readFileSync(join(box.web, 'DOCTRINE.md'), 'utf8').includes(rule), 'no fixture silently synchronizes the old worktree');
+
+ const item = json(box.repo, 'add', 'web', 'Follow the approved ruling', '--specs', drafted.id,
+ '--criterion', 'The builder follows the approved ruling.', '--check', 'true').item;
+ json(box.web, 'claim', String(item.item_id));
+ const frozen = JSON.parse(json(box.web, 'show', String(item.item_id)).item_frozen);
+ assert.deepEqual(frozen.rows.map(row => [row.id, row.text]), [[drafted.id, row.text]], 'claim freezes shared approved text');
+ assert.equal(box.git(box.web, 'rev-parse', 'HEAD'), oldHeads[1], 'a doctrine citation does not advance the checkout');
+ box.git(box.repo, 'add', 'DOCTRINE.md');
+ box.git(box.repo, 'commit', '-q', '-m', `docs(doctrine): approve ruling [${drafted.id}]`);
+
+ const replacement = 'A builder stops after two failed attempts. Source: chat, 2026-10-16';
+ json(box.repo, 'spec', 'approve', drafted.id, '--text', replacement);
+ assert.deepEqual(json(box.web, 'resume').stale, [], 'an unapplied change does not replace the in-force ruling');
+ json(box.repo, 'spec', 'apply');
+ const changed = json(box.web, 'resume');
+ assert.ok(changed.stale.some(entry => entry.id === item.item_id && entry.rows.includes(drafted.id)), 'the old checkout detects the changed frozen row');
+ assert.equal(changed.doctrineNotes[0].text, replacement);
+ const again = json(box.web, 'resume');
+ assert.deepEqual(again.doctrineNotes, []);
+ assert.ok(again.stale.some(entry => entry.id === item.item_id), 'staleness remains after its one-time notice');
+
+ const declined = json(box.repo, 'spec', 'draft', 'A ruling the person declines.', '--doctrine', '--source', 'shout 42');
+ json(box.repo, 'spec', 'decline', declined.id, '--reason', 'The person declines this proposal.');
+ json(box.repo, 'spec', 'apply');
+ assert.ok(json(other, 'resume').doctrineNotes.every(note => note.id !== declined.id), 'declined rulings are never announced');
+
+ box.git(box.repo, 'add', 'DOCTRINE.md');
+ box.git(box.repo, 'commit', '-q', '-m', `docs(doctrine): revise ruling [${drafted.id}]`);
+ const approvedSource = readFileSync(file, 'utf8');
+ const retiredSource = approvedSource.replace(`- ${drafted.row.id} [approved, must]`, `- ${drafted.row.id} [retired, must]`);
+ assert.notEqual(retiredSource, approvedSource);
+ writeFileSync(file, retiredSource);
+ box.git(box.repo, 'add', 'DOCTRINE.md');
+ box.git(box.repo, 'commit', '-q', '-m', 'docs(doctrine): retire ruling');
+ // An old applied receipt must not revive a retired committed rule via an unstaged restoration.
+ writeFileSync(file, approvedSource);
+ assert.ok(json(other, 'resume').doctrineNotes.every(note => note.id !== drafted.id), 'committed retirement wins over a stale receipt and working-copy restoration');
+ const retiredItem = json(box.repo, 'add', 'web', 'Do not revive the retired ruling', '--specs', drafted.id,
+ '--criterion', 'A stale applied receipt cannot revive committed retirement.', '--check', 'true').item;
+ const refused = box.run(other, 'claim', String(retiredItem.item_id), '--json');
+ assert.notEqual(refused.code, 0, 'the stale receipt cannot make a retired rule claimable');
+ assert.equal(JSON.parse(refused.out).error.code, 'UNKNOWN_SPEC');
+ assert.equal(json(other, 'show', String(retiredItem.item_id)).item_status, 'open', 'refusal leaves the item unclaimed');
+});
+
+test('local doctrine edits flag their frozen row without hiding shared approved rulings [D1,S19,V3]', (t) => {
+ const e2e = createE2eHelpers();
+ t.after(e2e.cleanup);
+ const box = e2e.project('true');
+ const oldHead = box.git(box.web, 'rev-parse', 'HEAD');
+ /** Exercise the real private CLI and retain its complete successful JSON result. */
+ function json(path, ...args) {
+ const result = box.run(path, ...args, '--json');
+ assert.equal(result.code, 0, result.err || result.out);
+ return JSON.parse(result.out);
+ }
+ const drafted = json(box.repo, 'spec', 'draft', 'Keep shared approved guidance visible.',
+ '--doctrine', '--source', 'chat, 2026-10-16');
+ box.git(box.repo, 'add', 'DOCTRINE.md');
+ box.git(box.repo, 'commit', '-q', '-m', 'docs(doctrine): propose shared guidance');
+ json(box.repo, 'spec', 'approve', drafted.id);
+ json(box.repo, 'spec', 'apply');
+ const shared = json(box.repo, 'add', 'web', 'Follow shared guidance', '--specs', drafted.id,
+ '--criterion', 'Shared approved guidance stays in force.', '--check', 'true').item;
+ const edited = json(box.repo, 'add', 'web', 'Follow inherited guidance', '--specs', 'doctrine:PB1',
+ '--criterion', 'A changed local row remains visible to diagnostics.', '--check', 'true').item;
+ for (const item of [shared, edited]) {
+ json(box.web, 'claim', String(item.item_id));
+ json(box.web, 'release', String(item.item_id));
+ }
+ const frozen = [shared, edited].map(item => json(box.web, 'show', String(item.item_id)).item_frozen);
+ const baseline = json(box.web, 'resume');
+ assert.deepEqual(baseline.stale, [], 'unchanged old-checkout files retain the shared approved rule');
+ assert.ok(baseline.doctrineNotes.some(note => note.id === drafted.id));
+ const file = join(box.web, 'DOCTRINE.md');
+ const original = readFileSync(file, 'utf8');
+ assert.ok(!original.includes('Keep shared approved guidance visible.'));
+ writeFileSync(file, original + '\n## Local diagnostic edit\n- PB1 [approved, must] A changed local inherited rule. | gate: true\n');
+ const changed = json(box.web, 'resume');
+ assert.deepEqual(changed.stale.map(item => [item.id, item.rows]), [[edited.item_id, ['doctrine:PB1']]],
+ 'only the locally edited rule is stale; shared approved guidance is still available');
+ assert.deepEqual(changed.doctrineNotes, [], 'an unapproved working-copy edit is not announced as new guidance');
+ assert.equal(box.git(box.web, 'rev-parse', 'HEAD'), oldHead, 'diagnostics never advance the old checkout');
+ assert.deepEqual([shared, edited].map(item => json(box.web, 'show', String(item.item_id)).item_frozen), frozen);
+ writeFileSync(file, original);
+ assert.deepEqual(json(box.web, 'resume').stale, [], 'restoring the working file clears only its diagnostic change');
+});