@sabaiway/agent-workflow-kit 23.12.0 → 24.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +4 -4
  3. package/SKILL.md +1 -1
  4. package/bridges/codex-cli-bridge/SKILL.md +7 -2
  5. package/bridges/codex-cli-bridge/bin/codex-exec-jev.test.mjs +11 -6
  6. package/bridges/codex-cli-bridge/bin/codex-exec.sh +72 -33
  7. package/bridges/codex-cli-bridge/bin/codex-exec.test.mjs +111 -3
  8. package/bridges/codex-cli-bridge/bin/codex-fixtures-harness.test.mjs +16 -1
  9. package/bridges/codex-cli-bridge/bin/codex-model-posture.test.mjs +5 -3
  10. package/bridges/codex-cli-bridge/bin/codex-review.sh +1 -1
  11. package/bridges/codex-cli-bridge/capability.json +2 -2
  12. package/capability.json +1 -1
  13. package/package.json +1 -1
  14. package/references/advisor-writers.md +2 -0
  15. package/references/agents/author.md +21 -0
  16. package/references/agents/executor.md +12 -6
  17. package/references/contracts.md +4 -4
  18. package/references/hooks/gate-approve.mjs +7 -8
  19. package/references/hooks/stage-write-guard.mjs +314 -0
  20. package/references/modes/agents.md +6 -4
  21. package/references/modes/bootstrap.md +1 -1
  22. package/references/modes/flow-writer.md +10 -2
  23. package/references/modes/hook.md +4 -1
  24. package/references/modes/now.md +1 -1
  25. package/references/modes/procedures.md +49 -10
  26. package/references/modes/recipes.md +7 -7
  27. package/references/modes/recommendations.md +4 -3
  28. package/references/modes/robustness-brief.md +9 -8
  29. package/references/modes/set-recipe.md +1 -1
  30. package/references/modes/state-block-guard.md +4 -3
  31. package/references/modes/status.md +1 -1
  32. package/references/modes/upgrade.md +1 -1
  33. package/references/modes/worktrees.md +28 -5
  34. package/references/rules/story-sessions.md +2 -2
  35. package/references/scripts/archives/archive-caps.mjs +1 -1
  36. package/references/scripts/archives/archive-changelog.mjs +8 -8
  37. package/references/scripts/archives/archive-decisions.mjs +7 -7
  38. package/references/scripts/archives/archive-issues.mjs +5 -5
  39. package/references/scripts/archives/rotation-conservation.mjs +2 -1
  40. package/references/scripts/docs-size/check-docs-size.mjs +15 -15
  41. package/references/scripts/family.json +2 -0
  42. package/references/scripts/gates/kit-command-gates.mjs +7 -8
  43. package/references/scripts/gates/migrate-gates.mjs +10 -10
  44. package/references/scripts/git-hooks/install-git-hooks.mjs +13 -13
  45. package/references/scripts/run.mjs +1 -2
  46. package/references/scripts/shared/index.mjs +2 -0
  47. package/references/scripts/shared/locations.mjs +103 -0
  48. package/references/scripts/spec-schema/spec-schema.mjs +2 -1
  49. package/references/templates/orchestration.json +1 -1
  50. package/tools/ack-store.mjs +2 -1
  51. package/tools/apply-danger-check.mjs +20 -6
  52. package/tools/atomic-write.mjs +3 -2
  53. package/tools/attribution.mjs +2 -1
  54. package/tools/autonomy-config.mjs +2 -1
  55. package/tools/bridge-wiring.mjs +13 -11
  56. package/tools/carriers.mjs +54 -14
  57. package/tools/cheap-agents-read.mjs +28 -7
  58. package/tools/cheap-agents.mjs +15 -10
  59. package/tools/checker-gates-read.mjs +6 -5
  60. package/tools/commands.mjs +2 -2
  61. package/tools/coverage-declared/config.mjs +2 -1
  62. package/tools/coverage-producer.mjs +10 -9
  63. package/tools/delegation.mjs +7 -6
  64. package/tools/detect-backends.mjs +1 -1
  65. package/tools/dispatch-baseline.mjs +2 -1
  66. package/tools/distribution-files/scripts.mjs +4 -4
  67. package/tools/ensure-configs.mjs +2 -2
  68. package/tools/ensure-ops.mjs +24 -24
  69. package/tools/ensure-specs.mjs +7 -7
  70. package/tools/epic-shape-cli.mjs +2 -2
  71. package/tools/epic-shape-ledger.mjs +5 -5
  72. package/tools/epic-shape.mjs +5 -3
  73. package/tools/epic-store.mjs +2 -1
  74. package/tools/family-members.mjs +7 -5
  75. package/tools/family-registry.mjs +36 -30
  76. package/tools/feedback-record-cli.mjs +4 -5
  77. package/tools/flow-writer.mjs +26 -15
  78. package/tools/gate-hook.mjs +33 -28
  79. package/tools/gates-declaration.mjs +2 -1
  80. package/tools/gates-init.mjs +6 -5
  81. package/tools/git-hooks.mjs +64 -41
  82. package/tools/grounding.mjs +3 -2
  83. package/tools/hide-footprint.mjs +2 -1
  84. package/tools/hook-writer/index.mjs +147 -0
  85. package/tools/init-preflight.mjs +5 -4
  86. package/tools/init-project.mjs +12 -11
  87. package/tools/inject-methodology.mjs +3 -2
  88. package/tools/jev-guide.mjs +2 -2
  89. package/tools/known-footprint.mjs +27 -25
  90. package/tools/mcp-registration.mjs +6 -5
  91. package/tools/migration-blocks.mjs +2 -1
  92. package/tools/migration-notes.mjs +2 -2
  93. package/tools/node-evidence.mjs +4 -4
  94. package/tools/now-facts.mjs +5 -5
  95. package/tools/now-status.mjs +1 -5
  96. package/tools/orchestration-config.mjs +2 -1
  97. package/tools/orchestration-readme.mjs +7 -2
  98. package/tools/plan-approval/cli.mjs +45 -0
  99. package/tools/plan-approval/entries.mjs +109 -0
  100. package/tools/plan-approval/index.mjs +2 -0
  101. package/tools/plan-approval/record.mjs +198 -0
  102. package/tools/plan-files.mjs +6 -4
  103. package/tools/plan-shape-cli.mjs +10 -64
  104. package/tools/plan-shape-facts.mjs +240 -83
  105. package/tools/plan-shape.mjs +173 -160
  106. package/tools/plan-structure/cli.mjs +79 -0
  107. package/tools/plan-structure/index.mjs +67 -0
  108. package/tools/procedures.mjs +21 -17
  109. package/tools/profile-gaps.mjs +4 -6
  110. package/tools/project-rules/rules-priors.mjs +2 -0
  111. package/tools/project-rules/themes.mjs +6 -4
  112. package/tools/recipes.mjs +44 -29
  113. package/tools/recommendations.mjs +84 -33
  114. package/tools/reference-profile.mjs +2 -2
  115. package/tools/renderers.mjs +14 -8
  116. package/tools/repo-lex.mjs +84 -0
  117. package/tools/robustness-brief.mjs +14 -11
  118. package/tools/satellite-locator.mjs +3 -2
  119. package/tools/script-priors.mjs +3 -2
  120. package/tools/session-close-check.mjs +71 -15
  121. package/tools/set-flow.mjs +2 -2
  122. package/tools/set-recipe.mjs +17 -9
  123. package/tools/source-size/help.mjs +4 -4
  124. package/tools/source-size/layout.mjs +2 -1
  125. package/tools/source-size/piles.mjs +2 -2
  126. package/tools/source-size-config.mjs +3 -3
  127. package/tools/source-size-refusal.mjs +4 -3
  128. package/tools/source-size-report.mjs +41 -13
  129. package/tools/spec-check-cli.mjs +159 -21
  130. package/tools/spec-check-ops.mjs +74 -5
  131. package/tools/spec-check.mjs +54 -45
  132. package/tools/spec-coverage-cli.mjs +3 -2
  133. package/tools/stage-render/cli.mjs +231 -0
  134. package/tools/stage-render/index.mjs +340 -0
  135. package/tools/stage-render/stages.json +115 -0
  136. package/tools/stage-write-guard/cli.mjs +64 -0
  137. package/tools/stage-write-guard/index.mjs +56 -0
  138. package/tools/state-block-hook.mjs +38 -163
  139. package/tools/task-brief.mjs +8 -13
  140. package/tools/task-thread.mjs +3 -1
  141. package/tools/tier-guide-facts.mjs +23 -9
  142. package/tools/tier-preview.mjs +15 -19
  143. package/tools/transition/index.mjs +10 -9
  144. package/tools/uninstall.mjs +26 -12
  145. package/tools/vehicle-settings.mjs +2 -1
  146. package/tools/velocity-profile.mjs +5 -6
  147. package/tools/view-model.mjs +7 -4
  148. package/tools/worktree-prompt.mjs +7 -3
  149. package/tools/worktrees.mjs +235 -159
  150. package/tools/write-lanes.mjs +20 -14
@@ -1,10 +1,13 @@
1
1
  import { posix } from 'node:path';
2
2
  import { tokenizeMarkdown } from '../references/scripts/shared/index.mjs';
3
- import { parseRobustTag } from './robustness-literals.mjs';
3
+ import { SPEC_SCHEMA } from '../references/scripts/spec-schema/index.mjs';
4
4
  import { unique } from './claim-relation.mjs';
5
5
  import { checkStoryOwnership, PIN_FILE, PIN_VERBS } from './plan-shape-ownership.mjs';
6
+ import { AMENDMENT_LINE, checkRobustTags, relateAmendments } from './plan-structure/index.mjs';
7
+ import { escapeForLine } from './source-size-refusal.mjs';
6
8
 
7
9
  export const PLAN_TITLE_PREFIX = '# Plan: ';
10
+ export const ONE_PLAN_LABEL = 'One plan: ';
8
11
  export const PLAN_HEADINGS = Object.freeze([
9
12
  '## Goal and boundary',
10
13
  '## Module ledger',
@@ -12,21 +15,28 @@ export const PLAN_HEADINGS = Object.freeze([
12
15
  '## Phase: Cleanup',
13
16
  '## Next steps',
14
17
  ]);
18
+ export const RETIRED_FORM_CODES = Object.freeze({ sizeField: 'retired-size-field', totalLine: 'retired-total-line' });
15
19
 
16
20
  const MAX_PLAN_LINES = 100;
17
- const MAX_LEDGER_ROWS = 25;
21
+ const MAX_LEDGER_ROWS = 45;
18
22
  const MAX_ROW_BYTES = 200;
19
- const SECTION_CAPS = Object.freeze({
20
- '## Goal and boundary': 10,
21
- '## Module ledger': 60,
22
- '## Verification': 20,
23
- });
23
+ const SECTION_CAPS = new Map([[PLAN_HEADINGS[0], 10], [PLAN_HEADINGS[1], 60], [PLAN_HEADINGS[2], 20]]);
24
24
  const CLEANUP_NEXT_CAP = 10;
25
+ const CLEANUP_NEXT = 'Cleanup and Next steps';
26
+ const PLAN_QUESTION = 'is every part of this plan needed, does its work belong in one plan, and is the plan logical and optimal? ' +
27
+ `If so, say why on one line "${ONE_PLAN_LABEL}<why>" in Goal and boundary; if not, cut what is not needed or split it by task ` +
28
+ 'along independently verifiable boundaries, never to fit the count';
29
+ const ONE_PLAN_TWICE = 'keep only one reason line in Goal and boundary';
30
+ const ONE_PLAN_UNNEEDED = 'drop the reason line when the plan keeps every signal';
25
31
  const ROW_ID = /^[A-Za-z0-9._-]+$/;
26
32
  const VERBS = new Set(['create', 'modify', 'delete']);
27
33
  const GLOB_BYTE = /[*?[{]/;
28
- const TOTAL_LINE = /^total:\s+(~?\d+)\s+→\s+(~?\d+)\s+lines(?:\s+.+)?$/;
29
- const SPEC_LINE = /docs\/ai\/specs\/|(?:^|\W)(?:not adopted|adopting|nothing spec-covered touched)(?:\W|$)/;
34
+ const SWEEP = Object.freeze({ verb: 'modify', count: /\(([1-9]\d*) files\)/, countCode: 'sweep-count' });
35
+ const AMENDMENT_CHECK = Object.freeze({ code: 'amendment-check', message: `remove ${AMENDMENT_LINE} before approval` });
36
+ const TOTAL_PREFIX = 'total:';
37
+ const ROW_SEPARATOR = ' | ';
38
+ const ROW_FIELDS = 5;
39
+ const SPEC_LINE = /(?:^|\W)(?:not adopted|adopting|nothing spec-covered touched)(?:\W|$)/;
30
40
  const TEST_PATH = /(?:^|\/)\S+\.test\.[^/]+$/;
31
41
  const EXTENSION_PHASE = /^## Phase: (?!Cleanup\s*$)\S(?:.*\S)?$/;
32
42
  const BULLET = /^-\s+\S/;
@@ -36,31 +46,29 @@ export const isSweep = (path) => GLOB_BYTE.test(path);
36
46
  const endsWithPath = (path, suffix) => path === suffix || path.endsWith(`/${suffix}`);
37
47
  export { unique } from './claim-relation.mjs';
38
48
  const getFindingLine = (document, index) => document.frontLines + index + 1;
39
- const makeFinding = (line, code, message, rowId = null) => ({ line, code, message, rowId });
49
+ export const makeFinding = (line, code, message, rowId = null) => ({ line, code, message, rowId });
40
50
  const getHeading = (document, text) => document.headings.find((heading) => heading.text === text);
41
51
  const getNextSection = (document, heading) => document.headings.find((item) => item.index > heading.index && item.level <= 2);
42
52
  const getBodyEnd = (document) => document.lines.length - (document.lines.at(-1) === '' ? 1 : 0);
43
53
  const getSectionEnd = (document, heading) => getNextSection(document, heading)?.index ?? getBodyEnd(document);
44
- const getSectionLines = (document, headingText) => {
45
- const heading = getHeading(document, headingText);
46
- return heading ? document.lines.slice(heading.index + 1, getSectionEnd(document, heading)) : [];
47
- };
48
- const getSectionSpan = (document, headingText) => {
49
- const heading = getHeading(document, headingText);
50
- return heading ? getSectionEnd(document, heading) - heading.index : 0;
51
- };
52
- const getBudget = (value) => {
53
- const parsed = /^\d+$/.test(value) ? Number(value) : null;
54
- return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
54
+ const getGoalLines = (document) => {
55
+ const goal = getHeading(document, PLAN_HEADINGS[0]);
56
+ if (!goal) return [];
57
+ const start = goal.index + 1;
58
+ return document.lines.slice(start, getSectionEnd(document, goal)).map((text, offset) => {
59
+ const index = start + offset;
60
+ const reason = text.startsWith(ONE_PLAN_LABEL) && !document.fencedLines.has(index)
61
+ ? text.slice(ONE_PLAN_LABEL.length).replace(/\r$/u, '') : '';
62
+ return { text, line: getFindingLine(document, index), reason: reason.trim() ? reason : null };
63
+ });
55
64
  };
56
- const getFigure = (value) => Number(String(value).replace(/^~/, ''));
65
+ const getSectionSpan = (document, heading) => heading ? getSectionEnd(document, heading) - heading.index : 0;
57
66
  const getConcretePaths = (row, facts) => isSweep(row.path) ? facts.expansions?.[row.path] ?? [] : [row.path];
58
67
  const getPathFact = (facts, path) => facts.pathFacts?.[path] ?? null;
59
68
  const getAnchorPath = (anchor) => anchor.replace(/:[1-9]\d*$/, '');
60
69
  const hasPathDefect = (path) => !(!path.includes('\\') &&
61
70
  path.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..'));
62
- const hasRaiseBullet = (verificationBullets, path) => verificationBullets.some((bullet) =>
63
- bullet.includes('--write-baseline') && bullet.includes('--reason') && bullet.includes(path));
71
+ const isRetiredTotal = (raw) => raw.trim().startsWith(TOTAL_PREFIX);
64
72
 
65
73
  // fenceContinues (queue-audit's reader): only a NESTED fence continues an open bullet — a column-0
66
74
  // fence is a document block and closes it; `gaps` records where an absorbed run sat, so no reader
@@ -91,14 +99,13 @@ export const bulletBlocks = (lines, fencedLines, from, to, { fenceContinues = fa
91
99
  };
92
100
 
93
101
  const parseRow = (raw, line) => {
94
- const parts = raw.split(' | ').map((part) => part.trim());
95
- if (parts.length !== 6) return { raw, line, valid: false, id: parts[0] || null };
96
- const [id, verb, path, responsibility, budget, anchor] = parts;
97
- const budgetValid = budget === 'n/a' || budget === '—' || getBudget(budget) !== null;
98
- const deleteValid = verb === 'delete'
99
- ? budget === '—' && anchor === '—'
100
- : budget !== '—' && anchor !== '—' && anchor.length > 0;
101
- const valid = ROW_ID.test(id) && VERBS.has(verb) && path.length > 0 && responsibility.length > 0 && budgetValid && deleteValid;
102
+ const parts = raw.split(ROW_SEPARATOR).map((part) => part.trim());
103
+ if (parts.length !== ROW_FIELDS) {
104
+ return { raw, line, valid: false, id: parts[0] || null, retiredSizeField: parts.length === ROW_FIELDS + 1 };
105
+ }
106
+ const [id, verb, path, responsibility, anchor] = parts;
107
+ const anchorValid = verb === 'delete' ? anchor === '—' : anchor !== '—' && anchor.length > 0;
108
+ const valid = ROW_ID.test(id) && VERBS.has(verb) && path.length > 0 && responsibility.length > 0 && anchorValid;
102
109
  return {
103
110
  raw,
104
111
  line,
@@ -107,8 +114,6 @@ const parseRow = (raw, line) => {
107
114
  verb,
108
115
  path,
109
116
  responsibility,
110
- budget,
111
- budgetLines: getBudget(budget),
112
117
  anchor,
113
118
  anchorPath: anchor === '—' ? null : getAnchorPath(anchor),
114
119
  };
@@ -118,33 +123,23 @@ export const parseLedger = (text, suppliedDocument = null) => {
118
123
  const document = suppliedDocument ?? tokenizeMarkdown(String(text ?? ''), 'the plan');
119
124
  const start = getHeading(document, PLAN_HEADINGS[1]);
120
125
  const end = getHeading(document, PLAN_HEADINGS[2]);
121
- if (!start || !end || end.index <= start.index) return { rows: [], total: null, entries: [], document };
126
+ if (!start || !end || end.index <= start.index) return { rows: [], entries: [], document };
122
127
  const entries = document.lines.slice(start.index + 1, end.index).map((raw, offset) => ({
123
- raw,
128
+ raw: raw.replace(/\r$/u, ''),
124
129
  index: start.index + 1 + offset,
125
130
  line: getFindingLine(document, start.index + 1 + offset),
126
131
  }));
127
- const rows = entries.filter((entry) => entry.raw.includes(' | ')).map((entry) => parseRow(entry.raw, entry.line));
128
- const totals = entries.filter((entry) => entry.raw.trim().startsWith('total:'));
129
- const totalMatch = totals.length === 1 ? TOTAL_LINE.exec(totals[0].raw.trim()) : null;
130
- const total = totalMatch ? {
131
- line: totals[0].line,
132
- beforeRaw: totalMatch[1],
133
- afterRaw: totalMatch[2],
134
- before: getFigure(totalMatch[1]),
135
- after: getFigure(totalMatch[2]),
136
- } : null;
137
- return { rows, total, totals, entries, document };
132
+ const rows = entries.filter(({ raw }) => raw.includes(ROW_SEPARATOR) && !isRetiredTotal(raw))
133
+ .map(({ raw, line }) => parseRow(raw, line));
134
+ return { rows, entries, document };
138
135
  };
139
136
 
140
- const getVerificationBullets = (document) => {
137
+ const hasVerificationBullet = (document) => {
141
138
  const heading = getHeading(document, PLAN_HEADINGS[2]);
142
- if (!heading) return [];
143
- return bulletBlocks(document.lines, document.fencedLines, heading.index + 1, getSectionEnd(document, heading))
144
- .map((block) => block.lines.join('\n').replace(/^\-\s+/, '').replace(/\s+/g, ' ').trim());
139
+ return heading && bulletBlocks(document.lines, document.fencedLines, heading.index + 1, getSectionEnd(document, heading)).length > 0;
145
140
  };
146
141
 
147
- const checkHeadings = (text, document) => {
142
+ const checkHeadings = (document) => {
148
143
  const findings = [];
149
144
  const first = document.headings[0];
150
145
  if (!first || first.level !== 1 || !first.text.startsWith(PLAN_TITLE_PREFIX) || first.text.slice(PLAN_TITLE_PREFIX.length).trim() === '') {
@@ -168,25 +163,54 @@ const checkHeadings = (text, document) => {
168
163
  findings.push(makeFinding(getFindingLine(document, heading.index), 'headings', `${heading.text} is not an admitted extension phase between Verification and Cleanup`));
169
164
  }
170
165
  }
171
- if (getLineCount(text) > MAX_PLAN_LINES) findings.push(makeFinding(1, 'line-cap', `the plan has ${getLineCount(text)} lines; the cap is ${MAX_PLAN_LINES}`));
172
- for (const [heading, cap] of Object.entries(SECTION_CAPS)) {
166
+ return findings;
167
+ };
168
+
169
+ const getCountsPastSignals = (text, document, { approved, amendmentLines }, soleReason) => {
170
+ const lines = getLineCount(text) - amendmentLines.length - Number(Boolean(soleReason));
171
+ const counts = [{ name: 'lines', value: lines, signal: MAX_PLAN_LINES, line: 1, code: 'line-cap', subject: `the plan has ${lines} lines` }];
172
+ for (const [literal, signal] of SECTION_CAPS) {
173
+ const heading = getHeading(document, literal);
174
+ if (!heading) continue;
173
175
  const span = getSectionSpan(document, heading);
174
- if (span > cap) findings.push(makeFinding(getFindingLine(document, getHeading(document, heading).index), 'section-cap', `${heading} spans ${span} lines; the cap is ${cap}`));
176
+ const uncounted = literal === PLAN_HEADINGS[1]
177
+ ? amendmentLines.filter((line) => line < getFindingLine(document, heading.index + span)).length
178
+ : Number(literal === PLAN_HEADINGS[0] && Boolean(soleReason));
179
+ const value = span - uncounted;
180
+ counts.push({ name: literal, value, signal, line: getFindingLine(document, heading.index),
181
+ code: 'section-cap', subject: `${literal} spans ${value} lines` });
175
182
  }
176
- const cleanupNext = getSectionSpan(document, PLAN_HEADINGS[3]) + getSectionSpan(document, PLAN_HEADINGS[4]);
177
- if (cleanupNext > CLEANUP_NEXT_CAP) findings.push(makeFinding(1, 'section-cap', `Cleanup and Next steps span ${cleanupNext} lines; their shared cap is ${CLEANUP_NEXT_CAP}`));
178
- return findings;
183
+ const cleanupNext = getSectionSpan(document, getHeading(document, PLAN_HEADINGS[3])) + getSectionSpan(document, getHeading(document, PLAN_HEADINGS[4]));
184
+ counts.push({ name: CLEANUP_NEXT, value: cleanupNext, signal: CLEANUP_NEXT_CAP, line: 1,
185
+ code: 'section-cap', subject: `${CLEANUP_NEXT} span ${cleanupNext} lines` });
186
+ const excessRow = approved[MAX_LEDGER_ROWS];
187
+ if (excessRow) counts.push({ name: 'rows', value: approved.length, signal: MAX_LEDGER_ROWS, line: excessRow.line,
188
+ rowId: excessRow.id, code: 'row-cap', subject: `the ledger has ${approved.length} rows` });
189
+ return counts.filter(({ value, signal }) => value > signal);
179
190
  };
180
191
 
181
- const isPinRow = (row, path) => row.verb === 'modify' && row.path === path && posix.basename(row.path) === PIN_FILE;
182
- const checkPinBindings = (rows, owners, facts) => {
192
+ const makeCountFinding = ({ line, code, subject, signal, rowId }) =>
193
+ makeFinding(line, code, `${subject}, past its signal of ${signal} — ${PLAN_QUESTION}`, rowId);
194
+
195
+ const checkPlanCounts = (text, document, relation, reasons, authoring) => {
196
+ const [first, second] = reasons;
197
+ const soleReason = second ? null : first;
198
+ const counts = getCountsPastSignals(text, document, relation, soleReason);
199
+ if (soleReason && counts.length > 0) return { findings: [], notes: [{ counts, reason: soleReason.reason }] };
200
+ const findings = counts.map(makeCountFinding);
201
+ if (second) findings.push(makeFinding(second.line, 'one-plan-twice', ONE_PLAN_TWICE));
202
+ if (soleReason && authoring) findings.push(makeFinding(soleReason.line, 'one-plan-unneeded', ONE_PLAN_UNNEEDED));
203
+ return { findings, notes: [] };
204
+ };
205
+
206
+ const checkPinBindings = (rows, owners, facts, isApprovedPin) => {
183
207
  if (!Object.hasOwn(facts, 'pathFacts')) return [];
184
208
  return [...owners].flatMap(([path, group]) => {
185
- const pins = group.filter((row) => isPinRow(row, path));
209
+ const pins = group.filter((row) => isApprovedPin(row, path));
186
210
  if (pins.length < 2) return [];
187
211
  const taken = new Set();
188
212
  return pins.flatMap((pin) => {
189
- const above = rows.slice(0, rows.indexOf(pin)).findLast((row) => row.valid && PIN_VERBS.has(row.verb) && !taken.has(row) &&
213
+ const above = rows.slice(0, rows.indexOf(pin)).findLast((row) => PIN_VERBS.has(row.verb) && !taken.has(row) &&
190
214
  getPathFact(facts, row.path)?.shipped === true && getPathFact(facts, row.path)?.pinTest === path);
191
215
  if (above) { taken.add(above); return []; }
192
216
  return [makeFinding(pin.line, 'pin-unbound', `${pin.id} is a repeated pin row with no untaken shipped create or delete above it`, pin.id)];
@@ -194,54 +218,50 @@ const checkPinBindings = (rows, owners, facts) => {
194
218
  });
195
219
  };
196
220
 
197
- const checkLedgerStructure = (parsed, facts) => {
198
- const findings = [];
221
+ const checkLedgerStructure = (parsed, facts, relation, goalLines) => {
222
+ const validRows = parsed.rows.filter((row) => row.valid);
223
+ const findings = [...relation.findings, ...checkRobustTags({ rows: validRows, facts, makeFinding })];
199
224
  const nonBlank = parsed.entries.filter((entry) => entry.raw.trim() !== '');
200
- const rowLines = new Set(parsed.rows.map((row) => row.line));
201
- const totalLines = new Set((parsed.totals ?? []).map((total) => total.line));
225
+ const rowLines = new Set(parsed.rows.map(({ line }) => line));
202
226
  for (const entry of nonBlank) {
203
- if (!rowLines.has(entry.line) && !totalLines.has(entry.line)) findings.push(makeFinding(entry.line, 'ledger-line', 'a ledger line must be a six-field row or the total line'));
204
- }
205
- for (const row of parsed.rows) {
206
- if (!row.valid) findings.push(makeFinding(row.line, 'row-grammar', 'the row must carry six valid fields and delete rows alone use — for budget and anchor', row.id));
227
+ if (isRetiredTotal(entry.raw)) findings.push(makeFinding(entry.line, RETIRED_FORM_CODES.totalLine,'the total line is retired: drop it'));
228
+ else if (entry.raw !== AMENDMENT_LINE && !rowLines.has(entry.line)) findings.push(makeFinding(entry.line, 'ledger-line', 'a ledger line must be a five-field row or the amendment line'));
207
229
  }
208
- if (parsed.rows.length > MAX_LEDGER_ROWS) findings.push(makeFinding(parsed.rows[MAX_LEDGER_ROWS].line, 'row-cap', `the ledger has ${parsed.rows.length} rows; the cap is ${MAX_LEDGER_ROWS}`));
209
230
  const ids = new Map();
210
- for (const row of parsed.rows.filter((item) => item.id)) {
231
+ for (const row of parsed.rows) {
232
+ if (row.retiredSizeField) findings.push(makeFinding(row.line, RETIRED_FORM_CODES.sizeField,'the size field is retired: drop the fifth field, or remove a ` | ` inside the responsibility', row.id));
233
+ else if (!row.valid) findings.push(makeFinding(row.line, 'row-grammar', 'the row must carry five valid fields and delete rows alone use — for the anchor', row.id));
234
+ if (!row.id) continue;
211
235
  const prior = ids.get(row.id);
212
236
  if (prior) findings.push(makeFinding(row.line, 'duplicate-id', `${row.id} duplicates the row on line ${prior}`, row.id));
213
237
  else ids.set(row.id, row.line);
214
238
  }
215
- for (const row of parsed.rows.filter((item) => item.valid)) {
216
- const countedBytes = Buffer.byteLength([row.id, row.verb, row.responsibility, row.budget].join(' | '), 'utf8');
239
+ for (const row of validRows) {
240
+ const countedBytes = Buffer.byteLength([row.id, row.verb, row.responsibility].join(ROW_SEPARATOR), 'utf8');
217
241
  if (countedBytes > MAX_ROW_BYTES) findings.push(makeFinding(row.line, 'row-bytes', `${row.id} has ${countedBytes} counted bytes; the cap is ${MAX_ROW_BYTES}`, row.id));
218
242
  const contained = !hasPathDefect(row.path) && getPathFact(facts, row.path)?.contained !== false;
219
243
  if (!contained) findings.push(makeFinding(row.line, 'containment', `${row.id} path must be a contained repo-relative POSIX path`, row.id));
220
244
  const anchorContained = row.anchorPath === null || (!hasPathDefect(row.anchorPath) && getPathFact(facts, row.anchorPath)?.contained !== false);
221
245
  if (!anchorContained) findings.push(makeFinding(row.line, 'containment', `${row.id} anchor must be a contained repo-relative POSIX path`, row.id));
222
- if (isSweep(row.path) && (row.verb !== 'modify' || !/\([1-9]\d* files\)/.test(row.responsibility))) {
246
+ if (isSweep(row.path) && (row.verb !== SWEEP.verb || !SWEEP.count.test(row.responsibility))) {
223
247
  findings.push(makeFinding(row.line, 'sweep', `${row.id} sweep must use modify and assert its count as (N files)`, row.id));
224
248
  }
225
249
  }
226
250
  const owners = new Map();
227
- for (const row of parsed.rows.filter((item) => item.valid)) {
251
+ const isApprovedPin = (row, path) => relation.approved.includes(row) && row.verb === 'modify' && row.path === path && posix.basename(path) === PIN_FILE;
252
+ for (const row of validRows) {
228
253
  for (const path of getConcretePaths(row, facts)) {
229
254
  const prior = owners.get(path) ?? [];
230
- const conflicting = prior.find((owner) => !isPinRow(owner, path) || !isPinRow(row, path));
255
+ const conflicting = prior.find((owner) => !isApprovedPin(owner, path) || !isApprovedPin(row, path));
231
256
  if (conflicting) {
232
257
  findings.push(makeFinding(row.line, 'duplicate-path', `${path} is owned by both ${conflicting.id} and ${row.id}`, row.id));
233
258
  }
234
259
  owners.set(path, [...prior, row]);
235
260
  }
236
261
  }
237
- findings.push(...checkPinBindings(parsed.rows, owners, facts));
238
- const last = nonBlank.at(-1);
239
- if (!parsed.total || (parsed.totals ?? []).length !== 1 || last?.line !== parsed.total?.line) {
240
- findings.push(makeFinding(last?.line ?? 1, 'total', 'the exact total line must be the last non-blank ledger line'));
241
- }
242
- const bullets = getVerificationBullets(parsed.document);
243
- if (bullets.length === 0) findings.push(makeFinding(getHeading(parsed.document, PLAN_HEADINGS[2]) ? getFindingLine(parsed.document, getHeading(parsed.document, PLAN_HEADINGS[2]).index) : 1, 'acceptance', 'Verification must carry at least one top-level - bullet'));
244
- if (!getSectionLines(parsed.document, PLAN_HEADINGS[0]).some((line) => SPEC_LINE.test(line))) {
262
+ findings.push(...checkPinBindings(validRows, owners, facts, isApprovedPin));
263
+ if (!hasVerificationBullet(parsed.document)) findings.push(makeFinding(getHeading(parsed.document, PLAN_HEADINGS[2]) ? getFindingLine(parsed.document, getHeading(parsed.document, PLAN_HEADINGS[2]).index) : 1, 'acceptance', 'Verification must carry at least one top-level - bullet'));
264
+ if (!goalLines.some(({ text, reason }) => reason === null && (text.includes(SPEC_SCHEMA.storePrefix) || SPEC_LINE.test(text)))) {
245
265
  findings.push(makeFinding(getHeading(parsed.document, PLAN_HEADINGS[0]) ? getFindingLine(parsed.document, getHeading(parsed.document, PLAN_HEADINGS[0]).index) : 1, 'governing-spec', 'Goal and boundary must name a governing spec path or the adopted state'));
246
266
  }
247
267
  return findings;
@@ -253,69 +273,66 @@ export const resolveAnchorCandidates = (repoFiles, suffix, precedingPaths) => {
253
273
  return above.length > 0 ? above : unique(repoFiles.filter((path) => endsWithPath(path, suffix)));
254
274
  };
255
275
 
256
- const getAnchorCandidates = (row, preceding, facts) => {
257
- const suffix = row.anchorPath;
258
- if (!suffix || hasPathDefect(suffix)) return [];
259
- const precedingPaths = preceding.filter((item) => item.valid).flatMap((item) => getConcretePaths(item, facts));
260
- return facts.candidates(suffix, precedingPaths);
276
+ const getContractRefusal = (row, path, observed, rows, facts) => {
277
+ if (row.verb !== 'create' || path !== row.path || observed !== 'regular' || !path.startsWith(SPEC_SCHEMA.storePrefix) || !path.endsWith('.md') || hasPathDefect(path)) return '';
278
+ const contract = getPathFact(facts, path)?.contract;
279
+ if (!contract || contract.refused) return ': the spec reader refuses it';
280
+ if (facts.otherPlanCreates?.includes(path)) return ': another plan in flight creates it';
281
+ if (contract.kind === 'spec') return contract.status === 'draft' ? null : `: a ${contract.status} spec`;
282
+ const creates = (target) => rows.some((candidate) => candidate.valid && candidate.verb === 'create' && candidate.path === target);
283
+ if (contract.kind === 'index') return !contract.children?.length ? ': an index that lists no child' : contract.children.every(creates) ? null : ': an index listing a child the plan does not create';
284
+ const rootPath = posix.join(posix.dirname(path), SPEC_SCHEMA.navigatorFile);
285
+ const root = getPathFact(facts, rootPath)?.contract;
286
+ const listed = creates(rootPath) && root?.kind === 'spec' && root.status === 'draft' && !root.refused && root.parts?.includes(path) === true;
287
+ return contract.kind !== 'part' ? `: a ${contract.kind} document` : listed ? null : ': a part its draft root does not list, or of another root';
261
288
  };
262
289
 
263
- const getCurrentLines = (rows, facts, verbs) => unique(rows
264
- .filter((row) => row.valid && verbs.has(row.verb) && row.budget !== 'n/a')
265
- .flatMap((row) => getConcretePaths(row, facts)))
266
- .reduce((sum, path) => sum + (getPathFact(facts, path)?.lines ?? 0), 0);
290
+ const checkSweepCount = (row, count, { authoring = false } = {}) => {
291
+ if (!isSweep(row.path)) return [];
292
+ const expected = Number(SWEEP.count.exec(row.responsibility)?.[1]);
293
+ if (count === expected || (authoring && (!count || row.verb !== SWEEP.verb || Number.isNaN(expected)))) return [];
294
+ return [makeFinding(row.line, SWEEP.countCode, `${row.id} expected ${expected} files and resolves to ${count}`, row.id)];
295
+ };
267
296
 
268
- const checkAuthoring = (parsed, facts) => {
269
- const findings = [];
270
- const bullets = getVerificationBullets(parsed.document);
271
- const robustClasses = new Set(facts.robustClasses ?? []);
272
- for (const [index, row] of parsed.rows.entries()) {
273
- if (!row.valid) continue;
274
- const robust = parseRobustTag(row.responsibility);
275
- const unknownRobustClass = robust.classes?.find((classId) => !robustClasses.has(classId));
276
- if (robust.refusal || unknownRobustClass !== undefined) {
277
- const reason = robust.refusal ? `tag grammar refused ${robust.refusal}` : `class ${unknownRobustClass} is not in the shipped list`;
278
- findings.push(makeFinding(row.line, 'robust-class', `${row.id} robust tag: ${reason}`, row.id));
297
+ const checkRowAuthoring = (row, paths, rows, facts, findings) => {
298
+ for (const path of paths) {
299
+ const pathFact = getPathFact(facts, path);
300
+ if (pathFact?.inScope && row.verb === 'create' && !TEST_PATH.test(path)) {
301
+ const hasEarlierTest = rows.some((prior) => prior.line < row.line && prior.valid && prior.verb !== 'delete' && TEST_PATH.test(prior.path));
302
+ if (!hasEarlierTest) findings.push(makeFinding(row.line, 'red-first', `${row.id} needs a create or modify test row above it`, row.id));
279
303
  }
304
+ }
305
+ if (row.verb !== 'create') return;
306
+ const pathFact = getPathFact(facts, row.path);
307
+ if (pathFact?.shipped === true && pathFact.pinTest && !rows.some((candidate) => candidate.valid && candidate.verb === 'modify' &&
308
+ candidate.path === pathFact.pinTest)) {
309
+ findings.push(makeFinding(row.line, 'package-pin', `${row.id} ships but no modify row owns ${pathFact.pinTest}`, row.id));
310
+ }
311
+ };
312
+
313
+ const checkAuthoring = (parsed, facts, relation, { entriesOnly = false } = {}) => {
314
+ const findings = entriesOnly ? [] : parsed.entries.filter(({ raw }) => raw === AMENDMENT_LINE)
315
+ .map(({ line }) => makeFinding(line, AMENDMENT_CHECK.code, AMENDMENT_CHECK.message));
316
+ for (const row of (entriesOnly ? relation.entries : parsed.rows).filter((item) => item.valid)) {
280
317
  const paths = getConcretePaths(row, facts);
281
- const expectedKind = row.verb === 'create' ? 'absent' : 'regular';
282
- if (paths.length === 0 && isSweep(row.path)) findings.push(makeFinding(row.line, 'kind', `${row.id} sweep resolves to no regular path`, row.id));
283
- for (const path of paths) {
284
- const observed = getPathFact(facts, path)?.kind ?? 'unknown';
285
- if (observed !== expectedKind) findings.push(makeFinding(row.line, 'kind', `${row.id} expects ${expectedKind}, observed ${observed} at ${path}`, row.id));
286
- }
287
- const anchorCandidates = row.anchorPath ? getAnchorCandidates(row, parsed.rows.slice(0, index), facts) : null;
288
- if (anchorCandidates && anchorCandidates.length !== 1) {
289
- const count = anchorCandidates.length;
290
- findings.push(makeFinding(row.line, 'anchor', `${row.id} anchor resolves to ${count} candidates; make it unique`, row.id));
291
- }
292
- if (row.verb !== 'delete' && row.budgetLines !== null && !facts.capDeclared) {
293
- findings.push(makeFinding(row.line, 'cap-declaration', `${row.id} uses an integer budget but no source-size cap is declared; use n/a`, row.id));
294
- }
295
- for (const path of paths) {
296
- const pathFact = getPathFact(facts, path);
297
- if (!pathFact?.inScope) continue;
298
- if (row.budget === 'n/a') findings.push(makeFinding(row.line, 'source-budget', `${row.id} is in source scope and cannot use n/a`, row.id));
299
- if (row.verb === 'create' && !TEST_PATH.test(path)) {
300
- const hasEarlierTest = parsed.rows.slice(0, index).some((prior) => prior.valid && ['create', 'modify'].includes(prior.verb) && TEST_PATH.test(prior.path));
301
- if (!hasEarlierTest) findings.push(makeFinding(row.line, 'red-first', `${row.id} needs a create or modify test row above it`, row.id));
302
- }
303
- const ceiling = row.verb === 'modify' && pathFact.recordedLines != null ? pathFact.recordedLines : facts.cap;
304
- if (row.budgetLines !== null && ceiling != null && row.budgetLines > ceiling && !hasRaiseBullet(bullets, row.path)) {
305
- findings.push(makeFinding(row.line, 'budget-cap', `${row.id} budget ${row.budgetLines} exceeds ${ceiling}; name a reasoned baseline raise for ${row.path}`, row.id));
318
+ if (!entriesOnly) {
319
+ const expectedKind = row.verb === 'create' ? 'absent' : 'regular';
320
+ if (paths.length === 0 && isSweep(row.path)) findings.push(makeFinding(row.line, 'kind', `${row.id} sweep resolves to no regular path`, row.id));
321
+ findings.push(...checkSweepCount(row, paths.length, { authoring: true }));
322
+ for (const path of paths) {
323
+ const observed = getPathFact(facts, path)?.kind ?? 'unknown';
324
+ const cause = observed === expectedKind ? null : getContractRefusal(row, path, observed, parsed.rows, facts);
325
+ if (cause !== null) findings.push(makeFinding(row.line, 'kind', `${row.id} expects ${expectedKind}, observed ${observed} at ${path}${cause}`, row.id));
306
326
  }
307
- }
308
- if (row.verb === 'create') {
309
- const pathFact = getPathFact(facts, row.path);
310
- if (pathFact?.shipped === true && pathFact.pinTest && !parsed.rows.some((candidate) => candidate.valid && candidate.verb === 'modify' && candidate.path === pathFact.pinTest)) {
311
- findings.push(makeFinding(row.line, 'package-pin', `${row.id} ships but no modify row owns ${pathFact.pinTest}`, row.id));
327
+ if (row.anchorPath) {
328
+ const candidates = hasPathDefect(row.anchorPath) ? [] : facts.candidates(row.anchorPath,
329
+ parsed.rows.slice(0, parsed.rows.indexOf(row)).filter((prior) => prior.valid).flatMap((prior) => getConcretePaths(prior, facts)));
330
+ if (candidates && candidates.length !== 1) findings.push(makeFinding(row.line, 'anchor', `${row.id} anchor resolves to ${candidates.length} candidates; make it unique`, row.id));
312
331
  }
313
332
  }
333
+ checkRowAuthoring(row, paths, parsed.rows, facts, findings);
314
334
  }
315
- if (parsed.total) {
316
- const current = getCurrentLines(parsed.rows, facts, new Set(['modify', 'delete']));
317
- if (parsed.total.before !== current) findings.push(makeFinding(parsed.total.line, 'before-total', `before is ${parsed.total.before}; current counted paths sum to ${current}`));
318
- }
335
+ if (entriesOnly) return { findings, skips: [] };
319
336
  return { findings, skips: parsed.rows.filter((row) => row.verb === 'create').flatMap((row) =>
320
337
  getPathFact(facts, row.path)?.pinSkip ? [`${row.id}: package pin skipped — ${getPathFact(facts, row.path).pinSkip}`] : []) };
321
338
  };
@@ -324,23 +341,13 @@ const checkPostState = (parsed, facts) => {
324
341
  const findings = [];
325
342
  for (const row of parsed.rows.filter((item) => item.valid)) {
326
343
  const paths = getConcretePaths(row, facts);
327
- if (isSweep(row.path)) {
328
- const expected = Number(/\(([1-9]\d*) files\)/.exec(row.responsibility)?.[1]);
329
- if (paths.length === 0 || paths.length !== expected) findings.push(makeFinding(row.line, 'sweep-count', `${row.id} expected ${expected} files and resolves to ${paths.length}`, row.id));
330
- }
344
+ findings.push(...checkSweepCount(row, paths.length));
331
345
  for (const path of paths) {
332
346
  const fact = getPathFact(facts, path);
333
347
  const expectedKind = row.verb === 'delete' ? 'absent' : 'regular';
334
348
  if (fact?.kind !== expectedKind) findings.push(makeFinding(row.line, 'post-kind', `${row.id} expects ${expectedKind}, observed ${fact?.kind ?? 'unknown'} at ${path}`, row.id));
335
- if (row.verb !== 'delete' && row.budgetLines !== null && fact?.kind === 'regular' && fact.lines > row.budgetLines) {
336
- findings.push(makeFinding(row.line, 'post-budget', `${path} has ${fact.lines} lines, above ${row.id} budget ${row.budgetLines}`, row.id));
337
- }
338
349
  }
339
350
  }
340
- if (parsed.total) {
341
- const current = getCurrentLines(parsed.rows, facts, new Set(['create', 'modify']));
342
- if (parsed.total.after < current) findings.push(makeFinding(parsed.total.line, 'after-total', `after is ${parsed.total.after}; counted paths sum to ${current}`));
343
- }
344
351
  return { findings, skips: [] };
345
352
  };
346
353
 
@@ -359,26 +366,32 @@ const judge = (text, facts, stateRules) => {
359
366
  return { findings: [makeFinding(line, 'block-model', parsedResult.error.message)], skips: [], parsed: null };
360
367
  }
361
368
  const parsed = parsedResult.parsed;
362
- const goal = getHeading(parsed.document, PLAN_HEADINGS[0]);
363
- const goalLines = goal ? getSectionLines(parsed.document, PLAN_HEADINGS[0])
364
- .map((text, offset) => ({ text, line: getFindingLine(parsed.document, goal.index + 1 + offset) })) : [];
365
- const structural = [...checkHeadings(String(text ?? ''), parsed.document), ...checkLedgerStructure(parsed, facts),
369
+ const relation = relateAmendments({ parsed, makeFinding, isSweep });
370
+ const goalLines = getGoalLines(parsed.document);
371
+ const reasons = goalLines.filter(({ reason }) => reason !== null);
372
+ const counts = checkPlanCounts(String(text ?? ''), parsed.document, relation, reasons, stateRules === checkAuthoring);
373
+ const structural = [...checkHeadings(parsed.document), ...counts.findings, ...checkLedgerStructure(parsed, facts, relation, goalLines),
366
374
  ...checkStoryOwnership({ rows: parsed.rows, goalLines, facts, getConcretePaths }).findings];
367
- const state = stateRules ? stateRules(parsed, facts) : { findings: [], skips: [] };
368
- const findings = [...structural, ...state.findings].map((finding, index) => ({ ...finding, order: index }))
369
- .sort((left, right) => left.line - right.line || left.order - right.order)
370
- .map(({ order, ...finding }) => finding);
371
- return { findings, skips: state.skips, parsed };
375
+ const state = stateRules ? stateRules(parsed, facts, relation) : { findings: [], skips: [] };
376
+ const findings = [...structural, ...state.findings].sort((left, right) => left.line - right.line);
377
+ return { findings, skips: state.skips, parsed, ...(counts.notes.length ? { notes: counts.notes } : {}) };
372
378
  };
373
379
 
374
380
  export const checkPlan = (text, facts) => judge(text, facts, checkAuthoring);
375
381
  export const verifyPlan = (text, facts) => judge(text, facts, checkPostState);
376
382
  export const checkPlanStructure = (text, facts) => judge(text, facts, null);
383
+ export const checkPlanEntries = (text, facts) => judge(text, facts, (parsed, entryFacts, relation) => checkAuthoring(parsed, entryFacts, relation, { entriesOnly: true }));
384
+
385
+ const formatOnePlanNote = ({ counts, reason }) => {
386
+ const lifted = counts.map(({ name, value, signal }) => `${name} ${value} of ${signal}`).join(', ');
387
+ return `plan-shape: NOTE — one plan past its signals (${lifted}): ${escapeForLine(reason)}`;
388
+ };
377
389
 
378
390
  export const formatFindings = (result, label = 'plan') => {
379
391
  const lines = result.findings.length === 0
380
392
  ? [`plan-shape: ACCEPT — ${label}`]
381
393
  : [`plan-shape: REFUSE — ${label}`, ...result.findings.map((finding) =>
382
394
  `${label}:${finding.line}: ${finding.rowId ? `${finding.rowId}: ` : ''}${finding.code}: ${finding.message}`)];
383
- return [...lines, ...result.skips.map((skip) => `plan-shape: SKIP — ${skip}`)].join('\n');
395
+ return [...lines, ...(result.notes ?? []).map(formatOnePlanNote),
396
+ ...result.skips.map((skip) => `plan-shape: SKIP — ${skip}`)].join('\n');
384
397
  };
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { isDirectRun } from '../direct-run.mjs';
4
+ import { judgePlan, readPlanDocument } from '../plan-shape-facts.mjs';
5
+ import { checkPlanEntries, formatFindings, isSweep, makeFinding, parseLedger } from '../plan-shape.mjs';
6
+ import { escapeForDisplay } from '../repo-lex.mjs';
7
+ import { relateAmendments } from './index.mjs';
8
+
9
+ const USAGE = 'Usage: node plan-structure/cli.mjs <plan>';
10
+ const STRUCTURE_PREFIX = 'plan-structure: ';
11
+ const AMENDMENT_PREFIX = `${STRUCTURE_PREFIX}amendment — `;
12
+ const FIELD_SEPARATOR = ' | ';
13
+ const EMPTY_FIELD = '';
14
+ const LINE_ENDING = '\n';
15
+ const OPERAND_COUNT = 1;
16
+ const EXIT_ACCEPT = 0;
17
+ const EXIT_REFUSE = 1;
18
+ const EXIT_USAGE = 2;
19
+
20
+ const writeLine = (write, line) => write(`${line}${LINE_ENDING}`);
21
+
22
+ const judgeOperand = (cwd, operand) => {
23
+ try {
24
+ const document = readPlanDocument(cwd, operand);
25
+ return judgePlan(cwd, document, { rules: checkPlanEntries });
26
+ } catch (error) {
27
+ return { error };
28
+ }
29
+ };
30
+
31
+ const parseLedgerForDisplay = (text) => {
32
+ try {
33
+ return parseLedger(text);
34
+ } catch {
35
+ return null;
36
+ }
37
+ };
38
+
39
+ const formatVerdict = (result, operand) => formatFindings({
40
+ findings: result.findings.map(({ line, code, message, rowId }) => ({
41
+ line: escapeForDisplay(line),
42
+ code: escapeForDisplay(code),
43
+ message: escapeForDisplay(message),
44
+ rowId: rowId ? escapeForDisplay(rowId) : rowId,
45
+ })),
46
+ skips: result.skips.map(escapeForDisplay),
47
+ }, escapeForDisplay(operand));
48
+
49
+ const formatAmendment = ({ id, verb, path }) => {
50
+ const fields = [id, verb, path].map((field) => escapeForDisplay(field ?? EMPTY_FIELD));
51
+ return `${AMENDMENT_PREFIX}${fields.join(FIELD_SEPARATOR)}`;
52
+ };
53
+
54
+ export const main = (argv = process.argv.slice(2), io = {}) => {
55
+ const cwd = io.cwd ?? process.cwd();
56
+ const stdout = io.stdout ?? ((text) => process.stdout.write(text));
57
+ const stderr = io.stderr ?? ((text) => process.stderr.write(text));
58
+ if (argv.length !== OPERAND_COUNT) {
59
+ writeLine(stderr, USAGE);
60
+ return EXIT_USAGE;
61
+ }
62
+
63
+ const [operand] = argv;
64
+ const { accepted, error, result, text } = judgeOperand(cwd, operand);
65
+ if (error) {
66
+ writeLine(stderr, `${STRUCTURE_PREFIX}${escapeForDisplay(error.message)}`);
67
+ return EXIT_USAGE;
68
+ }
69
+
70
+ writeLine(stdout, formatVerdict(result, operand));
71
+ const parsed = parseLedgerForDisplay(text);
72
+ if (parsed) {
73
+ const { entries } = relateAmendments({ parsed, makeFinding, isSweep });
74
+ for (const entry of entries) writeLine(stdout, formatAmendment(entry));
75
+ }
76
+ return accepted ? EXIT_ACCEPT : EXIT_REFUSE;
77
+ };
78
+
79
+ if (isDirectRun(import.meta.url)) process.exitCode = main();