architecture-harness 0.16.0 → 0.18.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 (124) hide show
  1. package/package.json +8 -3
  2. package/src/cli/bash-command-guard.mjs +25 -10
  3. package/src/cli/bash-command-guard.test.mjs +30 -0
  4. package/src/cli/bash-edit-guard.mjs +28 -7
  5. package/src/cli/bash-edit-guard.test.mjs +24 -0
  6. package/src/cli/budget-counter.mjs +25 -4
  7. package/src/cli/budget-guard.mjs +73 -4
  8. package/src/cli/budget-guard.test.mjs +111 -0
  9. package/src/cli/budget.mjs +3 -2
  10. package/src/cli/check-registries.test.mjs +181 -0
  11. package/src/cli/check.mjs +130 -9
  12. package/src/cli/cli.test.mjs +215 -2
  13. package/src/cli/context-signal.mjs +92 -0
  14. package/src/cli/context-signal.test.mjs +99 -0
  15. package/src/cli/contract-history.mjs +46 -0
  16. package/src/cli/contract-history.test.mjs +118 -0
  17. package/src/cli/controller-guard.mjs +73 -0
  18. package/src/cli/controller-guard.test.mjs +119 -0
  19. package/src/cli/dispatch-guard.mjs +14 -4
  20. package/src/cli/dispatch-guard.test.mjs +5 -6
  21. package/src/cli/dispatch-reminder.mjs +19 -11
  22. package/src/cli/dispatch-reminder.test.mjs +32 -0
  23. package/src/cli/dispatch.mjs +23 -2
  24. package/src/cli/dispatch.test.mjs +39 -1
  25. package/src/cli/doctor.mjs +2 -1
  26. package/src/cli/explore-guard.mjs +2 -2
  27. package/src/cli/explore-hint.mjs +67 -7
  28. package/src/cli/explore-hint.test.mjs +104 -4
  29. package/src/cli/gh-merge-command.mjs +228 -0
  30. package/src/cli/gh-merge-command.test.mjs +273 -0
  31. package/src/cli/gh-run.mjs +30 -0
  32. package/src/cli/gh-run.test.mjs +22 -0
  33. package/src/cli/git-hooks.test.mjs +28 -0
  34. package/src/cli/git-read.mjs +42 -0
  35. package/src/cli/git-read.test.mjs +94 -0
  36. package/src/cli/handoff-note.mjs +69 -0
  37. package/src/cli/handoff-note.test.mjs +71 -0
  38. package/src/cli/init.mjs +7 -3
  39. package/src/cli/issue-gate.mjs +169 -0
  40. package/src/cli/issue-gate.test.mjs +234 -0
  41. package/src/cli/ledger.mjs +138 -0
  42. package/src/cli/ledger.test.mjs +127 -0
  43. package/src/cli/merge-guard.mjs +193 -0
  44. package/src/cli/merge-guard.test.mjs +328 -0
  45. package/src/cli/plan-check.mjs +151 -0
  46. package/src/cli/plan-check.test.mjs +143 -0
  47. package/src/cli/plan-stop.mjs +101 -0
  48. package/src/cli/plan-stop.test.mjs +136 -0
  49. package/src/cli/plugin-agents.test.mjs +105 -8
  50. package/src/cli/pr-check.mjs +17 -5
  51. package/src/cli/pr-check.test.mjs +85 -4
  52. package/src/cli/prose.mjs +192 -0
  53. package/src/cli/prose.test.mjs +248 -0
  54. package/src/cli/qc.mjs +22 -0
  55. package/src/cli/registry-history.mjs +1 -1
  56. package/src/cli/report-stash.mjs +69 -0
  57. package/src/cli/report-stash.test.mjs +71 -0
  58. package/src/cli/report-stop.mjs +266 -0
  59. package/src/cli/report-stop.test.mjs +471 -0
  60. package/src/cli/shell-command.mjs +81 -6
  61. package/src/cli/shell-command.test.mjs +101 -1
  62. package/src/cli/task-gate.mjs +179 -0
  63. package/src/cli/task-gate.test.mjs +507 -0
  64. package/src/cli/tokens.mjs +239 -0
  65. package/src/cli/tokens.test.mjs +286 -0
  66. package/src/cli/transcript-usage.mjs +135 -0
  67. package/src/cli/transcript-usage.test.mjs +129 -0
  68. package/src/cli/workflow-hooks.test.mjs +72 -0
  69. package/src/cli/workflow-place.mjs +143 -0
  70. package/src/cli/workflow-place.test.mjs +146 -0
  71. package/src/cli/workflow-settings.mjs +77 -0
  72. package/src/cli/workflow-settings.test.mjs +79 -0
  73. package/src/cli/worktree.mjs +1 -1
  74. package/src/cli/worktree.test.mjs +19 -2
  75. package/src/config.mjs +99 -4
  76. package/src/config.test.mjs +38 -3
  77. package/src/descriptions.mjs +5 -1
  78. package/src/eslint/index.mjs +2 -0
  79. package/src/eslint/jsx.mjs +57 -0
  80. package/src/eslint/preset.mjs +32 -6
  81. package/src/eslint/preset.test.mjs +60 -0
  82. package/src/eslint/rules/durable-idempotency-key.mjs +26 -0
  83. package/src/eslint/rules/ime-safe-key.mjs +1 -50
  84. package/src/eslint/rules/mutation-control-pending.mjs +128 -0
  85. package/src/eslint/rules/no-supersession-trail.mjs +8 -4
  86. package/src/eslint/rules/registry-literal.mjs +36 -2
  87. package/src/eslint/rules.test.mjs +153 -0
  88. package/src/gates/call-args.mjs +90 -0
  89. package/src/gates/call-args.test.mjs +21 -0
  90. package/src/gates/config-floor.mjs +41 -20
  91. package/src/gates/config-floor.test.mjs +71 -1
  92. package/src/gates/contract-idempotency.mjs +103 -0
  93. package/src/gates/contract-idempotency.test.mjs +276 -0
  94. package/src/gates/contract-operations.mjs +120 -0
  95. package/src/gates/contract-operations.test.mjs +275 -0
  96. package/src/gates/contract-routes.mjs +82 -0
  97. package/src/gates/contract-routes.test.mjs +210 -0
  98. package/src/gates/registry-literal.mjs +79 -15
  99. package/src/gates/registry-literal.test.mjs +89 -0
  100. package/src/gates/saga-key.mjs +253 -0
  101. package/src/gates/saga-key.test.mjs +322 -0
  102. package/src/gates/scrub.mjs +108 -0
  103. package/src/gates/scrub.test.mjs +29 -0
  104. package/src/gates/tenant-isolation-test.mjs +80 -0
  105. package/src/gates/tenant-isolation-test.test.mjs +129 -0
  106. package/src/gates/tenant-predicate.mjs +644 -91
  107. package/src/gates/tenant-predicate.test.mjs +662 -1
  108. package/src/prose-lines.mjs +49 -0
  109. package/src/prose-lines.test.mjs +63 -0
  110. package/src/registries.mjs +89 -0
  111. package/src/registries.test.mjs +44 -0
  112. package/src/vale-style.test.mjs +158 -0
  113. package/templates/docs/enforcement.md +26 -2
  114. package/templates/github/workflows/ci.yml +18 -1
  115. package/templates/quality-thresholds.json +1 -1
  116. package/templates/vale/.vale.ini +7 -0
  117. package/templates/vale/styles/Qc/AndOr.yml +7 -0
  118. package/templates/vale/styles/Qc/InOrderTo.yml +6 -0
  119. package/templates/vale/styles/Qc/Latin.yml +9 -0
  120. package/templates/vale/styles/Qc/PassiveVoice.yml +21 -0
  121. package/templates/vale/styles/Qc/Please.yml +6 -0
  122. package/templates/vale/styles/Qc/Progress.yml +9 -0
  123. package/templates/vale/styles/Qc/SentenceLength.yml +6 -0
  124. package/templates/vale/styles/Qc/Utilize.yml +10 -0
@@ -0,0 +1,151 @@
1
+ // The branch that checks a superpowers plan before anyone runs it. Each `### Task N:` names its files, has a
2
+ // test step and a commit step, and keeps any estimate within one implementer's tool-call budget.
3
+
4
+ import { readFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { reviewDefaults } from "../config.mjs";
7
+ import { reviewSettings } from "./workflow-settings.mjs";
8
+
9
+ const TASK_HEADING = /^###[ \t]+Task[ \t]+(\d+)[ \t]*:[ \t]*(.*)$/;
10
+ const SECTION_END = /^#{1,3}[ \t]/;
11
+ const FILE_LINE = /^[ \t]*[-*][ \t]+(?:Create|Modify|Test|Delete|Rename):[ \t]*\S/i;
12
+ const STEP_LINE = /^[ \t]*[-*][ \t]+\[[ xX]\][ \t]+\*\*(.+?)\*\*/;
13
+ const ESTIMATE_LINE = /^[ \t]*\*\*Estimate:\*\*[ \t]*(\d+)(?:[ \t]*(?:-|–|—|to)[ \t]*(\d+))?/i;
14
+ const FENCE = /^[ \t]*(`{3,}|~{3,})/;
15
+ const GIT_COMMIT = /\bgit[ \t]+commit\b/;
16
+ const TEST_WORD = /\btests?\b/i;
17
+ const COMMIT_WORD = /\bcommit\b/i;
18
+ const NO_TEST_LINE = /^[ \t]*(?:[-*][ \t]+)?Test:[ \t]*none(?![\w.])(.*)$/i;
19
+ const NO_TEST_DASH = /^[ \t]*(?:—|–|--?)[ \t]*/;
20
+ const NO_TEST_WORDS = 3;
21
+ const PATH_LINE = /^[ \t]*[-*][ \t]+(?:Create|Modify|Test|Delete|Rename)\b/i;
22
+ const DOC_FILE = /\.(?:md|mdx|txt|json|ya?ml)$|^(?:CHANGELOG|LICENSE)|^VERSION$/i;
23
+ const BARE_NAME = /^(?:Dockerfile|Makefile|Jenkinsfile|Procfile|Gemfile|Rakefile|Vagrantfile|Brewfile)$/i;
24
+ const NOT_A_PATH = /^(?:v?\d+(?:\.\d+)+|\d+(?:-\d+)?|e\.g|i\.e|etc|vs)$/i;
25
+ const NO_TEST_SPELLING = "`Test: none — <reason>`";
26
+
27
+ const tidy = (word) => word.replace(/^[(["']+/, "").replace(/[)\]"',;.]+$/, "").replace(/:\d+(?:-\d+)?$/, "");
28
+
29
+ /** Every path a Create, Modify, Test, Delete, or Rename line names that is not a document. Fails closed. */
30
+ function sourceFilesOf(line) {
31
+ const rest = line.replace(/^[^:]*:/, "");
32
+ const found = [/^\s*`([^`\s]+)`/.exec(rest)?.[1]];
33
+ for (const [, span] of rest.matchAll(/`([^`\s]+)`/g)) found.push(span);
34
+ for (const token of rest.replace(/`/g, " ").split(/\s+/)) found.push(token);
35
+ const named = (word) => /[/.]/.test(word) || BARE_NAME.test(word);
36
+ const paths = found.filter((word) => word).map(tidy).filter((word) => word !== "" && !NOT_A_PATH.test(word));
37
+ const first = found[0] ? tidy(found[0]) : null;
38
+ const isPath = (word) => word === first || named(word);
39
+ return [...new Set(paths.filter(isPath).filter((word) => !DOC_FILE.test(word.split(/[\\/]/).pop())))];
40
+ }
41
+
42
+ /** The tasks of a plan, with their file lines, step titles, commit evidence, and estimate. Fenced code is not structure. */
43
+ export function parsePlan(markdown) {
44
+ const tasks = [];
45
+ let task = null;
46
+ let fence = null;
47
+ markdown.split(/\r?\n/).forEach((line, index) => {
48
+ const marker = FENCE.exec(line)?.[1];
49
+ if (fence) {
50
+ if (marker && marker[0] === fence[0] && marker.length >= fence.length && line.trim() === marker) fence = null;
51
+ else if (task && GIT_COMMIT.test(line)) task.commitCommand = true;
52
+ return;
53
+ }
54
+ if (marker) {
55
+ fence = marker;
56
+ return;
57
+ }
58
+ const heading = TASK_HEADING.exec(line);
59
+ if (heading) {
60
+ task = {
61
+ number: Number(heading[1]),
62
+ title: heading[2].trim(),
63
+ line: index + 1,
64
+ files: 0,
65
+ steps: [],
66
+ commitCommand: false,
67
+ estimate: null,
68
+ sourceFiles: [],
69
+ noTest: null,
70
+ };
71
+ tasks.push(task);
72
+ return;
73
+ }
74
+ if (SECTION_END.test(line)) {
75
+ task = null;
76
+ return;
77
+ }
78
+ if (!task) return;
79
+ const noTest = NO_TEST_LINE.exec(line);
80
+ if (noTest) {
81
+ const reason = noTest[1].replace(NO_TEST_DASH, "").trim();
82
+ task.noTest = { reason, words: reason === "" ? 0 : reason.split(/\s+/).length };
83
+ return;
84
+ }
85
+ if (PATH_LINE.test(line)) task.sourceFiles.push(...sourceFilesOf(line));
86
+ if (FILE_LINE.test(line)) task.files += 1;
87
+ const step = STEP_LINE.exec(line)?.[1];
88
+ if (step) task.steps.push(step);
89
+ const estimate = ESTIMATE_LINE.exec(line);
90
+ if (estimate) task.estimate = Number(estimate[2] ?? estimate[1]);
91
+ });
92
+ return tasks;
93
+ }
94
+
95
+ /** @returns each way the plan breaks the format, one entry per task and problem. */
96
+ export function checkPlan(markdown, { maxTaskCalls = reviewDefaults.maxTaskCalls } = {}) {
97
+ const tasks = parsePlan(markdown);
98
+ if (tasks.length === 0) return [{ task: null, detail: "the plan has no `### Task N:` heading" }];
99
+ const problems = [];
100
+ for (const task of tasks) {
101
+ const add = (detail) => problems.push({ task: task.number, detail });
102
+ if (task.files === 0) add("names no file: list each as `- Create:`, `- Modify:` or `- Test:` with its path");
103
+ if (task.noTest) {
104
+ if (task.noTest.words < NO_TEST_WORDS) {
105
+ add(`carries \`Test: none\` without a reason of at least ${NO_TEST_WORDS} words: write ${NO_TEST_SPELLING}`);
106
+ }
107
+ else if (task.sourceFiles.length > 0) {
108
+ add(`carries \`Test: none\` but names source code (${task.sourceFiles.join(", ")}); ${NO_TEST_SPELLING} is only for a task with no code`);
109
+ }
110
+ } else if (!task.steps.some((step) => TEST_WORD.test(step))) {
111
+ add(`has no test step: a step whose title names the test it writes or runs, or for a task with no code the line ${NO_TEST_SPELLING}`);
112
+ }
113
+ if (!task.commitCommand && !task.steps.some((step) => COMMIT_WORD.test(step))) {
114
+ add("has no commit step: a step titled Commit, or a `git commit` in a step's code");
115
+ }
116
+ if (task.estimate !== null && task.estimate > maxTaskCalls) {
117
+ add(`estimates ${task.estimate} tool calls, over swarm.review.maxTaskCalls (${maxTaskCalls}); split it`);
118
+ }
119
+ }
120
+ return problems;
121
+ }
122
+
123
+ /** `qc plan-check <plan.md>`. @returns the exit code */
124
+ export function runPlanCheck(config, [file] = []) {
125
+ if (!file) {
126
+ console.error("usage: qc plan-check <plan.md>");
127
+ return 2;
128
+ }
129
+ let markdown;
130
+ try {
131
+ markdown = readFileSync(path.resolve(config.root ?? process.cwd(), file), "utf8");
132
+ } catch (error) {
133
+ console.error(`FAIL plan-check ${file}: cannot read it (${error.message})`);
134
+ return 1;
135
+ }
136
+ let maxTaskCalls;
137
+ try {
138
+ maxTaskCalls = reviewSettings(config.swarm)?.maxTaskCalls ?? config.swarm?.review?.maxTaskCalls ?? reviewDefaults.maxTaskCalls;
139
+ } catch (error) {
140
+ console.error(error.message);
141
+ return 1;
142
+ }
143
+ const problems = checkPlan(markdown, { maxTaskCalls });
144
+ for (const problem of problems) {
145
+ console.error(`FAIL plan-check ${problem.task === null ? file : `Task ${problem.task}`}: ${problem.detail}`);
146
+ }
147
+ if (problems.length > 0) return 1;
148
+ const count = parsePlan(markdown).length;
149
+ console.log(`OK plan-check ${file}: ${count} task${count === 1 ? "" : "s"}`);
150
+ return 0;
151
+ }
@@ -0,0 +1,143 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { checkPlan, parsePlan } from "./plan-check.mjs";
9
+
10
+ const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
11
+ const FENCE = "`".repeat(3);
12
+
13
+ const task = (n, { files = true, fileLines = null, exempt = null, testStep = true, commit = true, estimate = null, extra = [] } = {}) =>
14
+ [
15
+ `### Task ${n}: Part ${n}`,
16
+ "",
17
+ "**Files:**",
18
+ ...(fileLines ?? (files ? [`- Create: \`src/part-${n}.mjs\``, `- Test: \`src/part-${n}.test.mjs\``] : [])),
19
+ ...(exempt === null ? [] : [exempt]),
20
+ ...(estimate === null ? [] : [`**Estimate:** ${estimate} tool calls`]),
21
+ "",
22
+ ...(testStep ? ["- [ ] **Step 1: Write the failing test**"] : ["- [ ] **Step 1: Write the code**"]),
23
+ ...extra,
24
+ ...(commit ? ["- [ ] **Step 2: Commit**"] : []),
25
+ "",
26
+ ].join("\n");
27
+ const plan = (...tasks) => ["# Plan", "", "## Global Constraints", "", ...tasks, "## Notes", ""].join("\n");
28
+
29
+ test("a well-formed plan has no problem", () => {
30
+ assert.deepEqual(checkPlan(plan(task(1, { estimate: 30 }), task(2))), []);
31
+ assert.equal(parsePlan(plan(task(1), task(2))).length, 2);
32
+ });
33
+
34
+ test("a plan with no task heading is refused", () => {
35
+ assert.deepEqual(checkPlan("# Plan\n\nJust prose.\n"), [{ task: null, detail: "the plan has no `### Task N:` heading" }]);
36
+ });
37
+
38
+ test("each missing part is named with its task", () => {
39
+ const problems = checkPlan(plan(task(1, { files: false }), task(2, { testStep: false }), task(3, { commit: false })));
40
+ assert.deepEqual(problems.map((problem) => problem.task), [1, 2, 3]);
41
+ assert.match(problems[0].detail, /names no file/);
42
+ assert.match(problems[1].detail, /no test step/);
43
+ assert.match(problems[2].detail, /no commit step/);
44
+ });
45
+
46
+ test("an estimate over the budget is refused, and a range counts its upper end", () => {
47
+ assert.match(checkPlan(plan(task(1, { estimate: 36 })))[0].detail, /estimates 36 tool calls, over swarm\.review\.maxTaskCalls \(35\)/);
48
+ assert.match(checkPlan(plan(task(1, { estimate: "20-40" })))[0].detail, /estimates 40/);
49
+ assert.deepEqual(checkPlan(plan(task(1, { estimate: 20 })), { maxTaskCalls: 20 }), []);
50
+ assert.equal(checkPlan(plan(task(1, { estimate: 21 })), { maxTaskCalls: 20 }).length, 1);
51
+ });
52
+
53
+ test("fenced code is not structure, but a git commit in it is a commit step", () => {
54
+ const fenced = [FENCE + "markdown", "### Task 9: Not a task", FENCE, FENCE + "bash", "git commit -m x", FENCE];
55
+ const tasks = parsePlan(plan(task(1, { commit: false, extra: fenced })));
56
+ assert.deepEqual(tasks.map((found) => found.number), [1]);
57
+ assert.equal(tasks[0].commitCommand, true);
58
+ assert.deepEqual(checkPlan(plan(task(1, { commit: false, extra: fenced }))), []);
59
+ });
60
+
61
+ test("qc plan-check exits 0 on a good plan and 1 on a bad one, reading the budget from the config", (t) => {
62
+ const dir = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-plan-check-")));
63
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
64
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, review: { maxTaskCalls: 10 } } }));
65
+ writeFileSync(path.join(dir, "good.md"), plan(task(1, { estimate: 10 })));
66
+ writeFileSync(path.join(dir, "bad.md"), plan(task(1, { estimate: 20 })));
67
+ const good = spawnSync(process.execPath, [QC, "plan-check", "good.md"], { cwd: dir, encoding: "utf8" });
68
+ assert.equal(good.status, 0, good.stderr);
69
+ assert.match(good.stdout, /OK {2}plan-check {2}good\.md: 1 task/);
70
+ const bad = spawnSync(process.execPath, [QC, "plan-check", "bad.md"], { cwd: dir, encoding: "utf8" });
71
+ assert.equal(bad.status, 1);
72
+ assert.match(bad.stderr, /FAIL {2}plan-check {2}Task 1: estimates 20 tool calls, over swarm\.review\.maxTaskCalls \(10\)/);
73
+ const missing = spawnSync(process.execPath, [QC, "plan-check", "none.md"], { cwd: dir, encoding: "utf8" });
74
+ assert.equal(missing.status, 1);
75
+ });
76
+
77
+ const DOC_FILES = ["- Modify: `README.md` (the table)", "- Modify: `packages/pkg/package.json` (`version` bump)", "- Modify: `CHANGELOG.md`"];
78
+
79
+ test("a task with no code may carry the Test: none line in place of a test step", () => {
80
+ const exempt = "Test: none — a docs and version change with no code";
81
+ const docs = task(1, { fileLines: DOC_FILES, exempt, testStep: false });
82
+ assert.deepEqual(checkPlan(plan(docs)), []);
83
+ assert.deepEqual(checkPlan(plan(task(1, { fileLines: DOC_FILES, exempt: "- " + exempt, testStep: false }))), []);
84
+ assert.equal(parsePlan(plan(docs))[0].files, 3, "the exemption line is not a file");
85
+ });
86
+
87
+ test("the Test: none line needs a reason of a few words", () => {
88
+ for (const exempt of ["Test: none", "Test: none — ", "Test: none — docs", "Test: none — docs only"]) {
89
+ const problems = checkPlan(plan(task(1, { fileLines: DOC_FILES, exempt, testStep: false })));
90
+ assert.equal(problems.length, 1, exempt);
91
+ assert.match(problems[0].detail, /Test: none.*reason/, exempt);
92
+ }
93
+ });
94
+
95
+ test("the Test: none line is refused for a task that names a source file", () => {
96
+ const code = ["- Modify: `README.md`", "- Modify: `src/photos/create.ts` (drop the runner)"];
97
+ const problems = checkPlan(plan(task(1, { fileLines: code, exempt: "Test: none — the gates cover this cleanup", testStep: false })));
98
+ assert.equal(problems.length, 1);
99
+ assert.match(problems[0].detail, /src\/photos\/create\.ts/);
100
+ assert.match(problems[0].detail, /Test: none/);
101
+ assert.equal(checkPlan(plan(task(1, { fileLines: code, exempt: "Test: none — the gates cover this cleanup" }))).length, 1, "a test step does not excuse it");
102
+ });
103
+
104
+ test("the missing-test-step message names the Test: none line as the way out", () => {
105
+ const [problem] = checkPlan(plan(task(1, { testStep: false })));
106
+ assert.match(problem.detail, /no test step/);
107
+ assert.match(problem.detail, /Test: none — <reason>/);
108
+ });
109
+
110
+ const EXEMPT = "Test: none — the gates cover this cleanup";
111
+ const refusedFor = (fileLines) => checkPlan(plan(task(1, { fileLines, exempt: EXEMPT, testStep: false })));
112
+
113
+ test("a line range after the path does not hide a source file", () => {
114
+ const problems = refusedFor(["- Modify: `src/a.ts:12-40`", "- Modify: `src/b.mjs:7`"]);
115
+ assert.equal(problems.length, 1);
116
+ assert.match(problems[0].detail, /src\/a\.ts/);
117
+ assert.match(problems[0].detail, /src\/b\.mjs/);
118
+ assert.deepEqual(refusedFor(["- Modify: `docs/guide.md:3-9`", "- Modify: `package.json:2`"]), []);
119
+ });
120
+
121
+ test("every path on a Files line is read, not only the first", () => {
122
+ assert.equal(refusedFor(["- Modify: `README.md`, `src/b.ts`"]).length, 1);
123
+ assert.equal(refusedFor(["- Modify: README.md and scripts/build.sh"]).length, 1);
124
+ assert.equal(refusedFor(["- Modify: `README.md`; Test: `backend/tests/cli.test.ts`"]).length, 1);
125
+ });
126
+
127
+ test("a path that is not a document counts as source, so the exemption fails closed", () => {
128
+ for (const name of ["Dockerfile", "Makefile", "bin/run", "src/a.mts", "src/a.cts", "api/photo.proto", "infra/main.tf"]) {
129
+ const problems = refusedFor([`- Modify: \`README.md\`, \`${name}\``]);
130
+ assert.equal(problems.length, 1, name);
131
+ assert.match(problems[0].detail, new RegExp(name.replace(/[./]/g, "\\$&")), name);
132
+ }
133
+ assert.equal(refusedFor(["- Modify: `Dockerfile`"]).length, 1);
134
+ const docs = ["- Modify: `CHANGELOG.md`", "- Modify: `LICENSE`", "- Modify: `a/b.yaml`, `c.yml`, `d.json`", "- Modify: `notes.txt`, `page.mdx`"];
135
+ assert.deepEqual(refusedFor(docs), []);
136
+ });
137
+
138
+ test("an estimate range accepts a hyphen, an en dash, an em dash, and to", () => {
139
+ for (const range of ["20-40", "20–40", "20—40", "20 to 40"]) {
140
+ assert.match(checkPlan(plan(task(1, { estimate: range })))[0].detail, /estimates 40 tool calls, over/, range);
141
+ }
142
+ assert.deepEqual(checkPlan(plan(task(1, { estimate: "10–30" }))), []);
143
+ });
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ // The trigger that runs the plan check when a planner reports. The hand-back gate refuses a report whose
3
+ // plan fails `qc plan-check`, and the stop records the plan in the ledger.
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { appendRecord } from "./ledger.mjs";
10
+ import { checkPlan } from "./plan-check.mjs";
11
+ import { dropReport, keepReport, reportOf } from "./report-stash.mjs";
12
+ import { nativePath } from "./workflow-place.mjs";
13
+ import { workflowOf } from "./workflow-settings.mjs";
14
+
15
+ const HANDBACK = "SubagentHandback";
16
+ const PLAN_LINE = /^[ \t]*PLAN:[ \t]*(\S.*?)[ \t]*$/m;
17
+ const QUOTES = /^["'`]|["'`]$/g;
18
+
19
+ const preContext = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
20
+ const deny = (reason) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason } });
21
+ const block = (reason) => ({ decision: "block", reason });
22
+
23
+ /** The path on a report's `PLAN:` line, or null. */
24
+ export const planPathOf = (text) => PLAN_LINE.exec(String(text))?.[1]?.replace(QUOTES, "") ?? null;
25
+
26
+ /** @returns what the planner must fix before its report goes through; empty when the plan passes. */
27
+ export function planProblems(text, cwd, maxTaskCalls) {
28
+ const named = planPathOf(text);
29
+ if (!named) return ["a line that starts `PLAN:` with the plan's absolute path"];
30
+ const file = path.resolve(cwd, nativePath(named));
31
+ let markdown;
32
+ try {
33
+ markdown = readFileSync(file, "utf8");
34
+ } catch {
35
+ return [`a plan at ${file}, which cannot be read`];
36
+ }
37
+ return checkPlan(markdown, { maxTaskCalls }).map((problem) => (problem.task === null ? problem.detail : `Task ${problem.task} ${problem.detail}`));
38
+ }
39
+
40
+ const refusal = (problems) => `Plan check: fix these, then send the report again. ${problems.map((problem, i) => `${i + 1}) ${problem}.`).join(" ")}`;
41
+
42
+ /** A block already held this stop once, so it ends now, records nothing, and says what is still missing. */
43
+ const held = (problems) => ({ systemMessage: `${refusal(problems)} A block already held this stop once, so it ends now and the ledger records nothing.` });
44
+
45
+ /** The verdict on one hook event. @returns the hook output, or null to let it pass with no message. */
46
+ export function decide(call, tmp = os.tmpdir()) {
47
+ const event = call.hook_event_name;
48
+ const onHandback = call.tool_name === HANDBACK && (event === "PreToolUse" || event === "PostToolUse");
49
+ if (!onHandback && event !== "SubagentStop") return null;
50
+ const agentId = typeof call.agent_id === "string" && call.agent_id !== "" ? call.agent_id : null;
51
+ if (!agentId) return null;
52
+ let workflow;
53
+ try {
54
+ workflow = workflowOf(call, tmp);
55
+ } catch (error) {
56
+ return event === "PreToolUse" ? preContext(`Plan check is off: ${error.message}`) : null;
57
+ }
58
+ if (!workflow || !workflow.review.plannerTypes.includes(call.agent_type)) return null;
59
+ const session = call.session_id ?? "session";
60
+ if (event === "PostToolUse") {
61
+ try {
62
+ keepReport(session, agentId, String(call.tool_input?.message ?? ""), tmp);
63
+ } catch {
64
+ // Without the kept report the stop judges the closing text, and asks for the PLAN: line again.
65
+ }
66
+ return null;
67
+ }
68
+ const text = event === "PreToolUse" ? String(call.tool_input?.message ?? "") : reportOf(call, tmp);
69
+ const cwd = call.cwd ?? process.cwd();
70
+ const problems = planProblems(text, cwd, workflow.review.maxTaskCalls);
71
+ if (problems.length > 0) {
72
+ if (event === "PreToolUse") return deny(refusal(problems));
73
+ return call.stop_hook_active === true ? held(problems) : block(refusal(problems));
74
+ }
75
+ if (event === "PreToolUse") return null;
76
+ try {
77
+ appendRecord(workflow.ledger, { type: "stop", session, agentType: call.agent_type, agentId, role: "planner", plan: path.resolve(cwd, nativePath(planPathOf(text))) });
78
+ dropReport(session, agentId, tmp);
79
+ } catch (error) {
80
+ return { systemMessage: `Plan check: the ledger write failed (${error.message}), so this planner stop is not recorded.` };
81
+ }
82
+ return null;
83
+ }
84
+
85
+ async function readStdin() {
86
+ let data = "";
87
+ for await (const chunk of process.stdin) data += chunk;
88
+ return data;
89
+ }
90
+
91
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
92
+ if (isEntryPoint) {
93
+ let call = null;
94
+ try {
95
+ call = JSON.parse(await readStdin());
96
+ } catch {
97
+ // Not hook input, so there is no plan to check.
98
+ }
99
+ const output = call ? decide(call) : null;
100
+ if (output) process.stdout.write(JSON.stringify(output));
101
+ }
@@ -0,0 +1,136 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { readLedger } from "./ledger.mjs";
9
+ import { decide, planPathOf } from "./plan-stop.mjs";
10
+
11
+ const HOOK = fileURLToPath(new URL("./plan-stop.mjs", import.meta.url));
12
+ const PLANNER = fileURLToPath(new URL("../../../../agents/sdd-planner.md", import.meta.url));
13
+ const GOOD = [
14
+ "# Plan",
15
+ "",
16
+ "### Task 1: One",
17
+ "",
18
+ "- Create: `a.mjs`",
19
+ "**Estimate:** 20 tool calls",
20
+ "- [ ] **Step 1: Write the failing test**",
21
+ "- [ ] **Step 2: Commit**",
22
+ "",
23
+ ].join("\n");
24
+
25
+ function workspace(t) {
26
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-plan-stop-")));
27
+ t.after(() => rmSync(base, { recursive: true, force: true }));
28
+ const on = path.join(base, "on");
29
+ const plain = path.join(base, "plain");
30
+ execFileSync("git", ["init", "-q", on], { stdio: "pipe" });
31
+ execFileSync("git", ["init", "-q", plain], { stdio: "pipe" });
32
+ writeFileSync(path.join(on, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
33
+ const tmp = path.join(base, "tmp");
34
+ const plans = path.join(base, "plans");
35
+ mkdirSync(tmp);
36
+ mkdirSync(plans);
37
+ writeFileSync(path.join(plans, "good.md"), GOOD);
38
+ writeFileSync(path.join(plans, "big.md"), GOOD.replace("20 tool calls", "50 tool calls"));
39
+ return { on, plain, tmp, plans, ledger: path.join(on, ".git", "qc", "ledger.jsonl") };
40
+ }
41
+
42
+ const handback = (cwd, message, event = "PreToolUse") => ({
43
+ session_id: "s",
44
+ cwd,
45
+ hook_event_name: event,
46
+ tool_name: "SubagentHandback",
47
+ tool_input: { message },
48
+ agent_id: "planner-1",
49
+ agent_type: "architecture:sdd-planner",
50
+ });
51
+ const stop = (cwd, last, active = false) => ({
52
+ session_id: "s",
53
+ cwd,
54
+ hook_event_name: "SubagentStop",
55
+ agent_id: "planner-1",
56
+ agent_type: "sdd-planner",
57
+ last_assistant_message: last,
58
+ stop_hook_active: active,
59
+ });
60
+ const denied = (output) => output?.hookSpecificOutput?.permissionDecisionReason ?? null;
61
+
62
+ test("the plan path is read from its PLAN: line", () => {
63
+ assert.equal(planPathOf("PLAN: C:/plans/a.md\nTask 1: 20 calls"), "C:/plans/a.md");
64
+ assert.equal(planPathOf("The plan is at a.md"), null);
65
+ });
66
+
67
+ test("with swarm.dispatch off, or for another agent type, nothing is judged", (t) => {
68
+ const ws = workspace(t);
69
+ assert.equal(decide(handback(ws.plain, "no plan line"), ws.tmp), null);
70
+ assert.equal(decide({ ...stop(ws.on, "no plan line"), agent_type: "sdd-reviewer" }, ws.tmp), null);
71
+ });
72
+
73
+ test("a planner hand-back with no PLAN: line, an unreadable plan, or a plan that fails the check is refused", (t) => {
74
+ const ws = workspace(t);
75
+ assert.match(denied(decide(handback(ws.on, "Done."), ws.tmp)) ?? "", /PLAN:/);
76
+ assert.match(denied(decide(handback(ws.on, `PLAN: ${path.join(ws.plans, "none.md")}`), ws.tmp)) ?? "", /cannot be read/);
77
+ assert.match(denied(decide(handback(ws.on, `PLAN: ${path.join(ws.plans, "big.md")}`), ws.tmp)) ?? "", /Task 1 estimates 50 tool calls/);
78
+ });
79
+
80
+ test("a kept hand-back with a good plan lets the stop pass, and the stop is recorded with the plan", (t) => {
81
+ const ws = workspace(t);
82
+ const message = `PLAN: ${path.join(ws.plans, "good.md")}\nTask 1: 20 calls`;
83
+ assert.equal(decide(handback(ws.on, message), ws.tmp), null);
84
+ assert.equal(decide(handback(ws.on, message, "PostToolUse"), ws.tmp), null);
85
+ assert.equal(decide(stop(ws.on, "Sent."), ws.tmp), null);
86
+ const [record] = readLedger(ws.ledger);
87
+ assert.deepEqual([record.type, record.role, record.plan], ["stop", "planner", path.join(ws.plans, "good.md")]);
88
+ });
89
+
90
+ test("a planner stop with no hand-back is judged on its last message", (t) => {
91
+ const ws = workspace(t);
92
+ assert.equal(decide(stop(ws.on, "Done."), ws.tmp)?.decision, "block");
93
+ assert.equal(decide(stop(ws.on, `PLAN: ${path.join(ws.plans, "good.md")}`), ws.tmp), null);
94
+ });
95
+
96
+ test("the planner definition asks for the PLAN: line and the estimate line", () => {
97
+ const text = readFileSync(PLANNER, "utf8");
98
+ assert.match(text, /`PLAN: <absolute path of the plan>`/);
99
+ assert.match(text, /`\*\*Estimate:\*\* <n> tool calls`/);
100
+ });
101
+
102
+ test("the hook process is silent in a checkout without the checks", (t) => {
103
+ const ws = workspace(t);
104
+ const result = spawnSync(process.execPath, [HOOK], {
105
+ input: JSON.stringify(stop(ws.plain, "Done.")),
106
+ env: { ...process.env, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp },
107
+ encoding: "utf8",
108
+ });
109
+ assert.equal(result.status, 0, result.stderr);
110
+ assert.equal(result.stdout, "");
111
+ assert.equal(existsSync(ws.ledger), false);
112
+ });
113
+
114
+ test("a stop that a block already held once ends with a message and records nothing", (t) => {
115
+ const ws = workspace(t);
116
+ assert.equal(decide(stop(ws.on, "Done."), ws.tmp)?.decision, "block");
117
+ const output = decide(stop(ws.on, "Done.", true), ws.tmp);
118
+ assert.equal(output.decision, undefined);
119
+ assert.match(output.systemMessage, /PLAN:/);
120
+ assert.equal(existsSync(ws.ledger), false);
121
+ });
122
+
123
+ test("the retry after a block records the plan once the report is fixed", (t) => {
124
+ const ws = workspace(t);
125
+ assert.equal(decide(stop(ws.on, "Done."), ws.tmp)?.decision, "block");
126
+ assert.equal(decide(stop(ws.on, `PLAN: ${path.join(ws.plans, "good.md")}`, true), ws.tmp), null);
127
+ assert.deepEqual(readLedger(ws.ledger).map((record) => [record.type, record.role]), [["stop", "planner"]]);
128
+ });
129
+
130
+ test("a plan named with a Git Bash drive path resolves on Windows", { skip: process.platform !== "win32" }, (t) => {
131
+ const ws = workspace(t);
132
+ const gitBash = "/" + path.join(ws.plans, "good.md").replace(/^([A-Za-z]):/, (_, drive) => drive.toLowerCase()).replaceAll("\\", "/");
133
+ assert.equal(decide(handback(ws.on, `PLAN: ${gitBash}`), ws.tmp), null);
134
+ assert.equal(decide(stop(ws.on, `PLAN: ${gitBash}`), ws.tmp), null);
135
+ assert.equal(readLedger(ws.ledger)[0].plan.toLowerCase(), path.join(ws.plans, "good.md").toLowerCase());
136
+ });