architecture-harness 0.25.0 → 0.26.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 (244) hide show
  1. package/package.json +3 -22
  2. package/src/cli/ask.mjs +42 -0
  3. package/src/cli/ask.test.mjs +40 -0
  4. package/src/cli/branch-sync.mjs +126 -0
  5. package/src/cli/branch-sync.test.mjs +428 -0
  6. package/src/cli/budget-guard.mjs +74 -5
  7. package/src/cli/budget-guard.test.mjs +185 -2
  8. package/src/cli/budget-report.mjs +85 -0
  9. package/src/cli/budget-report.test.mjs +173 -0
  10. package/src/cli/budget.mjs +8 -5
  11. package/src/cli/check-commands.mjs +123 -11
  12. package/src/cli/check-commands.test.mjs +360 -6
  13. package/src/cli/check-feature-switches.test.mjs +110 -0
  14. package/src/cli/check-full.test.mjs +152 -0
  15. package/src/cli/check-verdict.mjs +46 -0
  16. package/src/cli/check-verdict.test.mjs +32 -0
  17. package/src/cli/check.mjs +137 -4
  18. package/src/cli/check.test.mjs +45 -0
  19. package/src/cli/checkpoint.mjs +143 -0
  20. package/src/cli/checkpoint.test.mjs +146 -0
  21. package/src/cli/child-run.mjs +7 -2
  22. package/src/cli/child-run.test.mjs +17 -2
  23. package/src/cli/ci-failures.mjs +304 -0
  24. package/src/cli/ci-failures.test.mjs +615 -0
  25. package/src/cli/ci-preview.mjs +62 -0
  26. package/src/cli/ci-preview.test.mjs +85 -0
  27. package/src/cli/ci-state.mjs +25 -29
  28. package/src/cli/ci-state.test.mjs +174 -2
  29. package/src/cli/ci-template.test.mjs +86 -0
  30. package/src/cli/claude-core.test.mjs +37 -0
  31. package/src/cli/codex-implement.mjs +580 -47
  32. package/src/cli/codex-implement.test.mjs +1946 -29
  33. package/src/cli/codex-limit.mjs +85 -0
  34. package/src/cli/codex-limit.test.mjs +179 -0
  35. package/src/cli/codex-reset.mjs +78 -0
  36. package/src/cli/codex-reset.test.mjs +192 -0
  37. package/src/cli/codex-verify.mjs +230 -0
  38. package/src/cli/codex-verify.test.mjs +402 -0
  39. package/src/cli/comment-watch.mjs +391 -0
  40. package/src/cli/comment-watch.test.mjs +392 -0
  41. package/src/cli/commit-guard.mjs +219 -0
  42. package/src/cli/commit-guard.test.mjs +809 -0
  43. package/src/cli/context-budgets.mjs +47 -0
  44. package/src/cli/context-budgets.test.mjs +96 -0
  45. package/src/cli/context-watch.mjs +116 -0
  46. package/src/cli/context-watch.test.mjs +395 -0
  47. package/src/cli/contract-history.mjs +1 -1
  48. package/src/cli/controller-guard.mjs +38 -0
  49. package/src/cli/controller-guard.test.mjs +66 -2
  50. package/src/cli/cost-stop.mjs +5 -1
  51. package/src/cli/cost-stop.test.mjs +26 -0
  52. package/src/cli/diff-shape.mjs +162 -0
  53. package/src/cli/diff-shape.test.mjs +200 -0
  54. package/src/cli/direct-lane.mjs +32 -19
  55. package/src/cli/direct-lane.test.mjs +21 -3
  56. package/src/cli/dispatch-guard.mjs +11 -0
  57. package/src/cli/dispatch-guard.test.mjs +145 -10
  58. package/src/cli/dispatch-reminder.mjs +23 -10
  59. package/src/cli/dispatch-reminder.test.mjs +63 -11
  60. package/src/cli/dispatch-route.mjs +54 -0
  61. package/src/cli/dispatch-route.test.mjs +101 -0
  62. package/src/cli/dispatch-slot.mjs +2 -2
  63. package/src/cli/dispatch-slot.test.mjs +18 -19
  64. package/src/cli/dispatch.test.mjs +3 -3
  65. package/src/cli/e2e-affected.mjs +15 -0
  66. package/src/cli/e2e-affected.test.mjs +73 -0
  67. package/src/cli/fleet.mjs +180 -0
  68. package/src/cli/fleet.test.mjs +213 -0
  69. package/src/cli/gate-slot.mjs +2 -1
  70. package/src/cli/gh-merge-command.mjs +96 -31
  71. package/src/cli/gh-merge-command.test.mjs +74 -0
  72. package/src/cli/gh-run.mjs +64 -3
  73. package/src/cli/gh-run.test.mjs +66 -1
  74. package/src/cli/git-hooks.test.mjs +25 -3
  75. package/src/cli/git-read.mjs +2 -1
  76. package/src/cli/integrate-tree.mjs +47 -0
  77. package/src/cli/integrate.mjs +143 -40
  78. package/src/cli/integrate.test.mjs +347 -1
  79. package/src/cli/integration-lane.mjs +62 -0
  80. package/src/cli/integration-lane.test.mjs +213 -0
  81. package/src/cli/ledger.mjs +4 -2
  82. package/src/cli/ledger.test.mjs +12 -3
  83. package/src/cli/legs.mjs +53 -0
  84. package/src/cli/legs.test.mjs +70 -0
  85. package/src/cli/lint-changed.mjs +59 -10
  86. package/src/cli/lint-changed.test.mjs +112 -1
  87. package/src/cli/locked-tests.mjs +134 -0
  88. package/src/cli/locked-tests.test.mjs +188 -0
  89. package/src/cli/merge-guard.mjs +234 -62
  90. package/src/cli/merge-guard.test.mjs +768 -39
  91. package/src/cli/metrics.mjs +53 -0
  92. package/src/cli/metrics.test.mjs +73 -0
  93. package/src/cli/milestone.mjs +297 -0
  94. package/src/cli/milestone.test.mjs +294 -0
  95. package/src/cli/mutate.mjs +203 -0
  96. package/src/cli/mutate.test.mjs +134 -0
  97. package/src/cli/output-redaction.mjs +26 -0
  98. package/src/cli/output-redaction.test.mjs +117 -0
  99. package/src/cli/overview.mjs +131 -0
  100. package/src/cli/overview.test.mjs +137 -0
  101. package/src/cli/pause.mjs +93 -0
  102. package/src/cli/pause.test.mjs +109 -0
  103. package/src/cli/plan-check.mjs +84 -12
  104. package/src/cli/plan-check.test.mjs +152 -2
  105. package/src/cli/plan-stop.mjs +7 -4
  106. package/src/cli/plan-stop.test.mjs +87 -0
  107. package/src/cli/platform-risk.mjs +46 -0
  108. package/src/cli/platform-risk.test.mjs +38 -0
  109. package/src/cli/plugin-skills.test.mjs +25 -0
  110. package/src/cli/pr-guard.mjs +128 -0
  111. package/src/cli/pr-guard.test.mjs +154 -0
  112. package/src/cli/promotion-branch.mjs +2 -0
  113. package/src/cli/qc.mjs +160 -27
  114. package/src/cli/qc.test.mjs +93 -0
  115. package/src/cli/report-stop.mjs +5 -0
  116. package/src/cli/report-stop.test.mjs +23 -1
  117. package/src/cli/retry-failed.mjs +3 -1
  118. package/src/cli/review-gate.mjs +24 -6
  119. package/src/cli/review-gate.test.mjs +116 -0
  120. package/src/cli/review-promotion.mjs +107 -0
  121. package/src/cli/review-promotion.test.mjs +251 -0
  122. package/src/cli/role-budget.mjs +50 -0
  123. package/src/cli/role-budget.test.mjs +91 -0
  124. package/src/cli/run-log.mjs +73 -0
  125. package/src/cli/run-log.test.mjs +121 -0
  126. package/src/cli/secret-patterns.mjs +16 -0
  127. package/src/cli/secret-patterns.test.mjs +73 -0
  128. package/src/cli/setup-block.mjs +24 -0
  129. package/src/cli/setup-block.test.mjs +96 -0
  130. package/src/cli/setup-checks.mjs +65 -0
  131. package/src/cli/setup-checks.test.mjs +158 -0
  132. package/src/cli/setup-compaction.mjs +55 -0
  133. package/src/cli/setup-compaction.test.mjs +115 -0
  134. package/src/cli/setup-skills.mjs +65 -0
  135. package/src/cli/setup-skills.test.mjs +171 -0
  136. package/src/cli/setup.mjs +107 -0
  137. package/src/cli/setup.test.mjs +275 -0
  138. package/src/cli/skill-length.test.mjs +8 -0
  139. package/src/cli/spawn-command.mjs +47 -0
  140. package/src/cli/spawn-command.test.mjs +64 -0
  141. package/src/cli/task-gate-review.test.mjs +21 -2
  142. package/src/cli/task-gate.mjs +25 -12
  143. package/src/cli/task-gate.test.mjs +43 -5
  144. package/src/cli/tokens.mjs +46 -3
  145. package/src/cli/tokens.test.mjs +103 -3
  146. package/src/cli/tools.mjs +49 -0
  147. package/src/cli/tools.test.mjs +89 -0
  148. package/src/cli/transcript-usage.mjs +27 -0
  149. package/src/cli/transcript-usage.test.mjs +34 -0
  150. package/src/cli/user-config-package.mjs +1 -1
  151. package/src/cli/user-config-toml.mjs +63 -7
  152. package/src/cli/user-config.mjs +39 -7
  153. package/src/cli/user-config.test.mjs +238 -5
  154. package/src/cli/watch-arm.mjs +39 -0
  155. package/src/cli/watch-arm.test.mjs +87 -0
  156. package/src/cli/watch.mjs +80 -35
  157. package/src/cli/watch.test.mjs +233 -27
  158. package/src/cli/work-order-guard.mjs +2 -1
  159. package/src/cli/workflow-hooks.test.mjs +18 -4
  160. package/src/cli/workflow-settings.mjs +44 -8
  161. package/src/cli/workflow-settings.test.mjs +124 -1
  162. package/src/cli/worktree.mjs +14 -1
  163. package/src/cli/worktree.test.mjs +20 -1
  164. package/src/config.mjs +174 -7
  165. package/src/config.test.mjs +327 -5
  166. package/src/consumer-package.mjs +31 -0
  167. package/src/consumer-package.test.mjs +54 -0
  168. package/src/descriptions.mjs +2 -0
  169. package/src/eslint/index.mjs +12 -0
  170. package/src/eslint/jsx.mjs +20 -0
  171. package/src/eslint/preset.mjs +26 -2
  172. package/src/eslint/preset.test.mjs +104 -2
  173. package/src/eslint/rules/no-arbitrary-class-value.mjs +32 -0
  174. package/src/eslint/rules/no-literal-color.mjs +94 -0
  175. package/src/eslint/rules/no-static-inline-style.mjs +41 -0
  176. package/src/eslint/rules/one-component-per-file.mjs +70 -0
  177. package/src/eslint/rules/raw-element-in-primitive.mjs +31 -0
  178. package/src/eslint/rules/timeless-comment.mjs +92 -0
  179. package/src/eslint/rules.test.mjs +189 -0
  180. package/src/eslint/ui-regressions.test.mjs +39 -0
  181. package/src/gates/contract-operations.mjs +3 -3
  182. package/src/gates/contract-operations.test.mjs +28 -0
  183. package/src/gates/feature-switches.mjs +19 -0
  184. package/src/gates/feature-switches.test.mjs +55 -0
  185. package/src/gates/plain-language.mjs +396 -0
  186. package/src/gates/plain-language.test.mjs +210 -0
  187. package/src/gates/runtime-imports.test.mjs +114 -0
  188. package/src/gates/saga-key.test.mjs +1 -1
  189. package/src/global-skills.mjs +9 -0
  190. package/src/global-skills.test.mjs +53 -0
  191. package/src/plugin.test.mjs +3 -2
  192. package/src/ui/class-sites.mjs +38 -6
  193. package/src/ui/codemod.mjs +4 -1
  194. package/src/ui/codemod.test.mjs +52 -0
  195. package/src/ui/components.mjs +5 -3
  196. package/src/ui/components.test.mjs +8 -0
  197. package/src/ui/dupes.test.mjs +18 -0
  198. package/templates/docs/enforcement.md +12 -2
  199. package/templates/docs/ui.md +33 -0
  200. package/templates/githooks/pre-commit +1 -0
  201. package/templates/githooks/pre-push +11 -2
  202. package/templates/github/workflows/ci.yml +57 -3
  203. package/user-config/claude/CLAUDE.core.md +28 -0
  204. package/user-config/claude/settings.shared.json +41 -1
  205. package/src/cli/screens-discovery.mjs +0 -60
  206. package/src/cli/screens.mjs +0 -84
  207. package/src/cli/stack.mjs +0 -14
  208. package/src/cli/throwaway-db.mjs +0 -127
  209. package/src/cli/throwaway-db.test.mjs +0 -83
  210. package/src/screens/auth-context.test.mjs +0 -41
  211. package/src/screens/auth-run.test.mjs +0 -147
  212. package/src/screens/auth.mjs +0 -223
  213. package/src/screens/auth.test.mjs +0 -76
  214. package/src/screens/capture-idle.test.mjs +0 -27
  215. package/src/screens/capture.browser-test.mjs +0 -73
  216. package/src/screens/capture.mjs +0 -175
  217. package/src/screens/capture.test.mjs +0 -28
  218. package/src/screens/catalog.browser-test.mjs +0 -32
  219. package/src/screens/catalog.mjs +0 -72
  220. package/src/screens/catalog.test.mjs +0 -36
  221. package/src/screens/chrome.mjs +0 -21
  222. package/src/screens/compare.mjs +0 -40
  223. package/src/screens/compare.test.mjs +0 -30
  224. package/src/screens/discovery.browser-test.mjs +0 -29
  225. package/src/screens/discovery.mjs +0 -158
  226. package/src/screens/discovery.test.mjs +0 -27
  227. package/src/screens/inventory.mjs +0 -69
  228. package/src/screens/inventory.test.mjs +0 -10
  229. package/src/screens/map.mjs +0 -63
  230. package/src/screens/map.test.mjs +0 -35
  231. package/src/screens/open.browser-test.mjs +0 -50
  232. package/src/screens/regions.mjs +0 -137
  233. package/src/screens/regions.test.mjs +0 -38
  234. package/src/screens/session-files.mjs +0 -39
  235. package/src/screens/session-files.test.mjs +0 -39
  236. package/src/screens/setup.browser-test.mjs +0 -49
  237. package/src/screens/setup.mjs +0 -78
  238. package/src/screens/stack-auth.browser-test.mjs +0 -30
  239. package/src/screens/stack-auth.mjs +0 -106
  240. package/src/screens/stack-auth.test.mjs +0 -65
  241. package/src/screens/write-guard.mjs +0 -26
  242. package/src/stack/stack.mjs +0 -131
  243. package/src/stack/stack.test.mjs +0 -40
  244. package/src/stack/supervisor.mjs +0 -30
@@ -0,0 +1,294 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import test from "node:test";
7
+ import { collectFinished, runMilestone } from "./milestone.mjs";
8
+ import { appendRecord, ledgerFileOf } from "./ledger.mjs";
9
+
10
+ const git = (root, ...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: "pipe" }).trim();
11
+ function file(root, name, text) {
12
+ writeFileSync(path.join(root, name), text);
13
+ git(root, "add", ".");
14
+ git(root, "commit", "-qm", name);
15
+ }
16
+ function fixture(t, { conflict = false } = {}) {
17
+ const top = mkdtempSync(path.join(tmpdir(), "qc-milestone-"));
18
+ t.after(() => rmSync(top, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
19
+ const root = path.join(top, "repo");
20
+ const origin = path.join(top, "origin");
21
+ mkdirSync(root); mkdirSync(origin);
22
+ git(origin, "init", "-q", "--bare");
23
+ git(root, "init", "-q", "-b", "main");
24
+ for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git(root, "config", key, value);
25
+ file(root, "shared.txt", "base\n");
26
+ git(root, "remote", "add", "origin", origin);
27
+ git(root, "push", "-q", "origin", "main");
28
+ const members = [];
29
+ for (let n = 1; n <= 3; n++) {
30
+ const branch = `feat/${n}-member`;
31
+ git(root, "switch", "-qc", branch, "main");
32
+ file(root, conflict && n < 3 ? "shared.txt" : `${n}.txt`, `${n}\n`);
33
+ git(root, "push", "-q", "origin", branch);
34
+ const sha = git(root, "rev-parse", "HEAD");
35
+ members.push({ branch, sha, issue: String(n) });
36
+ appendRecord(ledgerFileOf(root), { type: "verdict", sha, kind: n === 2 ? "branch" : "codex", verdict: "APPROVED" });
37
+ }
38
+ git(root, "switch", "-q", "main");
39
+ const config = { root, worktree: { base: "origin/main" }, swarm: { review: { merge: "branch" } }, generated: { globs: [] } };
40
+ const calls = []; const output = [];
41
+ const io = { say: (s) => output.push(s), gh: (args) => { calls.push(args); return args[1] === "list" ? "[]" : args[1] === "view" ? null : "https://github.com/a/b/pull/1"; } };
42
+ return { root, origin, members, config, calls, output, io };
43
+ }
44
+ const created = (calls) => calls.filter((args) => args[1] === "create");
45
+
46
+ test("merged and closed PRs reserve each candidate without a branch or saved state", async (t) => {
47
+ const f = fixture(t);
48
+ const queried = [];
49
+ const prs = new Map([
50
+ ["milestone/2026-01-02-1", { number: 1, state: "MERGED" }],
51
+ ["milestone/2026-01-02-2", { number: 2, state: "CLOSED" }],
52
+ ]);
53
+ const gh = (args) => {
54
+ if (args[1] !== "list") return f.io.gh(args);
55
+ const candidate = args[args.indexOf("--head") + 1];
56
+ assert.deepEqual(args, ["pr", "list", "--state", "all", "--head", candidate, "--limit", "1", "--json", "number"]);
57
+ queried.push(candidate);
58
+ return JSON.stringify(prs.has(candidate) ? [{ number: prs.get(candidate).number }] : []);
59
+ };
60
+ assert.equal(await runMilestone(f.config, [], { ...f.io, gh, now: new Date(2026, 0, 2) }), 0);
61
+ assert.deepEqual(queried, ["milestone/2026-01-02-1", "milestone/2026-01-02-2", "milestone/2026-01-02-3"]);
62
+ assert.equal(git(f.root, "branch", "--show-current"), "milestone/2026-01-02-3");
63
+ });
64
+
65
+ test("an unreadable candidate PR list fails before creating a branch", async (t) => {
66
+ const f = fixture(t);
67
+ const branches = git(f.root, "branch", "--list");
68
+ const errors = [];
69
+ t.mock.method(console, "error", (message) => errors.push(message));
70
+ const gh = (args) => {
71
+ assert.deepEqual(args, ["pr", "list", "--state", "all", "--head", "milestone/2026-01-02-1", "--limit", "1", "--json", "number"]);
72
+ return null;
73
+ };
74
+ assert.equal(await runMilestone(f.config, [], { ...f.io, gh, now: new Date(2026, 0, 2) }), 1);
75
+ assert.match(errors.join("\n"), /cannot read milestone pull requests/);
76
+ assert.equal(git(f.root, "branch", "--show-current"), "main");
77
+ assert.equal(git(f.root, "branch", "--list"), branches);
78
+ });
79
+
80
+ test("publication reuses an OPEN PR without creating another", async (t) => {
81
+ const f = fixture(t);
82
+ let views = 0;
83
+ const gh = (args) => {
84
+ if (args[1] !== "view") return f.io.gh(args);
85
+ views++;
86
+ return JSON.stringify({ number: 1, state: "OPEN" });
87
+ };
88
+ assert.equal(await runMilestone(f.config, [], { ...f.io, gh }), 0);
89
+ assert.equal(views, 1);
90
+ assert.equal(created(f.calls).length, 0);
91
+ });
92
+
93
+ test("publication creates a PR when the existing PR is MERGED", async (t) => {
94
+ const f = fixture(t);
95
+ const gh = (args) => args[1] === "view"
96
+ ? JSON.stringify({ number: 1, state: "MERGED" })
97
+ : f.io.gh(args);
98
+ assert.equal(await runMilestone(f.config, [], { ...f.io, gh }), 0);
99
+ assert.equal(created(f.calls).length, 1);
100
+ });
101
+
102
+ test("two finished branches → one milestone branch, one PR body with both Refs lines", async (t) => {
103
+ const f = fixture(t);
104
+ appendRecord(ledgerFileOf(f.root), { type: "verdict", sha: f.members[2].sha, kind: "codex", verdict: "CHANGES_REQUIRED" });
105
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
106
+ assert.match(git(f.root, "branch", "--show-current"), /^milestone\/\d{4}-\d{2}-\d{2}-1$/);
107
+ assert.equal(created(f.calls).length, 1);
108
+ const args = created(f.calls)[0];
109
+ assert.ok(!args.includes("--draft"));
110
+ assert.match(args[args.indexOf("--body") + 1], /Refs #1\nRefs #2/);
111
+ assert.equal(git(f.root, "rev-parse", "HEAD"), git(f.root, "rev-parse", "@{upstream}"));
112
+ { // generated files settle once
113
+ const f = fixture(t);
114
+ let runs = 0;
115
+ f.config.generated.command = "generate";
116
+ f.config.generated.globs = ["generated.txt"];
117
+ assert.equal(await runMilestone(f.config, [], { ...f.io, run: () => { runs++; writeFileSync(path.join(f.root, "generated.txt"), "generated output\n"); return 0; } }), 0);
118
+ assert.equal(runs, 1);
119
+ assert.equal(git(f.root, "show", "HEAD:generated.txt"), "generated output");
120
+ assert.equal(git(f.root, "log", "-1", "--format=%s"), "chore: regenerate the generated files");
121
+ assert.equal(git(f.root, "rev-parse", "HEAD"), git(f.root, "rev-parse", "@{upstream}"));
122
+ }
123
+ { // local-date numbering skips occupied local and remote ordinals
124
+ const f = fixture(t);
125
+ git(f.root, "branch", "milestone/2026-01-02-1", "main");
126
+ git(f.root, "push", "-q", "origin", "main:refs/heads/milestone/2026-01-02-2");
127
+ assert.equal(await runMilestone(f.config, [], { ...f.io, now: new Date(2026, 0, 2, 0, 5) }), 0);
128
+ assert.equal(git(f.root, "branch", "--show-current"), "milestone/2026-01-02-3");
129
+ }
130
+ });
131
+
132
+ test("a branch without an APPROVED verdict is not collected", (t) => {
133
+ const f = fixture(t);
134
+ rmSync(ledgerFileOf(f.root));
135
+ assert.deepEqual(collectFinished(f.config), []);
136
+ });
137
+
138
+ test("one conflicting branch is left out and the other two merge", async (t) => {
139
+ const f = fixture(t, { conflict: true });
140
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
141
+ assert.match(f.output.join("\n"), /Left out:.*feat\/2-member/);
142
+ for (const n of [0, 2]) git(f.root, "merge-base", "--is-ancestor", f.members[n].sha, "HEAD");
143
+ assert.match(readFileSync(path.join(f.root, "shared.txt"), "utf8"), /1/);
144
+ assert.match(created(f.calls)[0].at(-1), /Refs #3/);
145
+ { // all conflicts return success without a push or PR and restore the original branch
146
+ const f = fixture(t, { conflict: true });
147
+ appendRecord(ledgerFileOf(f.root), { type: "verdict", sha: f.members[2].sha, kind: "codex", verdict: "CHANGES_REQUIRED" });
148
+ file(f.root, "shared.txt", "new base\n");
149
+ f.config.worktree.base = "main";
150
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
151
+ assert.equal(git(f.root, "branch", "--show-current"), "main");
152
+ assert.deepEqual(f.calls.map((args) => args[1]), ["list"]);
153
+ assert.equal(git(f.root, "branch", "-r", "--list", "origin/milestone/*"), "");
154
+ assert.equal(f.output.filter((s) => s.startsWith("Left out:")).length, 2);
155
+ }
156
+ });
157
+
158
+ test("--drop rebuilds without the named branch", async (t) => {
159
+ const f = fixture(t);
160
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
161
+ const branch = git(f.root, "branch", "--show-current");
162
+ // Pinned members and original base survive later movement of their source refs.
163
+ git(f.root, "branch", "-f", f.members[0].branch, "main");
164
+ assert.equal(await runMilestone(f.config, ["--drop", "feat/2-member"], f.io), 0);
165
+ assert.equal(git(f.root, "branch", "--show-current"), branch);
166
+ assert.throws(() => git(f.root, "cat-file", "-e", "HEAD:2.txt"));
167
+ git(f.root, "cat-file", "-e", "HEAD:1.txt");
168
+ assert.equal(created(f.calls).length, 1);
169
+ assert.ok(f.calls.some((a) => a[1] === "edit" && !a.at(-1).includes("Refs #2")));
170
+
171
+ // Reproduce interruption after the leased push, before the replacement state is saved.
172
+ const interrupted = fixture(t);
173
+ assert.equal(await runMilestone(interrupted.config, [], interrupted.io), 0);
174
+ const name = git(interrupted.root, "branch", "--show-current");
175
+ const manifest = path.join(interrupted.root, ".git", "qc", "milestones", `${name.slice(10)}.json`);
176
+ const old = JSON.parse(readFileSync(manifest, "utf8"));
177
+ assert.equal(await runMilestone(interrupted.config, ["--drop", "feat/2-member"], interrupted.io), 0);
178
+ const pushed = git(interrupted.root, "rev-parse", "HEAD");
179
+ git(interrupted.root, "switch", "-qc", "saved-replay", pushed);
180
+ git(interrupted.root, "branch", "-f", name, old.head);
181
+ git(interrupted.root, "switch", "-q", name);
182
+ old.pendingDrop = { target: "feat/2-member", head: pushed, replay: "saved-replay" };
183
+ writeFileSync(manifest, JSON.stringify(old));
184
+ // A retry must recognize the already published replay and make no second push.
185
+ writeFileSync(path.join(interrupted.root, ".git", "hooks", "pre-push"), "#!/usr/bin/env node\nprocess.exit(1);\n", { mode: 0o755 });
186
+ assert.equal(await runMilestone(interrupted.config, ["--drop", "feat/2-member"], interrupted.io), 0);
187
+ assert.equal(git(interrupted.root, "branch", "--show-current"), name);
188
+ assert.equal(git(interrupted.root, "rev-parse", "HEAD"), pushed);
189
+ const recovered = JSON.parse(readFileSync(manifest, "utf8"));
190
+ assert.equal(recovered.phase, "done");
191
+ assert.equal(recovered.publishedSha, pushed);
192
+ assert.ok(!recovered.pendingDrop);
193
+ assert.ok(!recovered.members.some((m) => m.branch === "feat/2-member"));
194
+ { // drop recovers a GitHub body update failure without another push
195
+ const f = fixture(t);
196
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
197
+ assert.equal(await runMilestone(f.config, ["--drop", "feat/2-member"], { ...f.io, gh: () => null }), 1);
198
+ const head = git(f.root, "rev-parse", "HEAD");
199
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
200
+ assert.equal(git(f.root, "rev-parse", "HEAD"), head);
201
+ assert.ok(f.calls.some((a) => a[1] === "edit" && !a.at(-1).includes("Refs #2")));
202
+ }
203
+ });
204
+
205
+ test("collection pins pushed heads, ignores local-only/stale approvals and honors revocation and scopes", (t) => {
206
+ const f = fixture(t);
207
+ git(f.root, "switch", "-q", f.members[0].branch);
208
+ file(f.root, "local.txt", "local\n");
209
+ assert.equal(collectFinished(f.config)[0].sha, f.members[0].sha);
210
+ git(f.root, "push", "-q", "origin", f.members[0].branch);
211
+ appendRecord(ledgerFileOf(f.root), { type: "verdict", sha: f.members[1].sha, kind: "codex", verdict: "CHANGES_REQUIRED", scope: "security" });
212
+ assert.deepEqual(collectFinished(f.config).map((m) => m.branch), [f.members[2].branch]);
213
+ { // failed fetch refuses stale candidates
214
+ const f = fixture(t);
215
+ git(f.root, "remote", "set-url", "origin", path.join(f.root, "missing"));
216
+ assert.throws(() => collectFinished(f.config), /fetch/);
217
+ }
218
+ });
219
+
220
+ test("dry-run changes no refs or files and no candidates is a successful no-op", async (t) => {
221
+ const f = fixture(t);
222
+ const refs = git(f.root, "show-ref");
223
+ assert.equal(await runMilestone(f.config, ["--dry-run"], f.io), 0);
224
+ assert.equal(git(f.root, "show-ref"), refs);
225
+ assert.equal(f.calls.length, 0);
226
+ rmSync(ledgerFileOf(f.root));
227
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
228
+ assert.match(f.output.join("\n"), /nothing to merge/);
229
+ { // a concurrent milestone refuses before switching branches
230
+ const f = fixture(t);
231
+ const dir = path.join(f.root, ".git", "qc", "milestones");
232
+ mkdirSync(dir, { recursive: true });
233
+ writeFileSync(path.join(dir, "lock"), JSON.stringify({ pid: process.pid }));
234
+ assert.equal(await runMilestone(f.config, [], f.io), 1);
235
+ assert.equal(git(f.root, "branch", "--show-current"), "main");
236
+ assert.equal(f.calls.length, 0);
237
+ }
238
+ });
239
+
240
+ test("publication failure resumes the same branch and PR creation without another batch", async (t) => {
241
+ const f = fixture(t);
242
+ assert.equal(await runMilestone(f.config, [], { ...f.io, gh: (args) => args[1] === "list" ? "[]" : null }), 1);
243
+ const branch = git(f.root, "branch", "--show-current");
244
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
245
+ assert.equal(git(f.root, "branch", "--show-current"), branch);
246
+ assert.equal(created(f.calls).length, 1);
247
+ { // an unfinished clean build resumes from pinned members
248
+ const f = fixture(t);
249
+ f.config.generated.command = "generate";
250
+ assert.equal(await runMilestone(f.config, [], { ...f.io, run: () => 1 }), 1);
251
+ const branch = git(f.root, "branch", "--show-current");
252
+ assert.equal(await runMilestone(f.config, [], { ...f.io, run: () => 0 }), 0);
253
+ assert.equal(git(f.root, "branch", "--show-current"), branch);
254
+ assert.equal(created(f.calls).length, 1);
255
+ }
256
+ { // a rejected initial push resumes the same built milestone
257
+ const f = fixture(t);
258
+ const hook = path.join(f.root, ".git", "hooks", "pre-push");
259
+ writeFileSync(hook, "#!/usr/bin/env node\nprocess.exit(1);\n", { mode: 0o755 });
260
+ assert.equal(await runMilestone(f.config, [], f.io), 1);
261
+ const branch = git(f.root, "branch", "--show-current");
262
+ rmSync(hook);
263
+ git(f.root, "switch", "-q", "main");
264
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
265
+ assert.equal(git(f.root, "rev-parse", `origin/${branch}`), git(f.root, "rev-parse", branch));
266
+ assert.equal(created(f.calls).length, 1);
267
+ }
268
+ });
269
+
270
+ test("a lease race cannot overwrite another writer and retains the pinned replay", async (t) => {
271
+ const f = fixture(t);
272
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
273
+ const branch = git(f.root, "branch", "--show-current");
274
+ const original = git(f.root, "rev-parse", "HEAD");
275
+ const hook = path.join(f.root, ".git", "hooks", "pre-push");
276
+ writeFileSync(hook, `#!/usr/bin/env node\nrequire('node:child_process').execFileSync('git', ['--git-dir', ${JSON.stringify(f.origin)}, 'update-ref', 'refs/heads/${branch}', ${JSON.stringify(f.members[2].sha)}]);\n`, { mode: 0o755 });
277
+ assert.equal(await runMilestone(f.config, ["--drop", "feat/2-member"], f.io), 1);
278
+ assert.equal(git(f.origin, "rev-parse", `refs/heads/${branch}`), f.members[2].sha);
279
+ assert.equal(git(f.root, "rev-parse", "HEAD"), original);
280
+ const state = JSON.parse(readFileSync(path.join(f.root, ".git", "qc", "milestones", `${branch.slice(10)}.json`), "utf8"));
281
+ assert.equal(state.publishedSha, original);
282
+ assert.equal(state.pendingDrop.target, "feat/2-member");
283
+ { // drop refuses a moved published ref and preserves recoverable state
284
+ const f = fixture(t);
285
+ assert.equal(await runMilestone(f.config, [], f.io), 0);
286
+ const branch = git(f.root, "branch", "--show-current");
287
+ const published = git(f.root, "rev-parse", "HEAD");
288
+ file(f.root, "someone.txt", "moved\n");
289
+ git(f.root, "push", "-q", "origin", branch);
290
+ assert.equal(await runMilestone(f.config, ["--drop", "feat/2-member"], f.io), 1);
291
+ assert.equal(git(f.root, "rev-parse", "HEAD"), git(f.root, "rev-parse", `origin/${branch}`));
292
+ assert.notEqual(git(f.root, "rev-parse", "HEAD"), published);
293
+ }
294
+ });
@@ -0,0 +1,203 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { load } from "../config.mjs";
6
+ import { readLockedTests } from "./locked-tests.mjs";
7
+ import { spawnCommand } from "./spawn-command.mjs";
8
+ const cleanup = { recursive: true, force: true, maxRetries: 5, retryDelay: 100 };
9
+ const git = (root, ...args) => execFileSync("git", ["--literal-pathspecs", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
10
+ const names = (text) => text.split("\0").filter(Boolean);
11
+ const testFile = (file) => /\.(test|spec)\.[cm]?js$/.test(file) || /(^|\/)(__tests__|tests?|spec)\//.test(file);
12
+ /** Masks literals and comments without moving source offsets, including across lines. */
13
+ function codeMask(source) {
14
+ let result = "", state = "code", escaped = false, regexClass = false;
15
+ for (let i = 0; i < source.length; i += 1) {
16
+ const c = source[i], next = source[i + 1];
17
+ if (state === "line" && c === "\n") state = "code";
18
+ if (state === "code") {
19
+ if (c === "/" && next === "/") state = "line";
20
+ else if (c === "/" && next === "*") { state = "block"; result += " "; i += 1; continue; }
21
+ else if ('\'"`'.includes(c)) state = c;
22
+ else if (c === "/" && (!result.trim() || /[=(:,!&|?;{[]$/.test(result.trimEnd()) || /\b(return|throw|case)\s*$/.test(result))) state = "regex";
23
+ else { result += c; continue; }
24
+ } else if (state === "block" && c === "*" && next === "/") { state = "code"; result += " "; i += 1; continue; }
25
+ else if (!["line", "block"].includes(state)) {
26
+ if (escaped) escaped = false;
27
+ else if (c === "\\") escaped = true;
28
+ else if (state === "regex") {
29
+ if (c === "[" || c === "]") regexClass = c === "[";
30
+ else if (c === "/" && !regexClass) state = "code";
31
+ } else if (c === state) state = "code";
32
+ }
33
+ result += c === "\n" || c === "\r" ? c : " ";
34
+ }
35
+ return result;
36
+ }
37
+
38
+ function expressionEnd(mask, start, stops) {
39
+ let depth = 0;
40
+ for (let end = start; end < mask.length; end += 1) {
41
+ const c = mask[end];
42
+ if (!depth && stops.includes(c)) return end;
43
+ depth += "([{".includes(c) ? 1 : ")]}".includes(c) ? -1 : 0;
44
+ }
45
+ return mask.length;
46
+ }
47
+ export function mutants(line, mask = codeMask(line)) {
48
+ const result = new Set();
49
+ const replace = (start, end, value) => result.add(line.slice(0, start) + value + line.slice(end));
50
+ const flips = { "<": ">=", ">": "<=", "<=": ">", ">=": "<", "===": "!==", "!==": "===" };
51
+ for (const match of mask.matchAll(/===|!==|<=|>=|<|>|\btrue\b|\bfalse\b/g)) {
52
+ const token = match[0], start = match.index;
53
+ if (flips[token] && (/[<>=!]/.test(mask[start - 1] ?? "") || /[<>=]/.test(mask[start + token.length] ?? ""))) continue;
54
+ replace(start, start + token.length, flips[token] ?? (token === "true" ? "false" : "true"));
55
+ }
56
+ for (const match of mask.matchAll(/\bif\s*\(|\breturn\b/g)) {
57
+ const condition = match[0].startsWith("if"), start = match.index + match[0].length;
58
+ const end = expressionEnd(mask, start, condition ? ")" : ";}\r"), expression = line.slice(start, end).trim();
59
+ if (condition ? end < mask.length : expression && expression !== "undefined") replace(start, end, condition ? `!(${line.slice(start, end)})` : " undefined");
60
+ }
61
+ return [...result];
62
+ }
63
+
64
+ function safePath(root, file) {
65
+ if (!file || path.isAbsolute(file) || /^[A-Za-z]:/.test(file) || file.split(/[\\/]/).some((part) => !part || part === ".." || part === "." || part.toLowerCase() === ".git")) throw new Error(`unsafe mutation path: ${file}`);
66
+ const target = path.resolve(root, file);
67
+ for (let current = target; current !== root; current = path.dirname(current)) if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`unsafe mutation symlink: ${file}`);
68
+ return target;
69
+ }
70
+
71
+ function changedLines(worktree, base, siblings) {
72
+ const untracked = new Set(names(git(worktree, "ls-files", "--others", "--exclude-standard", "-z")));
73
+ const files = new Set([...names(git(worktree, "diff", "--name-only", "-z", "--no-renames", "--diff-filter=d", base, "--")), ...untracked]);
74
+ const result = [];
75
+ for (const file of files) {
76
+ if (!/\.(?:js|mjs|cjs)$/.test(file) || testFile(file)) continue;
77
+ const source = readFileSync(safePath(worktree, file), "utf8");
78
+ const sibling = file.replace(/\.(js|mjs|cjs)$/, ".test.$1");
79
+ if (existsSync(path.join(worktree, sibling))) siblings.push(sibling);
80
+ const lines = source.split("\n"), masks = codeMask(source).split("\n");
81
+ const changed = new Set(untracked.has(file) ? lines.keys() : []);
82
+ if (!untracked.has(file)) {
83
+ const diff = git(worktree, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--unified=0", base, "--", file);
84
+ for (const hunk of diff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) {
85
+ const start = Number(hunk[1]) - 1, count = hunk[2] === undefined ? 1 : Number(hunk[2]);
86
+ for (let i = start; i < start + count; i += 1) changed.add(i);
87
+ }
88
+ }
89
+ for (const i of changed) {
90
+ const variants = mutants(lines[i], masks[i]);
91
+ if (variants.length) result.push({ file, line: i + 1, variants, source, lines });
92
+ }
93
+ }
94
+ return result;
95
+ }
96
+
97
+ /** Mirror dependency directories so workspace symlinks can resolve inside the snapshot. */
98
+ function dependencies(origin, target, relocate, deadline) {
99
+ if (Date.now() >= deadline) throw new Error("dependency snapshot timed out");
100
+ if (lstatSync(target, { throwIfNoEntry: false })) return;
101
+ const stat = lstatSync(origin);
102
+ if (stat.isDirectory()) {
103
+ mkdirSync(target, { recursive: true });
104
+ for (const name of readdirSync(origin)) dependencies(path.join(origin, name), path.join(target, name), relocate, deadline);
105
+ } else if (stat.isSymbolicLink()) {
106
+ const resolved = realpathSync(origin);
107
+ symlinkSync(relocate(resolved), target, lstatSync(resolved).isDirectory() ? "junction" : "file");
108
+ } else copyFileSync(origin, target, constants.COPYFILE_FICLONE);
109
+ }
110
+ function snapshot(worktree, checkout, files, deadline) {
111
+ for (const file of names(git(worktree, "ls-files", "--deleted", "-z"))) rmSync(safePath(checkout, file), cleanup);
112
+ const copies = files.map((file) => ({ source: safePath(worktree, file), destination: safePath(checkout, file) }));
113
+ for (const { source, destination } of copies) {
114
+ if (!lstatSync(source).isFile()) continue;
115
+ mkdirSync(path.dirname(destination), { recursive: true }); copyFileSync(source, destination);
116
+ }
117
+ const relocate = (source) => {
118
+ const relative = path.relative(worktree, source);
119
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) ? path.resolve(checkout, relative) : source;
120
+ };
121
+ const folders = new Set([""]);
122
+ for (const file of files) for (let folder = path.dirname(file); folder !== "."; folder = path.dirname(folder)) folders.add(folder);
123
+ for (const folder of folders) {
124
+ const target = path.join(checkout, folder, "node_modules");
125
+ let origin = path.join(worktree, folder, "node_modules");
126
+ for (let parent = worktree; !folder && !existsSync(origin) && path.dirname(parent) !== parent;) {
127
+ parent = path.dirname(parent); origin = path.join(parent, "node_modules");
128
+ }
129
+ if (!existsSync(origin) || existsSync(target)) continue;
130
+ mkdirSync(path.dirname(safePath(checkout, path.relative(checkout, target))), { recursive: true });
131
+ const resolved = realpathSync(origin), local = relocate(resolved), destination = local === resolved ? target : local;
132
+ if (destination !== checkout) safePath(checkout, path.relative(checkout, destination));
133
+ dependencies(resolved, destination, relocate, deadline);
134
+ if (destination !== target) symlinkSync(destination, target, "junction");
135
+ }
136
+ }
137
+
138
+ function runBounded(command, cwd, deadline) {
139
+ if (Date.now() >= deadline) return Promise.resolve(null);
140
+ return new Promise((resolve, reject) => {
141
+ const env = { ...process.env }; delete env.NODE_TEST_CONTEXT;
142
+ const child = spawnCommand(command[0], command.slice(1), { cwd, env, stdio: "ignore", windowsHide: true, detached: process.platform !== "win32" });
143
+ let timedOut = false;
144
+ const timer = setTimeout(() => {
145
+ timedOut = true;
146
+ if (process.platform === "win32") {
147
+ try { execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }); }
148
+ catch { child.kill("SIGKILL"); }
149
+ } else {
150
+ try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") child.kill("SIGKILL"); }
151
+ }
152
+ }, Math.max(1, deadline - Date.now()));
153
+ child.once("error", (error) => { clearTimeout(timer); reject(error); });
154
+ child.once("close", (status) => { clearTimeout(timer); resolve(timedOut ? null : status ?? 1); });
155
+ });
156
+ }
157
+
158
+ /** Checks a snapshot under one deadline; survivors are advisory and never touch the issue checkout. */
159
+ export async function runMutation({ worktree, base, maxLines = 10, budgetMs = 180000, command, files, say = console.error }) {
160
+ const deadline = Date.now() + budgetMs, empty = { survived: [], skippedLines: 0 };
161
+ let root, checkout, lines = [];
162
+ try {
163
+ worktree = realpathSync(worktree);
164
+ const siblings = [];
165
+ lines = changedLines(worktree, base, siblings);
166
+ if (!lines.length) return empty;
167
+ const allFiles = [...new Set(names(git(worktree, "ls-files", "--cached", "--others", "--exclude-standard", "-z")))].filter((file) => existsSync(path.join(worktree, file)));
168
+ const tests = [...new Set([...(files ?? Object.keys(readLockedTests(worktree) ?? {})), ...siblings])];
169
+ if (!tests.length) { say("mutation: no test file; no mutation coverage"); return empty; }
170
+ for (const file of tests) safePath(worktree, file);
171
+ command ??= load(worktree).tests.command;
172
+ root = mkdtempSync(path.join(os.tmpdir(), "qc-mutation-"));
173
+ checkout = path.join(root, "checkout");
174
+ git(worktree, "worktree", "add", "--detach", checkout, "HEAD");
175
+ snapshot(worktree, checkout, allFiles, deadline);
176
+ const argv = [...command, ...tests.map((file) => path.resolve(checkout, file))], baseline = await runBounded(argv, checkout, deadline);
177
+ if (baseline !== 0) { say(`mutation: baseline ${baseline === null ? "timed out" : "failed"}; no mutation coverage`); return baseline === null ? { ...empty, skippedLines: lines.length } : empty; }
178
+ const survived = []; let completed = 0;
179
+ for (const entry of lines.slice(0, Math.min(10, Math.max(0, maxLines)))) {
180
+ if (Date.now() >= deadline) break;
181
+ const target = safePath(checkout, entry.file);
182
+ let finished = true;
183
+ try {
184
+ for (const mutant of entry.variants) {
185
+ writeFileSync(target, entry.lines.map((line, i) => i === entry.line - 1 ? mutant : line).join("\n"));
186
+ const syntax = await runBounded([process.execPath, "--check", target], checkout, deadline);
187
+ if (syntax !== 0) { finished = false; if (syntax === null) break; continue; }
188
+ const status = await runBounded(argv, checkout, deadline);
189
+ if (status === null) { finished = false; break; }
190
+ if (status === 0) survived.push({ file: entry.file, line: entry.line, mutant });
191
+ }
192
+ } finally { writeFileSync(target, entry.source); }
193
+ if (finished) completed += 1;
194
+ }
195
+ return { survived, skippedLines: lines.length - completed };
196
+ } catch (error) {
197
+ say(`mutation: ${error.message.replace(/[\r\n]+/g, " ")}; no mutation coverage`);
198
+ return { ...empty, skippedLines: Date.now() >= deadline ? lines.length : 0 };
199
+ } finally {
200
+ if (checkout) try { git(worktree, "worktree", "remove", "--force", checkout); }
201
+ finally { rmSync(root, cleanup); }
202
+ }
203
+ }
@@ -0,0 +1,134 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { mutants, runMutation } from "./mutate.mjs";
8
+
9
+ const cleanup = { recursive: true, force: true, maxRetries: 5, retryDelay: 100 };
10
+ function fixture(t, { source = "export const answer = true;\n", testSource = "import './value.mjs';\n" } = {}) {
11
+ const worktree = mkdtempSync(path.join(os.tmpdir(), "qc-mutate-test-"));
12
+ t.after(() => rmSync(worktree, cleanup));
13
+ const git = (...args) => execFileSync("git", args, { cwd: worktree, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
14
+ git("init", "-q");
15
+ git("config", "user.name", "Fixture");
16
+ git("config", "user.email", "fixture@example.test");
17
+ writeFileSync(path.join(worktree, "value.mjs"), "export const answer = false;\n");
18
+ writeFileSync(path.join(worktree, "value.test.mjs"), testSource);
19
+ git("add", ".");
20
+ git("commit", "-qm", "base");
21
+ const base = git("rev-parse", "HEAD");
22
+ writeFileSync(path.join(worktree, "value.mjs"), source);
23
+ return { worktree, base, command: [process.execPath, "--test"], files: ["value.test.mjs"], git };
24
+ }
25
+
26
+ test('mutants of "a < b" holds "a >= b"', () => {
27
+ assert.ok(mutants("a < b").includes("a >= b"));
28
+ });
29
+
30
+ test("a survivor appears when no test covers the line", async (t) => {
31
+ const f = fixture(t);
32
+ assert.deepEqual(await runMutation(f), { survived: [{ file: "value.mjs", line: 1, mutant: "export const answer = false;" }], skippedLines: 0 });
33
+ });
34
+
35
+ test("no survivor when a test fails on the mutant", async (t) => {
36
+ const f = fixture(t, { testSource: "import assert from 'node:assert/strict'; import { answer } from './value.mjs'; assert.equal(answer, true);\n" });
37
+ assert.deepEqual(await runMutation(f), { survived: [], skippedLines: 0 });
38
+ for (const linkDirectory of [false, true]) {
39
+ const linked = fixture(t, { testSource: "import assert from 'node:assert/strict'; import { answer } from 'fixture-bridge/bridge.mjs'; assert.equal(answer, true);\n" });
40
+ mkdirSync(path.join(linked.worktree, "pkg"));
41
+ linked.git("mv", "value.mjs", "pkg/value.mjs");
42
+ mkdirSync(path.join(linked.worktree, "deps"));
43
+ writeFileSync(path.join(linked.worktree, ".git/info/exclude"), "node_modules\ndeps\n");
44
+ const modules = path.join(linked.worktree, linkDirectory ? "deps" : "node_modules");
45
+ mkdirSync(modules, { recursive: true });
46
+ mkdirSync(path.join(modules, "fixture-bridge"));
47
+ writeFileSync(path.join(modules, "fixture-bridge/bridge.mjs"), "export { answer } from 'fixture-value/value.mjs';\n");
48
+ symlinkSync(path.join(linked.worktree, "pkg"), path.join(modules, "fixture-value"), "junction");
49
+ if (linkDirectory) symlinkSync(modules, path.join(linked.worktree, "node_modules"), "junction");
50
+ const diagnostics = [];
51
+ assert.deepEqual(await runMutation({ ...linked, say: (line) => diagnostics.push(line) }), { survived: [], skippedLines: 0 }, "workspace imports must read the mutant checkout");
52
+ assert.deepEqual(diagnostics, [], "workspace baseline must pass");
53
+ }
54
+ for (const locked of [false, true]) {
55
+ const related = fixture(t, { testSource: "import assert from 'node:assert/strict'; import { answer } from './value.mjs'; assert.equal(answer, true);\n" });
56
+ writeFileSync(path.join(related.worktree, "locked.test.mjs"), "import './value.mjs';\n");
57
+ const diagnostics = [];
58
+ assert.deepEqual(await runMutation({ ...related, files: ["locked.test.mjs", ...(locked ? related.files : [])], say: (line) => diagnostics.push(line) }), { survived: [], skippedLines: 0 }, "an unlocked sibling kills the mutant too");
59
+ assert.deepEqual(diagnostics, [], "locked and sibling baseline must pass");
60
+ }
61
+ });
62
+
63
+ test("the run stops at budgetMs and reports how many lines it skipped", async (t) => {
64
+ const snapshot = fixture(t);
65
+ mkdirSync(path.join(snapshot.worktree, "node_modules"));
66
+ writeFileSync(path.join(snapshot.worktree, ".git/info/exclude"), "node_modules\n");
67
+ const diagnostics = [];
68
+ assert.deepEqual(await runMutation({ ...snapshot, budgetMs: 0, say: (line) => diagnostics.push(line) }), { survived: [], skippedLines: 1 });
69
+ assert.match(diagnostics.join("\n"), /timed out/);
70
+ assert.equal(snapshot.git("worktree", "list", "--porcelain").split("worktree ").length, 2);
71
+ const pidFile = path.join(os.tmpdir(), `qc-mutation-child-${process.pid}-${Date.now()}`);
72
+ t.after(() => rmSync(pidFile, cleanup));
73
+ const f = fixture(t, { source: "export const answer = true;\nexport const extra = false;\n", testSource: `import { answer } from './value.mjs'; import { writeFileSync } from 'node:fs'; if (!answer) { writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(() => {}, 1000); }\n` });
74
+ const started = Date.now();
75
+ const result = await runMutation({ ...f, command: [process.execPath], budgetMs: 3000 });
76
+ assert.ok(Date.now() - started < 7000);
77
+ assert.deepEqual(result, { survived: [], skippedLines: 2 });
78
+ assert.ok(existsSync(pidFile), "mutant child reached its blocking code");
79
+ const pid = Number(readFileSync(pidFile, "utf8"));
80
+ assert.throws(() => process.kill(pid, 0), { code: "ESRCH" });
81
+ assert.equal(f.git("worktree", "list", "--porcelain").split("worktree ").length, 2);
82
+ });
83
+
84
+ test("mutants preserve strings, comments and operator boundaries", () => {
85
+ for (const [operator, complement] of [[">", "<="], ["<=", ">"], [">=", "<"], ["===", "!=="], ["!==", "==="]]) assert.ok(mutants(`a ${operator} b`).includes(`a ${complement} b`));
86
+ assert.ok(mutants("if (ready && (a < b)) return true;").includes("if (!(ready && (a < b))) return true;"));
87
+ assert.ok(mutants("return a + b;").includes("return undefined;"));
88
+ for (const source of ['"true < false"', "'a >= b'", "`true < false`", "// return true;", "/* true < false */", "/true|false/", "a => b", "a << b", "a >> b"]) assert.deepEqual(mutants(source), [], source);
89
+ assert.ok(mutants('const x = "true"; return false; // true').includes('const x = "true"; return true; // true'));
90
+ });
91
+
92
+ test("mutation caps changed JavaScript lines and preserves the issue checkout", async (t) => {
93
+ const excluded = fixture(t, { testSource: "process.exit(0);\n" });
94
+ rmSync(path.join(excluded.worktree, "value.mjs"));
95
+ for (const ext of ["ts", "mts", "cts", "tsx", "jsx"]) writeFileSync(path.join(excluded.worktree, `extra.${ext}`), "export const identity = <T>(x: T): T => x;\nexport const extra = true;\n");
96
+ assert.deepEqual(await runMutation(excluded), { survived: [], skippedLines: 0 }, "TypeScript and JSX never enter the line budget");
97
+ for (const ext of ["js", "cjs"]) {
98
+ const included = fixture(t);
99
+ writeFileSync(path.join(included.worktree, `extra.${ext}`), "const extra = true;\n");
100
+ assert.equal((await runMutation(included)).survived.length, 2, ext);
101
+ }
102
+ const broken = fixture(t, { source: "export class Value {\n #true = 1;\n read() { return this.#true; }\n}\n" });
103
+ const original = readFileSync(path.join(broken.worktree, "value.mjs"), "utf8");
104
+ writeFileSync(path.join(broken.worktree, "value.mjs"), original.replace("#true = 1", "#true = 2"));
105
+ broken.git("add", "value.mjs");
106
+ broken.git("commit", "-qm", "private field baseline");
107
+ broken.base = broken.git("rev-parse", "HEAD");
108
+ writeFileSync(path.join(broken.worktree, "value.mjs"), original);
109
+ assert.deepEqual(await runMutation(broken), { survived: [], skippedLines: 1 }, "a syntax-error mutant is skipped");
110
+ const source = Array.from({ length: 12 }, (_, i) => `export const v${i} = true;`).join("\n") + "\n";
111
+ const f = fixture(t, { source });
112
+ writeFileSync(path.join(f.worktree, "extra.ts"), "/*\ntrue < false\n*/\nexport const extra = true;\n");
113
+ writeFileSync(path.join(f.worktree, "ignored.py"), "return True\n");
114
+ f.git("add", "value.mjs");
115
+ const before = f.git("status", "--porcelain=v1");
116
+ const result = await runMutation({ ...f, maxLines: 100 });
117
+ assert.equal(result.survived.length, 10);
118
+ assert.equal(result.skippedLines, 2);
119
+ assert.equal(f.git("status", "--porcelain=v1"), before);
120
+ assert.equal(readFileSync(path.join(f.worktree, "value.mjs"), "utf8"), source);
121
+ assert.equal(f.git("worktree", "list", "--porcelain").split("worktree ").length, 2);
122
+ });
123
+
124
+ test("a failed baseline or missing tests produces one diagnostic and no coverage", async (t) => {
125
+ for (const missing of [false, true]) {
126
+ const f = fixture(t, { testSource: "process.exit(1);\n" });
127
+ if (missing) { rmSync(path.join(f.worktree, "value.test.mjs")); f.files = []; }
128
+ const diagnostics = [];
129
+ assert.deepEqual(await runMutation({ ...f, say: (line) => diagnostics.push(line) }), { survived: [], skippedLines: 0 });
130
+ assert.equal(diagnostics.length, 1);
131
+ assert.match(diagnostics[0], missing ? /no test file/i : /baseline.*fail/i);
132
+ assert.match(diagnostics[0], /no mutation coverage/i);
133
+ }
134
+ });