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(spec): qualify doctrine citations [A5]
Corey Olsonc28d86709d78
diff --git a/docs/formats.md b/docs/formats.mdindex a1e90eb3..c444d90e 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -42,6 +42,10 @@ After the requirement text, `gate:` names the check, `serves:` names comma-separThe row object returned by `parseSpec` has these fields:+### ID namespaces and collisions++A bare id names a row in `SPEC.md`. A doctrine row is cited as `doctrine:<id>` in item spec ids and commit headers, even when a row with the same bare id exists in `SPEC.md`. `spec check` compares the current rows in `SPEC.md` and `PRACTICE.md`, and rows within either file. Collisions already present in `HEAD` are reported as known warnings; adding a colliding row is an error that names both file paths and line numbers. A commit that cites a bare id shared with a doctrine row warns that the bare id resolves to `SPEC.md`; use the `doctrine:` prefix to cite the doctrine row.+`parseSpec` also returns `grammarVersion`, equal to `SPEC_GRAMMAR_VERSION` after the file's marker has been checked.<!-- parser-fields:start -->diff --git a/docs/formats.test.js b/docs/formats.test.jsindex 93b54f39..316611aa 100644--- a/docs/formats.test.js+++ b/docs/formats.test.js@@ -39,6 +39,13 @@ import { ID_RE, SPEC_GRAMMAR_VERSION, STATUSES, TIERS, lintSpec, parseSpec } froconst guide = readFileSync(new URL('./formats.md', import.meta.url), 'utf8');+test('formats guide documents collision grandfathering and doctrine citations [A5]', () => {+ assert.match(guide, /A bare id names a row in `SPEC\.md`/u);+ assert.match(guide, /`doctrine:<id>` in item spec ids and commit headers/u);+ assert.match(guide, /Collisions already present in `HEAD` are reported as known warnings/u);+ assert.match(guide, /adding a colliding row is an error that names both file paths and line numbers/u);+});+/** Return the text inside a named marked documentation block. */function block(start, end) {const begin = guide.indexOf(start);diff --git a/src/cli.js b/src/cli.jsindex 49efe669..20ef7306 100644--- a/src/cli.js+++ b/src/cli.js@@ -16,6 +16,7 @@ import {FIX_NOTE,applyFixers,commitMsgProblems,+ commitCitationWarnings,installHooks,preCommitProblems,prePushProblems,@@ -33,6 +34,7 @@ import {lintSpec,loadSpec,permanenceProblems,+ parseSpec,readSignoffs,signOff,standings,@@ -424,7 +426,7 @@ function whoAmI(ctx, board) {* @param {any} ctx* @returns {(item: any) => { text: string, digest: string }}*/-const freezer = (ctx) => (item) => frozenCriterion(loadSpec(ctx.info.root, ctx.config), item);+const freezer = (ctx) => (item) => frozenCriterion(loadSpec(ctx.info.root, ctx.config), item, ctx.doctrine);/*** The evidence a shout carries, from its flags (B22). The commit is resolved here, in this repo,@@ -1346,7 +1348,7 @@ function workCommands(io, args) {add: () => act((ctx, board, me) => {if (!first || !isLane(ctx.config, first)) throw new Refused('NO_LANE', `no lane "${first ?? ''}"; see: pullboard lanes`);const specIds = idList(values.specs);- const problems = idProblems(loadSpec(ctx.info.root, ctx.config), specIds);+ const problems = idProblems(loadSpec(ctx.info.root, ctx.config), specIds, ctx.doctrine);if (problems.length) throw new Refused('UNKNOWN_SPEC', `${problems.join('; ')}`);const parentId = values.parent ? idArg(values.parent, 'a parent item id') : null;const after = idList(values.after).map((text) => idArg(text, 'an item id after --after'));@@ -1588,27 +1590,44 @@ function specCommand(io, { first, second, rest, values }) {if (first === 'check' || first === undefined) {const files = [[ctx.config.spec, spec], ...(practice.exists ? [[ctx.config.practice, practice]] : [])];for (const [, parsed] of files) assertRequiredSigners(ctx.info.root, parsed.rows);- const repeatedAcrossFiles = new Map(files.map(([name]) => [name, []]));- const firstLocation = new Map();- for (const [name, parsed] of files) {+ const collisionFiles = [[ctx.config.spec, spec], ...(practice.repoExists ? [[ctx.config.practice, practice.repo]] : [])];+ const previousCounts = new Map(collisionFiles.map(([name]) => {+ const previous = tryGit(ctx.info.root, ['show', `HEAD:${name}`]);+ const rows = previous.status === 0 ? parseSpec(previous.stdout, { strictGrammarVersion: false }).rows : [];+ const counts = new Map();+ for (const row of rows) counts.set(row.id, (counts.get(row.id) ?? 0) + 1);+ return [name, counts];+ }));+ const locationsById = new Map();+ for (const [name, parsed] of collisionFiles) {for (const row of parsed.rows) {- const first = firstLocation.get(row.id);- if (first && first.name !== name) {- repeatedAcrossFiles.get(first.name).push({- level: 'error', line: first.line, id: row.id,- message: `duplicate id; also appears at ${name}:${row.line}`,- });- repeatedAcrossFiles.get(name).push({- level: 'error', line: row.line, id: row.id,- message: `duplicate id; also appears at ${first.name}:${first.line}`,- });- } else if (!first) firstLocation.set(row.id, { name, line: row.line });+ const locations = locationsById.get(row.id) ?? [];+ locations.push({ name, line: row.line });+ locationsById.set(row.id, locations);+ }+ }+ const collisionFindings = new Map(collisionFiles.map(([name]) => [name, []]));+ for (const [id, locations] of locationsById) {+ if (locations.length < 2) continue;+ const currentCounts = new Map();+ for (const location of locations) currentCounts.set(location.name, (currentCounts.get(location.name) ?? 0) + 1);+ const known = [...currentCounts].every(([name, count]) => count <= (previousCounts.get(name)?.get(id) ?? 0));+ for (let index = 0; index < locations.length; index++) {+ const location = locations[index];+ const other = locations[(index + 1) % locations.length];+ collisionFindings.get(location.name).push({+ level: known ? 'warning' : 'error', line: location.line, id,+ message: `${known ? 'known duplicate id' : 'duplicate id'}; also appears at ${other.name}:${other.line}`,+ });}}let errors = 0;const messages = [];for (const [name, parsed] of files) {- const findings = [...lintSpec(parsed), ...repeatedAcrossFiles.get(name)];+ const findings = [+ ...lintSpec(parsed).filter((finding) => !finding.message.startsWith('duplicate id;')),+ ...(collisionFindings.get(name) ?? []),+ ];findings.forEach((finding) => messages.push(`${name}:${finding.line} ${finding.id ?? ''} ${finding.level}: ${finding.message}`.replace(' ', ' ')));const history = committedIds(ctx.info.root, name);const cited = name === ctx.config.spec ? citations(ctx, history) : new Map();@@ -1740,7 +1759,10 @@ async function hookCommand(io, { first, second }) {problems = preCommitProblems({ root: info.root, isMain: info.isMain, config: ctx.config, agent });} else if (first === 'commit-msg') {const message = readFileSync(second ?? '', 'utf8');- problems = commitMsgProblems(message, { rules: ctx.config.commits, spec: loadSpec(info.root, ctx.config) });+ const spec = loadSpec(info.root, ctx.config);+ commitCitationWarnings(message, { spec, doctrine: ctx.doctrine })+ .forEach((warning) => io.say(`pullboard commit-msg: warning: ${warning}`));+ problems = commitMsgProblems(message, { rules: ctx.config.commits, spec, doctrine: ctx.doctrine });} else if (first === 'pre-push') {problems = prePushProblems(info.root, await readStdin(io.stdin));if (!problems.length) {diff --git a/src/hooks.js b/src/hooks.jsindex 9e73ebc8..3c89edc9 100644--- a/src/hooks.js+++ b/src/hooks.js@@ -74,7 +74,7 @@ function headerProblems(header, rules) {* @param {{ rules: any, spec: any }} context* @returns {string[]}*/-export function commitMsgProblems(raw, { rules, spec }) {+export function commitMsgProblems(raw, { rules, spec, doctrine = null }) {const lines = raw.split('\n').filter((line) => !line.startsWith('#'));while (lines.length && !lines.at(-1)?.trim()) lines.pop();const [header = '', second, ...body] = lines;@@ -82,7 +82,7 @@ export function commitMsgProblems(raw, { rules, spec }) {const { problems, type } = headerProblems(header, rules);const ids = citedIds(header);problems.push(- ...idProblems(spec, ids).map(+ ...idProblems(spec, ids, doctrine).map((problem) => `cite only rows that exist and are live, separated by commas like [G1,G2] (${problem})`,),);@@ -102,6 +102,25 @@ export function commitMsgProblems(raw, { rules, spec }) {return problems;}+/**+ * Colliding bare citations keep their SPEC.md meaning, but tell the author how to name doctrine.+ *+ * @param {string} raw+ * @param {{ spec: any, doctrine: any }} context+ * @returns {string[]}+ */+export function commitCitationWarnings(raw, { spec, doctrine }) {+ const ids = citedIds(raw.split('\n')[0] ?? '').filter((id) => !id.startsWith('doctrine:'));+ return ids.flatMap((id) => {+ const locations = [+ ...spec.rows.filter((row) => row.id === id).map((row) => `${spec.name ?? 'SPEC.md'}:${row.line}`),+ ...(doctrine?.repo?.rows ?? []).filter((row) => row.id === id).map((row) => `${doctrine.name}:${row.line}`),+ ];+ if (locations.length < 2) return [];+ return [`${id} is a known collision at ${locations.slice(0, 2).join(' and ')}; bare ids cite SPEC.md, use doctrine:${id} for a doctrine row`];+ });+}+/*** Staged paths: every path the commit touches, and the ones it writes. An optional base lets a* merge check only differences from the merged commit. Deletions and both sides of a rename countdiff --git a/src/spec.js b/src/spec.jsindex 47d4e69d..c74476b6 100644--- a/src/spec.js+++ b/src/spec.js@@ -209,13 +209,20 @@ export function lintSpec(spec, { maxWords = 20 } = {}) {** @param {ReturnType<typeof parseSpec>} spec* @param {string[]} ids+ * @param {ReturnType<import('./doctrine.js').loadDoctrine>} [doctrine]* @returns {string[]} Problems; empty when every id is live.*/-export function idProblems(spec, ids) {+export function idProblems(spec, ids, doctrine = null) {const byId = new Map(spec.rows.map((row) => [row.id, row]));return ids.flatMap((id) => {- const row = byId.get(id);- if (!row) return [`${id} is not in ${spec.name ?? 'the spec'}`];+ const prefix = 'doctrine:';+ const namespaced = id.startsWith(prefix);+ const rawId = namespaced ? id.slice(prefix.length) : id;+ if (id.includes(':') && !namespaced) return [`${id} uses an unknown namespace; use doctrine:<id> for a doctrine row`];+ const row = namespaced+ ? doctrine?.rows.find((entry) => entry.id === rawId)+ : byId.get(rawId);+ if (!row) return [`${id} is not in ${namespaced ? 'doctrine' : spec.name ?? 'the spec'}`];if (row.status === 'retired') return [`${id} is retired`];if (row.status === 'wont') return [`${id} is marked won't build; the person reopens it first`];return [];@@ -229,14 +236,18 @@ export function idProblems(spec, ids) {** @param {ReturnType<typeof parseSpec>} spec* @param {{ item_title: string, item_criterion: string, item_spec_ids: string, item_check?: string }} item+ * @param {ReturnType<import('./doctrine.js').loadDoctrine>} [doctrine]* @returns {{ text: string, digest: string }}*/-export function frozenCriterion(spec, item) {+export function frozenCriterion(spec, item, doctrine = null) {const ids = item.item_spec_ids ? item.item_spec_ids.split(',') : [];- const problems = idProblems(spec, ids);+ const problems = idProblems(spec, ids, doctrine);if (problems.length) throw new Refused('UNKNOWN_SPEC', `${problems.join('; ')}; fix the spec, or the coordinator withdraws the item`);const rows = ids.map((id) => {- const row = spec.rows.find((entry) => entry.id === id);+ const [namespace, rawId] = id.startsWith('doctrine:') ? ['doctrine', id.slice('doctrine:'.length)] : ['spec', id];+ const row = namespace === 'doctrine'+ ? doctrine.rows.find((entry) => entry.id === rawId)+ : spec.rows.find((entry) => entry.id === rawId);return { id, text: row.text, gate: row.gate };});const check = item.item_check ? { check: item.item_check } : {};@@ -348,7 +359,7 @@ export function signOff(root, spec, { ids, by, on, note = '', commit = '' }) {* @returns {string[]}*/export function citedIds(header) {- const match = /\[([A-Za-z0-9.,\s]+)\]\s*$/.exec(header);+ const match = /\[([A-Za-z0-9:.,\s]+)\]\s*$/.exec(header);if (!match) return [];return match[1].split(',').map((id) => id.trim()).filter(Boolean);}diff --git a/test/e2e.test.js b/test/e2e.test.jsindex 81ab74e1..bdf4be97 100644--- a/test/e2e.test.js+++ b/test/e2e.test.js@@ -270,6 +270,30 @@ test('spec check lints both files; spec view writes one page into the git dir [Sassert.match(view.out, /open: file:\/\//);});+test('items and commit headers cite doctrine rows by namespace; bare collisions warn [A5]', () => {+ const box = project();+ const added = box.run(box.repo, 'add', 'web', 'Use the inherited rule', '--specs', 'doctrine:PB1');+ assert.equal(added.code, 0, added.err);+ assert.match(box.run(box.repo, 'show', '1').out, /\[doctrine:PB1\]/u);++ const message = join(box.dir, 'message.txt');+ writeFileSync(message, 'feat(web): use the inherited rule [doctrine:PB1]\n');+ const namespaced = box.run(box.repo, 'hook', 'commit-msg', message);+ assert.equal(namespaced.code, 0, namespaced.err);+ assert.doesNotMatch(namespaced.out, /warning:/u);++ const practice = readFileSync(join(box.repo, 'PRACTICE.md'), 'utf8');+ writeFileSync(join(box.repo, 'PRACTICE.md'), `${practice}\n## Local\n- G1 [draft] A local rule colliding with SPEC.md.\n`);+ writeFileSync(message, 'feat(web): use the product rule [G1]\n');+ const warning = box.run(box.repo, 'hook', 'commit-msg', message);+ assert.equal(warning.code, 0, warning.err);+ assert.match(warning.out, /warning: G1 is a known collision at SPEC\.md:4 and PRACTICE\.md:\d+; bare ids cite SPEC\.md/u);+ assert.match(warning.out, /use doctrine:G1 for a doctrine row/u);+ const check = box.run(box.repo, 'spec', 'check');+ assert.equal(check.code, 1);+ assert.match(check.out, /duplicate id; also appears at PRACTICE\.md:/u);+});+test('the board lives in the git common dir; every worktree sees it; nothing is committed [B1, B3]', () => {const box = project();assert.equal(box.run(box.repo, 'add', 'web', 'Build', 'the', 'page', '--specs', 'G1').out.trim(), '#1');diff --git a/test/hooks.test.js b/test/hooks.test.jsindex f238d6ab..635e8009 100644--- a/test/hooks.test.js+++ b/test/hooks.test.js@@ -4,7 +4,7 @@import assert from 'node:assert/strict';import { test } from 'node:test';import { defaults } from '../src/config.js';-import { addedLines, blockedPaths, commitMsgProblems, matchesPattern, secretsIn } from '../src/hooks.js';+import { addedLines, blockedPaths, commitCitationWarnings, commitMsgProblems, matchesPattern, secretsIn } from '../src/hooks.js';import { parseSpec } from '../src/spec.js';const SPEC = { ...parseSpec('## G\n- G1 [approved, must] One. | gate: t\n- G2 [retired] Gone.\n'), name: 'SPEC.md' };@@ -27,6 +27,20 @@ test('feat and fix cite ids; cited ids exist and are not retired [C2]', () => {assert.match(check('fix: patch [G2]')[0], /G2 is retired/);});+test('doctrine citations are namespaced; a colliding bare id warns that it resolves to SPEC.md [A5]', () => {+ const doctrine = {+ name: 'PRACTICE.md',+ repo: { rows: [{ id: 'G1', line: 4 }] },+ rows: [{ id: 'G1', status: 'approved' }, { id: 'PB1', status: 'approved' }],+ };+ assert.deepEqual(commitMsgProblems('feat(web): add the rule [doctrine:PB1]', { rules: RULES, spec: SPEC, doctrine }), []);+ assert.deepEqual(commitMsgProblems('feat(web): add the rule [doctrine:G1]', { rules: RULES, spec: SPEC, doctrine }), []);+ assert.match(commitMsgProblems('fix(web): add the rule [doctrine:missing]', { rules: RULES, spec: SPEC, doctrine })[0], /doctrine:missing is not in doctrine/u);+ assert.deepEqual(commitCitationWarnings('feat(web): patch the rule [G1]', { spec: SPEC, doctrine }), [+ 'G1 is a known collision at SPEC.md:2 and PRACTICE.md:4; bare ids cite SPEC.md, use doctrine:G1 for a doctrine row',+ ]);+});+test('header format, length, case and period [C1]', () => {assert.match(check('Added the page')[0], /type\(scope\): subject/);assert.match(check('Added the page')[0], /saw "Added the page"/, 'the refusal shows the header it saw (C4)');diff --git a/test/spec.test.js b/test/spec.test.jsindex d7a5cc31..062eef5c 100644--- a/test/spec.test.js+++ b/test/spec.test.js@@ -110,23 +110,34 @@ test('real spec check refuses future grammar in either configured file [A5]', (t});test('spec check names both locations when ids repeat within or across configured files [A5]', (t) => {- const practiceRow = '# Practice\n\n## P\n- G1 [draft] A local rule.\n';+ const practiceRow = '# Practice\n\n## P\n- P1 [draft] A local rule.\n';const crossFile = specBox(t, { practice: practiceRow });+ writeFileSync(join(crossFile.root, crossFile.practiceName), practiceRow.replace('P1', 'G1'));const cross = crossFile.run('check');assert.equal(cross.status, 1);assert.match(cross.stdout, /SPEC\.md:6 G1 error: duplicate id; also appears at PRACTICE\.md:4/u);assert.match(cross.stdout, /PRACTICE\.md:4 G1 error: duplicate id; also appears at SPEC\.md:6/u);- for (const [file, source, line] of [- ['SPEC.md', SPEC.replace('- G1.2 [draft, aim]', '- G1 [draft, aim]'), 7],- ['PRACTICE.md', '# Practice\n\n## P\n- P1 [draft] First.\n- P1 [draft] Second.\n', 5],- ]) {- const box = specBox(t, { practice: file === 'PRACTICE.md' ? source : undefined });- if (file === 'SPEC.md') writeFileSync(join(box.root, file), source);- const result = box.run('check');- assert.equal(result.status, 1);- assert.match(result.stdout, new RegExp(`${file}:${line} .*duplicate id; first on line`));- }+ const duplicateSpec = specBox(t);+ writeFileSync(join(duplicateSpec.root, 'SPEC.md'), SPEC.replace('- G1.2 [draft, aim]', '- G1 [draft, aim]'));+ const duplicateSpecResult = duplicateSpec.run('check');+ assert.equal(duplicateSpecResult.status, 1);+ assert.match(duplicateSpecResult.stdout, /SPEC\.md:7 G1 error: duplicate id; also appears at SPEC\.md:6/u);++ const duplicatePractice = specBox(t, { practice: practiceRow });+ writeFileSync(join(duplicatePractice.root, 'PRACTICE.md'), practiceRow.replace('- P1 [draft] A local rule.', '- P1 [draft] First.\n- P1 [draft] Second.'));+ const duplicatePracticeResult = duplicatePractice.run('check');+ assert.equal(duplicatePracticeResult.status, 1);+ assert.match(duplicatePracticeResult.stdout, /PRACTICE\.md:5 P1 error: duplicate id; also appears at PRACTICE\.md:4/u);+});++test('spec check lists collisions already present in HEAD as known warnings [A5]', (t) => {+ const practice = '# Practice\n\n## G\n- G1 [draft] A known local rule.\n';+ const box = specBox(t, { practice });+ const result = box.run('check');+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stdout, /SPEC\.md:6 G1 warning: known duplicate id; also appears at PRACTICE\.md:4/u);+ assert.match(result.stdout, /PRACTICE\.md:4 G1 warning: known duplicate id; also appears at SPEC\.md:6/u);});test('a grammar-1 repair can commit after grammar 2 was already recorded [A5,S8]', (t) => {@@ -217,6 +228,21 @@ test('cited ids must exist and must not be retired', () => {assert.deepEqual(idProblems(spec, ['G9', 'G2']), ['G9 is not in SPEC.md', 'G2 is retired']);});+test('doctrine ids use their own namespace when an id also exists in SPEC.md [A5]', () => {+ const spec = { ...parseSpec('## G\n- G1 [approved] Product rule.\n'), name: 'SPEC.md' };+ const doctrine = { rows: [+ { id: 'G1', status: 'approved', text: 'House rule.', gate: '' },+ { id: 'PB1', status: 'approved', text: 'Inherited rule.', gate: '' },+ ] };+ assert.deepEqual(idProblems(spec, ['G1', 'doctrine:G1', 'doctrine:PB1'], doctrine), []);+ assert.deepEqual(idProblems(spec, ['doctrine:PB9'], doctrine), ['doctrine:PB9 is not in doctrine']);+ assert.deepEqual(idProblems(spec, ['other:G1'], doctrine), ['other:G1 uses an unknown namespace; use doctrine:<id> for a doctrine row']);+ const frozen = frozenCriterion(spec, {+ item_title: 'Use the house rule', item_criterion: 'follow it', item_spec_ids: 'doctrine:G1',+ }, doctrine);+ assert.match(frozen.text, /"id":"doctrine:G1","text":"House rule\."/u);+});+test('the frozen criterion covers title, criterion and cited row text [V2]', () => {const item = { item_title: 'Load twice', item_criterion: 'second load adds nothing', item_spec_ids: 'G1' };const first = frozenCriterion(parseSpec(SPEC), item);@@ -249,6 +275,7 @@ test('a sign-off holds the text it approved; changing the row makes it stale [S5test('commit headers cite ids in a trailing bracket [C2]', () => {assert.deepEqual(citedIds('feat(web): add the page [G1, K1.2]'), ['G1', 'K1.2']);+ assert.deepEqual(citedIds('feat(web): add the rule [doctrine:PB1]'), ['doctrine:PB1']);assert.deepEqual(citedIds('feat(web): add the page'), []);assert.deepEqual(citedIds('fix: handle [x] in the middle of text'), []);});